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

//加盟标签返回类型
type cooperationTagResponseType = InterDataType<cooperationTagType>;
//产品规格返回类型
type specType = InterDataType<ProductSpecListType>['list'][0];

interface PropsType {
  onCancel: () => void;
  data: specType | undefined;
  type: number; //产品所属类型
}

const { Option } = Select;

const SetProduceSpecPriceModal: FC<ModalProps & PropsType> = ({ open, onCancel, data, type }) => {
  // 表格事件
  const [form] = Form.useForm();
  // 等级标签列表
  const [tagInfoList, setTagInfoList] = useState<cooperationTagResponseType>([]);
  // 选择的列表
  const [selectList, setSelectList] = useState<number[]>([]);
  //是否编辑
  const [isEdit, setIsEdit] = useState<boolean>(false);

  // 获取当前规格的价格
  const getProductSpecPrice = (type: number, productSpecId?: number, leaseTerm?: number) => {
    ProduceManageAPI.getProductSpecPrice({ type, productSpecId, leaseTerm }).then(({ result }) => {
      setIsEdit(!!result.length);
      const levelNumber: number[] = result
        .filter((v) => v.cooperationTag != 0)
        .map((v) => v.cooperationTag);
      const Obj: any = result.reduce((pre: any, cur) => {
        pre[cur.cooperationTag] = cur.price;
        return { ...pre };
      }, {});
      if (result.length) {
        //没有设置价格的清空
        const setDefaultObj = tagInfoList.reduce((pre: any, cur) => {
          if (!Object.keys(Obj).includes(cur.id.toString())) {
            pre[cur.id] = undefined;
          }
          return pre;
        }, {});
        form.setFieldsValue({ ...Obj, level: levelNumber, ...setDefaultObj });
      } else {
        //如果没有返回价格，清楚上一次选择的租期价格
        const defaultObj = tagInfoList.reduce((pre: any, cur) => {
          pre[cur.id] = undefined;
          return pre;
        }, {});
        form.setFieldsValue({
          0: undefined,
          level: undefined,
          ...defaultObj,
        });
      }
      const arr = result
        .map((i) => {
          return i.cooperationTag;
        })
        .filter((i: number) => i !== 0);
      setSelectList(arr);
    });
  };
  // 获取等级标签
  const getTagNameList = () => {
    ProduceManageAPI.getCooperationListTag().then(({ result }) => {
      setTagInfoList(result || []);
    });
  };
  // 选择器点击事件
  const handleChange = (value: number[]) => {
    setSelectList(value);
  };
  // 将val转换为label
  const transValtoLabel = (id: number) => {
    const item = tagInfoList.find((i) => i.id === id);
    return item ? item.tagName : id;
  };
  // 关闭弹窗
  const handleClosed = () => {
    form.resetFields();
    setSelectList([]);
    onCancel();
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then(async (values) => {
        const specPrice = Object.keys(filterObjAttr(values, ['leaseTerm', 'level'])).reduce(
          (pre: any, cur: string) => {
            return [...pre, { price: values[cur], cooperationTag: Number(cur) }];
          },
          [],
        );
        ProduceManageAPI[isEdit ? 'editProductSpecPrice' : 'setProductSpecPrice']({
          specPrice,
          productSpecId: data?.id,
          type: type,
          leaseTerm: values.leaseTerm,
        }).then(({ code }) => {
          if (code === '200') {
            message.success('操作成功');
            handleClosed();
          }
        });
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };
  // 价格正则
  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();
  };
  //租期选择
  const rentDateChange = (value: string) => {
    getProductSpecPrice(type, data?.id, Number(value));
  };
  // componentsDidMounted
  useEffect(() => {
    if (data) {
      getTagNameList();
      getProductSpecPrice(type, data?.id, type === 0 ? undefined : 0);
    }
  }, [data]);
  return (
    <Modal
      open={open}
      title='配置价格'
      destroyOnClose
      width={768}
      onCancel={handleClosed}
      footer={[
        <Button key='1' type='default' onClick={handleClosed}>
          取消
        </Button>,
        <Button key='2' type='primary' onClick={handleSubmit}>
          确认
        </Button>,
      ]}
    >
      <Form name='form' form={form} layout='horizontal' labelWrap initialValues={{ leaseTerm: 0 }}>
        {type === 1 && (
          <Form.Item
            label='租期'
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            name='leaseTerm'
            rules={[{ required: true, message: '请选择租期' }]}
          >
            <Select onChange={rentDateChange}>
              <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='渠道等级'
          name='level'
          rules={[{ required: true, message: '请选择渠道等级' }]}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 15 }}
        >
          <Select
            placeholder='请选择渠道等级'
            allowClear
            mode='multiple'
            onChange={handleChange}
            value={selectList}
          >
            {tagInfoList.map((i, j) => (
              <Option value={i.id} key={j}>
                {i.tagName}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Row>
          <Col span={20}>
            <Form.Item
              name='0'
              label='市场单价'
              rules={[{ required: true, validator: priceValidator }]}
              labelCol={{ span: 6 }}
              wrapperCol={{ span: 18 }}
            >
              <Input placeholder='请输入市场单价' maxLength={11} allowClear />
            </Form.Item>
          </Col>
          <Col span={4}>
            <div style={{ margin: '6px 0 0 10px' }}>元/件</div>
          </Col>
        </Row>
        {selectList.map((i, j) => (
          <Row key={j}>
            <Col span={20}>
              <Form.Item
                name={i}
                label={transValtoLabel(i)}
                rules={[{ required: true, validator: priceValidator }]}
                key={j}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <Input placeholder='请输入定价金额' maxLength={11} allowClear />
              </Form.Item>
            </Col>
            <Col span={4}>
              <div style={{ margin: '6px 0 0 10px' }}>元/件</div>
            </Col>
          </Row>
        ))}
      </Form>
    </Modal>
  );
};
export default SetProduceSpecPriceModal;
