import { Button, Form, Input, message, Modal, ModalProps } from 'antd';
import { FC, useState } from 'react';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { listUserApplyTag } from '~/api/interface/customManageType';
import { InterDataType, InterListType } from '~/api/interface';
import { CustomManageAPI, FddInterfaceAPI } from '~/api';
import { useNavigate } from 'react-router-dom';
import { decode } from 'js-base64';
import { uploadContractType } from '~/api/interface/fddInterfaceType';
import { UploadFile } from 'antd/es/upload/interface';
import IframeModal from '~/components/modal/iframeModal';

// 列表类型
type joinType = InterListType<listUserApplyTag>[0];
// 合同返回类型
type contractType = InterDataType<uploadContractType>;

interface selfProps {
  onOk: () => void;
  onCancel: () => void;
  joinItem: joinType | undefined;
}
const ContractModal: FC<ModalProps & selfProps> = ({ open, onOk, onCancel, joinItem }) => {
  const navigate = useNavigate();
  const [contractForm] = Form.useForm<{ contractUrl: string; contractTitle: string }>();
  const [contractFileList, setContractFileList] = useState<UploadFile[]>([]);
  const [contractInfo, setContractInfo] = useState<contractType>();
  const [contractUrl, setContractUrl] = useState<string>('');
  const [iframeModalShow, setIframeModalShow] = useState<boolean>(false);

  const handleOk = () => {
    contractForm
      .validateFields()
      .then(() => {
        if (contractInfo) {
          signContract(contractInfo.contractNo);
        }
      })
      .catch((error: any) => {
        message.warning(error?.errorFields[0]?.errors[0]);
      });
  };
  const handleCancel = () => {
    onCancel();
    contractForm.resetFields();
    setContractFileList([]);
  };

  // 上传合同
  // 合同上传
  const uploadSuccess = (value: any) => {
    contractForm
      .validateFields(['contractTitle'])
      .then((values) => {
        if (joinItem?.orderNo) {
          FddInterfaceAPI.uploadContract({
            docUrl: value[0].url,
            orderNo: joinItem.orderNo,
            port: 1,
            title: values.contractTitle,
          })
            .then(({ result }) => {
              setContractFileList(value);
              contractForm.setFieldValue('contractUrl', value[0].url);
              setContractInfo(result);
            })
            .catch(({ code }) => {
              if (code === '1006' || code === '1005') {
                navigate('/systemManage/realNameAuth');
              }
              setContractFileList([]);
            });
        } else {
          setContractFileList([]);
          message.warning('orderNo不能为空');
        }
      })
      .catch((error: any) => {
        setContractFileList([]);
        message.warning(error?.errorFields[0]?.errors[0]);
      });
  };
  // 签署合同
  const signContract = (contractId: string) => {
    FddInterfaceAPI.signContract({ contractId, port: 1 }).then(({ result }) => {
      if (result) {
        setContractUrl(decode(result));
        setIframeModalShow(true);
      }
    });
  };
  const iframeModalCancel = () => {
    setIframeModalShow(false);
    if (joinItem) {
      CustomManageAPI.editUserApplyTagDetails({
        id: joinItem.id,
      }).then(({ result }) => {
        if (result?.signStatus === 2) {
          contractForm.resetFields();
          setContractFileList([]);
          onOk();
        }
      });
    }
  };
  return (
    <>
      <Modal open={open} onOk={handleOk} onCancel={handleCancel} title='签署合同' okText='签署合同'>
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 15 }} form={contractForm}>
          <Form.Item
            label='合同标题'
            rules={[{ required: true, message: '请输入合同标题' }]}
            name='contractTitle'
          >
            <Input placeholder='请输入合同标题' />
          </Form.Item>
          <Form.Item
            label='合同文件'
            rules={[{ required: true, message: '请上传合同文件' }]}
            name='contractUrl'
          >
            <Uploader
              fileUpload
              fileSize={20}
              listType='text'
              defaultFileList={contractFileList}
              onChange={uploadSuccess}
              fileType={['application/pdf']}
            >
              <Button icon={<UploadOutlined />} type='primary'>
                上传
              </Button>
            </Uploader>
          </Form.Item>
        </Form>
      </Modal>
      <IframeModal
        url={contractUrl}
        title='合同签署'
        open={iframeModalShow}
        onCancel={iframeModalCancel}
      />
    </>
  );
};
export default ContractModal;
