import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, message, Select } from 'antd';
import { ProduceManageAPI } from '~/api';
import { ProductSkuType, MakeItemEntity } from '../../propsType';
// import { categoryDec } from '@/api/modules/goods';

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

const { Option } = Select;

function AddOrEditProduceModal(props: PropsType) {
  // 父组件传参
  const { visible, closed, data, makeList, decList } = props;
  // 产品类型下拉列表
  const [productTypeSelectList, setProductTypeSelectList] = useState<
    { label: string; val: number }[]
  >([]);
  // 表格事件
  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 getListGoodsTypeList = async (type: number) => {
    const res: any = await ProduceManageAPI.getListGoodsTypeList(type);
    if (res && res.code === '200') {
      const arr = res.result.map((i: { goodsMasterType: string; goodsMasterTypeId: number }) => {
        return {
          label: i.goodsMasterType,
          val: i.goodsMasterTypeId,
        };
      });
      setProductTypeSelectList(arr);
    }
  };
  // 目录修改
  const decSelectChange = (value: number) => {
    form.setFieldValue('goodsTypeId', undefined);
    getListGoodsTypeList(value);
  };
  // componentsDidMounted
  useEffect(() => {
    if (!data) return;
    getListGoodsTypeList(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.sortName}
              </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.val} key={j}>
                {i.label}
              </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;
