import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, message, Select } from 'antd';
import { CategoryManageAPI, ProduceManageAPI } from '~/api';
import { ProductSkuType, MakeItemEntity } from '../../propsType';
import { InterDataType } from '~/api/interface';
import { categoryListType, directoryListType } from '~/api/interface/categoryManage';

//目录返回类型
type directoryType = InterDataType<directoryListType>;
//分类返回类型
type categoryType = InterDataType<categoryListType>['list'];

interface PropsType {
  visible: boolean;
  closed: any;
  data: ProductSkuType | undefined;
  makeList: MakeItemEntity[];
  decList: directoryType;
}

const { Option } = Select;

function AddOrEditProduceModal(props: PropsType) {
  // 父组件传参
  const { visible, closed, data, makeList, decList } = props;
  // 产品类型下拉列表
  const [productTypeSelectList, setProductTypeSelectList] = useState<categoryType>([]);
  // 表格事件
  const [form] = Form.useForm();
  // 关闭弹窗
  const handleClosed = async () => {
    form.resetFields();
    closed();
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then(async (values) => {
        const obj = { ...data, ...values };
        const res: any = await ProduceManageAPI[!obj.id ? 'addProductSku' : 'editProductSku'](obj);
        if (res && res.code === '200') {
          message.success('操作成功');
          await handleClosed();
        } else {
          message.warning(res.message);
        }
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };
  //根据目录获取分类
  const getCategoryListByDirectory = (directoryId: number) => {
    CategoryManageAPI.getCategoryList({ pageNo: 1, pageSize: 99999, directoryId, type: 4 }).then(
      ({ result }) => {
        setProductTypeSelectList(result.list || []);
      },
    );
  };
  // 目录修改
  const decSelectChange = (value: number) => {
    form.setFieldValue('goodsTypeId', undefined);
    getCategoryListByDirectory(value);
  };
  // componentsDidMounted
  useEffect(() => {
    if (!data) return;
    getCategoryListByDirectory(data.directoryId);
    form.setFieldsValue({
      ...data,
    });
  }, [data]);
  return (
    <Modal
      open={visible}
      title={data?.id ? '编辑' : '新增'}
      onCancel={handleClosed}
      onOk={handleSubmit}
      destroyOnClose
      width={768}
    >
      <Form
        name='form'
        form={form}
        layout='horizontal'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
      >
        <Form.Item
          name='productName'
          label='产品名称'
          rules={[{ required: true, message: '请输入产品名称' }]}
        >
          <Input placeholder='请输入产品名称' allowClear maxLength={30} />
        </Form.Item>
        <Form.Item
          label='产品目录'
          name='directoryId'
          rules={[{ required: true, message: '请选择产品目录' }]}
        >
          <Select placeholder='请选择产品目录' onChange={decSelectChange}>
            {decList.map((v: any, index: number) => (
              <Select.Option value={v.id} key={index}>
                {v.directoryName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name='goodsTypeId'
          label='产品类型'
          rules={[{ required: true, message: '请选择产品类型' }]}
        >
          <Select
            placeholder='请选择产品类型'
            allowClear
            showSearch
            filterOption={(input, option) =>
              (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
          >
            {productTypeSelectList.map((i, j) => (
              <Option value={i.id} key={j}>
                {i.classifyName}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name='model'
          label='产品型号'
          rules={[{ required: false, message: '请输入产品型号' }]}
        >
          <Input placeholder='请输入产品型号' allowClear maxLength={50} />
        </Form.Item>
        <Form.Item
          name='productBrandId'
          label='产品品牌'
          rules={[{ required: false, message: '请选择产品品牌' }]}
        >
          <Select
            filterOption={(input, option) =>
              (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
            showSearch
            placeholder='请选择产品品牌'
          >
            {makeList.map((v) => (
              <Select.Option value={v.id} key={v.id}>
                {v.brandName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
}
export default AddOrEditProduceModal;
