// 审批详情
import React, { useState, useMemo, useEffect } from 'react';
import { Steps, Button, Tooltip, message, Spin } from 'antd';
import { useParams, useRequest, useModel, useLocation } from 'umi';
import AuditModal from './components/AuditModal';
import FormAndFilesNode from './components/FormAndFilesNode';
import { queryAuditDetail, updateAuditList } from '@/services/boom';
import { queryGetContractList } from '@/services/contract';
import PageContent from '@/components/PageContent';
import SignModal from './components/SignModal';
import ContractDetail from '../ContractManager/detail';
import { Type } from '../Profile';
import { queryContractDetail } from '../../services/contract';

function OaAuditDetail() {
  const {
    initialState: { user },
  } = useModel('@@initialState');

  const [auditVisible, setAuditVisible] = useState(false);
  const location = useLocation();
  const {
    state: { id, type, code },
  } = location;
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    if (type == Type.CON) runCon({ code });
  }, [type]);

  const { data, loading, refresh } = useRequest(queryAuditDetail, {
    defaultParams: [{ id }],
  });
  const {
    current_seq,
    form,
    OaAuditList,
    Files = [],
    audit_status,
    AuditorInfo,
  } = data || {};
  // if (OaAuditList) console.log(JSON.stringify(OaAuditList));

  //请求列表
  const {
    data: conData,
    run: runCon,
    loading: conLoading,
  } = useRequest((data) => queryContractDetail(data), {
    manual: true,
    formatResult: (res) => {
      return res?.data?.detail;
    },
    onSuccess: (res) => {},
  });
  // console.log(conData);

  const getDescription = (node) => {
    let str = node?.AuditRoleInfo
      ? `审批人：${node?.AuditRoleInfo.Name || '-'}`
      : `审批人：${node?.AuditorUser.CName || '-'}`;
    if (node.desc) {
      return (
        <div>
          {str}
          <div>
            <Tooltip title={node.desc}>
              <span style={{ color: '#1A73E8', textDecoration: 'undeline' }}>
                审批意见
              </span>
            </Tooltip>
          </div>
        </div>
      );
    }
    return str;
  };
  const updateRes = useRequest(
    (values) => {
      let list = OaAuditList.map((item) => item.auditor);
      if (values.type == 'before') {
        list.splice(current_seq - 1, 0, values.approver);
      } else {
        list.splice(current_seq, 0, values.approver);
      }
      return updateAuditList(
        {
          oa_id: Number(id),
          audit_list: list,
        },
        values.type == 'after',
      );
    },
    {
      manual: true,
      onSuccess() {
        message.success('加签成功');
        setVisible(false);
        refresh();
      },
    },
  );

  const btns = useMemo(() => {
    if (!user || !data) return;
    if (
      user.ID == AuditorInfo?.ID &&
      // 0 待审核； 1  上级审批通过
      (audit_status === 0 || audit_status === 1)
    ) {
      return [
        <Button
          key={1}
          style={{ marginRight: 10 }}
          type="primary"
          onClick={() => setAuditVisible(1)}
        >
          审批通过
        </Button>,
        <Button key={2} onClick={() => setAuditVisible(2)} danger>
          审批拒绝
        </Button>,
        <Button key={3} onClick={() => setVisible(true)}>
          加签
        </Button>,
      ];
    }
    return [];
  }, [user, data]);

  return (
    <PageContent extra={btns} loading={loading && conLoading}>
      <Steps
        style={{ marginBottom: 20 }}
        current={audit_status == 3 ? OaAuditList?.length : current_seq - 1}
        status={audit_status == 2 ? 'error' : 'process'}
        items={OaAuditList?.map((item) => ({
          title: item.seq_name,
          description: getDescription(item),
        }))}
      ></Steps>
      {type == Type.OA ? (
        <FormAndFilesNode formData={form} fileList={Files} />
      ) : (
        <ContractDetail data={conData} />
      )}

      <AuditModal
        id={id}
        visible={auditVisible}
        onClose={() => setAuditVisible(false)}
        onOk={refresh}
      />
      <SignModal
        visible={visible}
        onCancel={() => setVisible(false)}
        onCreate={(values) => updateRes.run(values)}
        loading={updateRes.loading}
      />
    </PageContent>
  );
}

export default OaAuditDetail;
