import { FC, useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import { ModalProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { InterDataType, InterReqType } from '~/api/interface';
import { categoryListType } from '~/api/interface/categoryManage';
import { addServiceType, serviceType } from '~/api/interface/mallManageType';
import { MallManageAPI, SystemManageAPI } from '~/api';
import { listCompanyPage } from '~/api/interface/systemManageType';

//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];
//服务返回类型
type serviceListType = InterDataType<serviceType>['list'];
//单位返回类型
type companyType = InterDataType<listCompanyPage>['list'];

interface selfProps {
  industryCategoryList: categoryType;
  applicationCategoryList: categoryType;
  handleOk: () => void;
  handleCancel: () => void;
  currentServiceData: serviceListType[0] | undefined;
}
//新增服务参数类型
type addServiceParametersType = InterReqType<addServiceType>;

const AddOrEditServiceModal: FC<ModalProps & selfProps> = ({
  open,
  title,
  handleCancel,
  handleOk,
  industryCategoryList,
  applicationCategoryList,
  currentServiceData,
}) => {
  const [form] = Form.useForm<addServiceParametersType>();
  //封面图文件
  const [coverPlanFileList, setCoverPlanFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //分享卡片文件
  const [shareCardFileList, setShareCardFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //视频上传文件
  const [videoFileList, setVideoFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //单位列表
  const [companyList, setCompanyList] = useState<companyType>([]);

  //封面图上传成功
  const coverPlanUploadSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    form.setFieldsValue({
      coverPlan: fileList[0].url,
    });
    setCoverPlanFileList(fileList);
  };
  //分享卡片上传成功
  const shareCardUploadSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    form.setFieldsValue({
      shareCard: fileList[0].url,
    });
    setShareCardFileList(fileList);
  };
  //视频上传成功
  const videoUploadSuccess = (
    fileList: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    form.setFieldsValue({
      video: fileList[0].url,
    });
    setVideoFileList(fileList);
  };
  const onOk = () => {
    form.validateFields().then((value: any) => {
      MallManageAPI[currentServiceData ? 'editService' : 'addService']({
        id: currentServiceData ? currentServiceData.id : undefined,
        ...value,
      }).then(({ code }) => {
        if (code === '200') {
          message.success(currentServiceData ? '编辑服务成功' : '新增服务成功');
          form.resetFields();
          setCoverPlanFileList([]);
          setVideoFileList([]);
          setShareCardFileList([]);
          handleOk();
        }
      });
    });
  };
  const onCancel = () => {
    form.resetFields();
    setCoverPlanFileList([]);
    setVideoFileList([]);
    setShareCardFileList([]);
    handleCancel();
  };
  //获取单位列表
  const getCompanyList = () => {
    SystemManageAPI.listCompanyPage({ pageNo: 1, pageSize: 99999 }).then(({ result }) => {
      setCompanyList(result.list);
    });
  };
  useEffect(() => {
    getCompanyList();
  }, []);
  useEffect(() => {
    if (currentServiceData) {
      form.setFieldsValue({
        serviceName: currentServiceData.serviceName,
        applicationId: currentServiceData.applicationId,
        industryId: currentServiceData.industryId,
        coverPlan: currentServiceData.coverPlan,
        shareCard: currentServiceData.shareCard || undefined,
        video: currentServiceData.video || undefined,
        displayState: currentServiceData.displayState,
        companyId: currentServiceData.companyId,
      });
      setCoverPlanFileList([
        {
          id: Math.random(),
          uid: Math.random(),
          url: currentServiceData.coverPlan,
          name: 'coverPlan',
        },
      ]);
      if (currentServiceData.shareCard) {
        setShareCardFileList([
          {
            id: Math.random(),
            uid: Math.random(),
            url: currentServiceData.shareCard,
            name: 'shareCard',
          },
        ]);
      }
      if (currentServiceData.video) {
        setVideoFileList([
          {
            id: Math.random(),
            uid: Math.random(),
            url: currentServiceData.video,
            name: 'shareCard',
          },
        ]);
      }
    }
  }, [currentServiceData]);

  return (
    <Modal open={open} title={title} onCancel={onCancel} onOk={onOk}>
      <Form
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        form={form}
        initialValues={{ displayState: 0 }}
      >
        <Form.Item
          label='服务名称'
          name='serviceName'
          rules={[{ required: true, message: '请输入服务名称' }]}
        >
          <Input placeholder='请输入服务名称' maxLength={30} />
        </Form.Item>
        <Form.Item
          label='应用'
          name='applicationId'
          rules={[{ required: true, message: '请选择应用' }]}
        >
          <Select placeholder='请选择应用'>
            {applicationCategoryList.map((v) => (
              <Select.Option key={v.id} value={v.id}>
                {v.classifyName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='对应行业'
          name='industryId'
          rules={[{ required: true, message: '请选择对应行业' }]}
        >
          <Select placeholder='请选择对应行业'>
            {industryCategoryList.map((v) => (
              <Select.Option value={v.id} key={v.id}>
                {v.classifyName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='所属单位'
          name='companyId'
          rules={[{ required: true, message: '请选择所属单位' }]}
        >
          <Select
            placeholder='请选择所属单位'
            filterOption={(input, option) =>
              (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
            showSearch
          >
            {companyList.map((v) => (
              <Select.Option value={v.id} key={v.id}>
                {v.companyName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='封面图'
          name='coverPlan'
          rules={[{ required: true, message: '请上传封面图' }]}
        >
          <Uploader
            listType='picture-card'
            fileUpload
            onChange={coverPlanUploadSuccess}
            defaultFileList={coverPlanFileList}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='分享卡片' name='shareCard'>
          <Uploader
            listType='picture-card'
            fileUpload
            onChange={shareCardUploadSuccess}
            defaultFileList={shareCardFileList}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item label='视频' name='video'>
          <Uploader
            listType='text'
            fileUpload
            onChange={videoUploadSuccess}
            fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
            defaultFileList={videoFileList}
            fileSize={50}
          >
            <Button icon={<UploadOutlined />} size='small' type='primary'>
              上传
            </Button>
          </Uploader>
        </Form.Item>
        <Form.Item label='展示状态' name='displayState'>
          <Select placeholder='请选择展示状态'>
            <Select.Option value={0}>上架</Select.Option>
            <Select.Option value={1}>下架</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditServiceModal;
