import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { industryListPagesType, inspectionInsertType } from '~/api/interface/categoryManage';
import { PlusOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { CategoryManageAPI } from '~/api';

// 列表的类型
type TableType = InterListType<industryListPagesType>;
// 表单参数
type ReqType = InterReqType<inspectionInsertType>;
// 参数类型
interface selfProps {
  id: number;
  data?: TableType[0]['inspectionDTOS'][0];
  onCancel: () => void;
}

const AddEditChildrenView: React.FC<ModalProps & selfProps> = ({
  id,
  open,
  title,
  onCancel,
  data,
}) => {
  // 表格数据类型
  const [form] = Form.useForm<ReqType>();
  // 关闭事件
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };
  // 确定事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        // console.log('表单验证 --->', values);
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交数据
  const handleSubmit = async (values: ReqType) => {
    const res = await CategoryManageAPI[data?.id ? 'inspectionUpdate' : 'inspectionInsert']({
      ...values,
      id: data?.id || undefined,
      industryTypeId: data?.id ? data?.industryTypeId : id,
      caseImg: values?.caseImg
        ? JSON.stringify((values?.caseImg as any).map((i: { url: string }) => ({ fileUrl: i.url })))
        : undefined,
      saleState: 1,
    });
    if (res && res.code === '200') {
      message.success('操作成功').then();
      handleCancel();
    }
  };
  // 获取图片
  const getImgParse = (text: string) => {
    try {
      return JSON.parse(text)?.map((i: { fileUrl: string }) => ({ url: i.fileUrl }));
    } catch (e) {
      return [{ url: text }];
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue({
      ...data,
      caseImg: getImgParse(data?.caseImg),
    });
  }, [open]);
  return (
    <Modal title={title} open={open} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form form={form} labelAlign='right' labelCol={{ span: 5 }} wrapperCol={{ span: 10 }}>
        <Form.Item
          label='分类名称'
          name='inspectionName'
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input placeholder='请输入分类名称' maxLength={6} allowClear />
        </Form.Item>
        <Form.Item
          label='分类图标'
          name='inspectionImg'
          rules={[{ required: true, message: '请上传分类图标' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) =>
              form.setFieldValue('inspectionImg', e.at(0) ? e.at(0)?.url : undefined)
            }
            defaultFileList={data?.inspectionImg ? [{ url: data?.inspectionImg }] : []}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='分类描述'
          name='inspectionDescription'
          rules={[{ required: true, message: '请输入分类描述' }]}
        >
          <Input placeholder='请输入分类描述' maxLength={25} allowClear />
        </Form.Item>
        <Form.Item
          label='服务编号'
          name='inspectionNo'
          rules={[{ required: true, message: '请输入服务编号' }]}
        >
          <Input placeholder='请输入服务编号' maxLength={15} allowClear />
        </Form.Item>
        <Form.Item
          label='业务案例图片'
          name='caseImg'
          rules={[{ required: true, message: '请上传业务案例图片' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={4}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) => form.setFieldValue('caseImg', e?.length ? e : undefined)}
            defaultFileList={data?.caseImg ? getImgParse(data?.caseImg as any) : []}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='业务案例视频'
          name='caseVideo'
          rules={[{ required: false, message: '请上传业务案例视频' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['video/mp4', 'video/wmv', 'video/avi', 'video/mov', 'video/flv']}
            onChange={(e) => form.setFieldValue('caseVideo', e.at(0) ? e.at(0)?.url : undefined)}
            defaultFileList={data?.caseVideo ? [{ url: data?.caseVideo }] : []}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditChildrenView;
