import { Modal, Table, Space, Divider, message } from 'antd';
import { useRequest, useModel } from '@umijs/max';
import { queryContractDraft } from '@/services/contract';
import { queryDelDraft } from '../../../services/contract';
import { useEffect } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const DraftModal = ({ open, onCancel, onOk }) => {
  const [modal, contextHolder] = Modal.useModal();
  const columns = [
    {
      title: '合同名称',
      dataIndex: 'name',
      key: 'name',
      width: 100,
    },
    {
      title: '操作',
      width: '40%',
      align: 'center',
      render: (record) => {
        return (
          <Space>
            <a onClick={() => handlerOk(record)}>打开</a>
            <a onClick={() => handleDel(record.id)}>删除</a>
          </Space>
        );
      },
    },
  ];

  const handleDel = (id) => {
    modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: '提示：',
      content: <div>确定删除草稿！</div>,
      onOk: () => runDel({ id }),
    });
  };

  useEffect(() => {
    if (open) runList();
  }, [open]);

  const {
    data,
    loading,
    run: runList,
  } = useRequest(queryContractDraft, {
    formatResult: (res) => {
      if (res?.data) {
        return res.data?.list;
      }
    },
  });

  const { run: runDel } = useRequest(queryDelDraft, {
    manual: true,
    onSuccess: (res) => {
      message.success('删除成功');
      runList();
    },
  });

  const handlerOk = (record) => {
    const data = JSON.parse(record.content);
    onOk(data);
  };

  return (
    <Modal
      title="草稿箱"
      open={open}
      footer={null}
      onCancel={onCancel}
      onOk={onOk}
      width={700}
    >
      <Table
        dataSource={data}
        columns={columns}
        loading={loading}
        pagination={false}
      />
      {contextHolder}
    </Modal>
  );
};

export default DraftModal;
