import React, { useEffect, useState } from 'react';
import { Modal, Form, Select, Input, message, Button, ModalProps } from 'antd';
import { InterDataType } from '~/api/interface';
import { cooperationTagType } from '~/api/interface/produceManageType';
import { customizeEntity } from '~/api/interface/goodsType';
import { filterObjAttr } from '~/utils';

//加盟标签返回类型
type cooperationTagResponseType = InterDataType<cooperationTagType>;
interface selfProps {
  handleOk: (specPrice: any, leaseTerm: number) => void;
  handleCancel: () => void;
  customRowData: Partial<customizeEntity>;
  tagInfoList: cooperationTagResponseType;
  goodsType: number;
}

const ConfigurePriceModal: React.FC<ModalProps & selfProps> = ({
  open,
  handleOk,
  handleCancel,
  customRowData,
  tagInfoList,
  goodsType,
}) => {
  // 选择的列表
  const [selectList, setSelectList] = useState<number[]>([]);

  // 配置价格Form
  const [cfgPriceForm] = Form.useForm<any>();
  const deselectEvent = (id: number) => {
    const obj: any = {};
    obj[id] = undefined;
    cfgPriceForm.setFieldsValue(obj);
    const numArr: number[] = selectList.filter((i: number) => i !== id);
    setSelectList([...numArr]);
  };
  const levelSelectEvent = (id: number) => {
    selectList.push(id);
    setSelectList([...selectList]);
  };
  // 将val转换为label
  const transValtoLabel = (id: number) => {
    const item = tagInfoList.find((i) => i.id === id);
    return item ? item.tagName : id;
  };
  // 表单验证
  const handleSubmit = async () => {
    cfgPriceForm
      .validateFields()
      .then(async (values) => {
        const specPrice = Object.keys(filterObjAttr(values, ['leaseTerm'])).reduce(
          (pre: any, cur: string) => {
            if (Object.keys(customRowData.productSpecCPQVO).length != 0) {
              const priceItem: any = customRowData.productSpecCPQVO.specPrice.find(
                (i: any) => i.cooperationTag === Number(cur),
              );
              pre.push({
                id: priceItem?.id,
                price: values[cur],
                cooperationTag: cur,
              });
            } else {
              pre.push({ price: values[cur], cooperationTag: cur });
            }
            return pre;
          },
          [],
        );
        handleOk([...specPrice], values.leaseTerm);
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };
  const handleCancelEvent = () => {
    cfgPriceForm.resetFields();
    handleCancel();
  };
  // 价格正则
  const priceValidator = (_rule: any, value: any) => {
    const regExp = /^[1-9]\d{0,7}(\.\d{1,2})?$|^0(\.\d{1,2})?$/;
    const bol: boolean = regExp.test(value);
    if (!value) {
      return Promise.reject(new Error('请输入定价金额'));
    }
    if (!bol) {
      return Promise.reject(
        new Error('金额应为数字,小数最多两位,整数最多八位,不能输入0开头的整数'),
      );
    }
    return Promise.resolve();
  };

  useEffect(() => {
    // 新增规格则清空表单数据
    if (Object.keys(customRowData.productSpecCPQVO).length === 0) {
      cfgPriceForm.resetFields();
      setSelectList([]);
    } else {
      cfgPriceForm.setFieldValue('leaseTerm', customRowData.productSpecCPQVO.leaseTerm);
      const ids: number[] = [];
      customRowData.productSpecCPQVO.specPrice.map((item: any) => {
        cfgPriceForm.setFieldValue(Number(item.cooperationTag), item.price);
        if (item.cooperationTag != '0') {
          ids.push(Number(item.cooperationTag));
        }
        setSelectList(ids);
      });
    }
  }, [customRowData]);

  return (
    <Modal
      title='配置价格'
      open={open}
      onCancel={handleCancelEvent}
      zIndex={1009}
      footer={[
        <Button key={1} type='default' onClick={handleCancelEvent}>
          取消
        </Button>,
        <Button key={2} type='primary' onClick={handleSubmit}>
          确认
        </Button>,
      ]}
    >
      <Form
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 14 }}
        form={cfgPriceForm}
        initialValues={{ leaseTerm: 0 }}
      >
        {goodsType === 1 && (
          <Form.Item
            label='租期'
            name='leaseTerm'
            rules={[{ required: true, message: '请选择租期' }]}
          >
            <Select>
              <Select.Option value={0}>1-7天</Select.Option>
              <Select.Option value={1}>8-15天</Select.Option>
              <Select.Option value={2}>16-30天</Select.Option>
              <Select.Option value={3}>31天以上</Select.Option>
            </Select>
          </Form.Item>
        )}
        <Form.Item label='渠道等级'>
          <Select
            placeholder='请选择渠道等级'
            mode='multiple'
            filterOption={(input, option) =>
              (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
            }
            onDeselect={deselectEvent}
            onSelect={levelSelectEvent}
            value={selectList}
          >
            {tagInfoList.map((item) => (
              <Select.Option key={item.id} value={item.id}>
                {item.tagName}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label='市场单价'
          name={0}
          rules={[{ required: true, validator: priceValidator }]}
        >
          <Input placeholder='请输入市场单价' maxLength={11} />
        </Form.Item>
        {selectList.map((item: number) => (
          <Form.Item
            label={transValtoLabel(item)}
            key={item}
            name={item}
            rules={[{ required: true, validator: priceValidator }]}
          >
            <Input placeholder='请输入定价金额' maxLength={11} />
          </Form.Item>
        ))}
      </Form>
    </Modal>
  );
};

export default ConfigurePriceModal;
