import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterDataType, InterReqType } from '~/api/interface';
import { getCompanyInfoByIdType } from '~/api/interface/systemManageType';
import { UploadOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { getBusinessCaseType, updateBusinessCaseType } from '~/api/interface/customManageType';
import { CustomManageAPI } from '~/api';

// 店铺类型
type DetailType = InterDataType<getCompanyInfoByIdType>;
// 请求类型
type ReqType = InterReqType<updateBusinessCaseType>;
// 列表类型
type DataType = InterDataType<getBusinessCaseType>[0];

const AddSolutionModal: React.FC<
  ModalProps & { detail: DetailType; onCancel?: () => void; data?: DataType }
> = ({ open, title, onCancel, data }) => {
  // 表单数据
  const [form] = Form.useForm<ReqType & { businessVideo: { url: string }[] }>();
  // 取消事件
  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };
  // 确定事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        // console.log('确定事件 --->', err);
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType & { businessVideo: { url: string }[] }) => {
    const res = await CustomManageAPI.updateBusinessCase({
      businessDescription: values?.businessDescription,
      businessVideo: values?.businessVideo?.[0]?.url,
      id: data?.id,
    });
    if (res && res.code === '200') {
      message.success({ content: '操作成功' });
      handleCancel();
      // console.log('提交事件 --->', values);
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!data?.id) return;
    form.setFieldsValue({
      ...data,
      businessVideo: [{ url: data?.businessVideo }],
    });
  }, [data]);
  return (
    <Modal open={open} title={title} width={450} onCancel={handleCancel} onOk={handleOk}>
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }}>
        <Form.Item
          label='案例说明'
          name='businessDescription'
          rules={[{ required: true, message: '请输入案例说明' }]}
        >
          <Input.TextArea placeholder={'请输入案例说明'} maxLength={100} allowClear showCount />
        </Form.Item>
        <Form.Item
          label='案例视频'
          name='businessVideo'
          rules={[{ required: true, message: '请输入案例视频' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            fileLength={1}
            fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
            fileSize={100}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddSolutionModal;
