/**
 * 审核按钮封装
 * 徐立
 * 2020-3-28
 * data 为 'affair/getIdFormDetail' 接口请求到的数据
 * callback 提交完成后执行回调函数
 * form form表单控件
 */
import React, { useState } from 'react';
import { Modal, message } from 'antd';
import { preHandle } from '@/webPublic/one_stop_public/utils/myutils';
import { connect } from 'dva';
import Btn from './pagesBtn';
import styles from './styles.less';
import ModalDiy from '@/baseComponent/ModalDiy';
import { callbackSubmitData } from '@/webPublic/one_stop_public/models/callbackExamineProcess';
import { getToken } from '@/utils/authority';
import { isJSON } from '@/webPublic/zyd_public/utils/utils';
import { uaaRequest } from '@/webPublic/one_stop_public/utils/request';
import AuditProcessOneByOne
  from '@/webPublic/FormInsertDiy/AuditButton/pagesBtn/AuditProcessOneByOne';

function AuditButton(props) {
  const [visible, setVisible] = useState(false);
  const [modalContent, setModalContent] = useState('');
  const [isSubmitLoading, setSubmitLoading] = useState(false);
  const [affairOkParams, setAffairParams] = useState({});
  const [showProcessModal, setShowProcessModal] = useState(false); // 增加进度条 1条数据1条数据的调用接口
  const { callback } = props;

  function affairOk() {
    // 有taskIds属性时，是批量审核，
    const {
      dispatch,
      data,
      form,
      taskIds,
      selectRows
    } = props;
    const {
      oldKey,
      btnValue
    } = affairOkParams;
    if (window.stuSigningAuditXueShengChu && btnValue === '0') {
      // 黔南就业学生处批量审批签章 特殊处理 专门为黔南签章批量审核搞的函数
      // 应该是点击同意才执行这个全局函数.
      window.stuSigningAuditXueShengChu({
        userNowInfo: (isJSON(localStorage.getItem('user')) && JSON.parse(localStorage.getItem('user'))) || {},
        buttonInfo: data?.btns && data?.btns.length ? data?.btns.find((x) => x.value === btnValue) : {},
        token: getToken(),
        selectRows,
        taskIds: taskIds || [data.taskId], // 接口里面的taskId 任务Id
        examineMap: JSON.stringify({
          [oldKey]: btnValue, // 每个配置按钮对应的对象内容 oldkey = 接口中 key btnValue = 接口中 value
          // reason: value, // 审批理由
          code: taskIds ? undefined : data.code,
          reason: form.getFieldsValue()?.reason
        }),
        code: taskIds ? undefined : data.code,
        message,
        Modal,
        uaaRequest,
        callback,
        setVisible,
        setSubmitLoading,
        remark: {
          setVisible: '关闭弹窗的方法',
          setSubmitLoading: '显示为加载中',
          path: ' 代码在学工的这里面 src/webPublic/FormInsertDiy/AuditButton/index.js',
          message: '蚂蚁金服的message 用来展示进度条.  不懂问我',
          Modal: '蚂蚁金服的Modal  用来提示审核已完成',
          callback: '执行完了的回调函数',
          else: '其他参数打印出来自己看看',
          uaaRequest: '调一站式的接口的方法'
        }
      });
      return true;
    }

    let buttonInfo = data?.btns && data?.btns.length ? data?.btns.find((x) => x.value === btnValue) : {};
    const submitValues = (values) => {
      setSubmitLoading(true);
      preHandle(values);
      let payload = {
        // 批量 和 单个审批 都用这段代码
        taskIds: taskIds || [data.taskId], // 接口里面的taskId 任务Id
        code: taskIds ? undefined : data.code,
        // 审核相关内容
        examineMap: JSON.stringify({
          [oldKey]: btnValue, // 每个配置按钮对应的对象内容 oldkey = 接口中 key btnValue = 接口中 value
          // reason: value, // 审批理由
          code: taskIds ? undefined : data.code
        }),
        taskForm: JSON.stringify(values), // 审批表单的参数值
        apiData: data,
        taskFormKey: data?.taskFormKey,
        userNowInfo:
          (isJSON(localStorage.getItem('user')) && JSON.parse(localStorage.getItem('user'))) || {},
        buttonInfo,
        token: getToken()
      };
      payload = callbackSubmitData(payload);
      setVisible(false);
      setShowProcessModal(payload);
      return false;
      // dispatch({
      //   type: 'affair/getExamineProcess',
      //   payload,
      //   callback: (val) => {
      //     setSubmitLoading(false);
      //     setVisible(false);
      //     if (callback) {
      //       callback(val);
      //     }
      //   }
      // });
    };
    // console.log(buttonInfo);
    if (buttonInfo?.isValidateForm === false) {
      submitValues(form.getFieldsValue());
    } else {
      form.validateFieldsAndScroll((err, values) => {
        if (err) return;
        submitValues(values);
      });
    }

  }

  function hideModal() {
    setVisible(false);
  }

  /**
   * 根据不同值,返回对应样式
   */
  function getStyle(key, value) {
    if (key === 'examine') {
      switch (value) {
        case 1:
          return [`${styles.btn_margin}`, `${styles.btn}`, `${styles.btn_reject}`].join(' ');
        case 2:
          return [`${styles.btn_margin}`, `${styles.btn}`, `${styles.btn_no}`].join(' ');
        case 0:
          return 'deafalut';
        case '1':
          return [`${styles.btn_margin}`, `${styles.btn}`, `${styles.btn_reject}`].join(' ');
        case '2':
          return [`${styles.btn_margin}`, `${styles.btn}`, `${styles.btn_no}`].join(' ');
        case '0':
          return 'deafalut';
        default:
          return 'deafalut';
      }
    } else {
      return 'deafalut';
    }
  }

  function showModal(str, key, value) {
    const {
      data,
      form
    } = props;
    const buttonInfo = data?.btns && data?.btns.length ? data?.btns.find((x) => x.value === value) : {};
    const values = form.getFieldsValue();
    if (buttonInfo?.documentation) {
      let needAuditInfo = isJSON(buttonInfo.documentation) && JSON.parse(buttonInfo.documentation)?.needAuditInfo;
      if (needAuditInfo && !values.reason) {
        message.warning('请输入审批理由');
        return;
      }
    }
    setModalContent(`确定${str}吗？`);
    setAffairParams({
      oldKey: key,
      btnValue: value
    });
    setVisible(true);
  }

  const {
    data: {
      isHandle,
      btns
    }
  } = props;
  if (!isHandle || !Array.isArray(btns) || btns.length < 1) return null;
  return (
    <>
      <div className={styles.btn_page}>
        {btns.map((item) => (
          <Btn
            get="8"
            key={item.value}
            btnOne={() => {
              showModal(item.name, item.key, item.value);
              // console.log('显示了哦');
              setSubmitLoading(false);
            }}
            text={item.name}
            style={getStyle(item.key, item.value)}
          />
        ))}
      </div>
      <ModalDiy
        visible={visible}
        title="提示"
        handleCancel={hideModal}
        handleOk={affairOk}
        confirmLoading={isSubmitLoading}>
        <div style={{
          fontSize: '16px',
          textAlign: 'center',
          height: 150,
          lineHeight: '150px'
        }}>
          {modalContent}
        </div>
      </ModalDiy>
      {
        showProcessModal &&
        <AuditProcessOneByOne payloadData={showProcessModal}
                              callBack={callback}
                              setShowProcessModal={setShowProcessModal}
        />
      }

    </>
  );
}

export default connect()(AuditButton);
