import React, { useEffect } from 'react';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { releaseTenderNewsUpdate, releaseTenderNews } from '~/api/interface/resourceManageType';
import { ResourceManageAPI } from '~/api';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '~/utils/uploadFile';

// 列表的类型
type TableType = InterListType<releaseTenderNews>;
// 请求的表单类型
type ReqType = InterReqType<releaseTenderNewsUpdate>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}

const AddEditModal: React.FC<propType> = (props) => {
  AddEditModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data } = props;
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values as ReqType & { file: any[] });
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType & { file: any[] }) => {
    // 上传文件
    const filePath = await uploadFile(values?.file?.at(-1));
    // 新建formData
    const formData = new FormData();
    formData.append('file', values?.file?.at(-1));
    const blob = new Blob(
      [
        JSON.stringify({
          ...values,
          id: data?.id ? data?.id : null,
          url: filePath ? filePath : null,
        }),
      ],
      {
        type: 'application/json',
      },
    );
    formData.append('tenderNewsVO', blob);
    const res = await ResourceManageAPI[
      data?.id ? 'releaseTenderNewsUpdate' : 'releaseTenderNewsAdd'
    ](formData);
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form
        name='Form'
        form={form}
        labelAlign='right'
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='招标快讯名称'
          name='tenderName'
          rules={[{ required: true, message: '请输入名称' }]}
        >
          <Input placeholder={'请输入名称'} maxLength={20} allowClear />
        </Form.Item>
        <Form.Item
          label='状态'
          name='using'
          rules={[{ required: true, message: '请选择状态' }]}
          initialValue={1}
        >
          <Select
            placeholder={'请选择状态'}
            options={[
              { label: '上架', value: 1 },
              { label: '下架', value: 0 },
            ]}
            allowClear
          />
        </Form.Item>
        <Form.Item
          label='上传内容'
          name='file'
          rules={[{ required: !data?.id, message: '请上传内容' }]}
        >
          <Uploader
            listType={'text'}
            fileUpload={false}
            fileType={[
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
              'application/vnd.ms-excel',
            ]}
            onChange={(e) => {
              form.setFieldValue('file', e);
            }}
            defaultFileList={data?.url ? [{ url: data?.url }] : []}
          >
            <Button icon={<UploadOutlined />} type={'primary'}>
              上传
            </Button>
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
