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, InterReqType } from '~/api/interface';
import {
  cooperationTagType,
  editProductSpecPriceType,
  ProductSpecListType,
} from '~/api/interface/produceManageType';
import _ from 'lodash';

//加盟标签返回类型
type cooperationTagResponseType = InterDataType<cooperationTagType>;
//产品规格返回类型
type specType = InterDataType<ProductSpecListType>['list'][0];
//配置价格参数类型
type setPriceParametersType = InterReqType<editProductSpecPriceType>;

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

const rentDateData = [
  {
    value: 0,
    label: '1-7天',
  },
  {
    value: 1,
    label: '8-15天',
  },
  {
    value: 2,
    label: '16-30天',
  },
  {
    value: 3,
    label: '31天以上',
  },
];

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 [priceParameters, setPriceParameters] = useState<setPriceParametersType>([]);
  //当前租期
  const [currentLeaseTerm, setCurrentLeaseTerm] = useState<number>(0);

  // 获取当前规格的价格
  const getProductSpecPrice = (type: number, productSpecId?: number, leaseTerm?: number) => {
    ProduceManageAPI.getProductSpecPrice({ type, productSpecId, leaseTerm }).then(({ result }) => {
      const priceInfoList =
        type === 1
          ? //租赁
            rentDateData.map((v) => {
              const specPrice = result
                .filter((i) => i.leaseTerm === v.value) //type 判断商城商品
                .map((v) => ({ cooperationTag: v.cooperationTag, id: v.id, price: v.price }));
              return {
                leaseTerm: v.value,
                productSpecId: data?.id,
                specPrice,
                type: type,
              };
            })
          : //销售商品
            [
              {
                productSpecId: data?.id,
                specPrice: result.map((v) => ({
                  cooperationTag: v.cooperationTag,
                  id: v.id,
                  price: v.price,
                })),
                type: type,
              },
            ];
      console.log('转化数据-->', priceInfoList);
      setPriceParameters([...priceInfoList]);
      const levelNumber: number[] = priceInfoList[0].specPrice
        .filter((v) => v.cooperationTag != 0)
        .map((v) => v.cooperationTag);
      const Obj: any = priceInfoList[0].specPrice.reduce((pre: any, cur) => {
        pre[cur.cooperationTag] = cur.price;
        return { ...pre };
      }, {});
      form.setFieldsValue({ ...Obj, level: levelNumber });
      const arr = priceInfoList[0].specPrice
        .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([]);
    setCurrentLeaseTerm(0);
    onCancel();
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then(async (values) => {
        const specPrice = Object.getOwnPropertyNames(values)
          .filter((v) => !['leaseTerm', 'level'].includes(v))
          .reduce((pre: any, cur: string) => {
            return [...pre, { price: values[cur], cooperationTag: Number(cur) }];
          }, []);
        if (priceParameters) {
          priceParameters[currentLeaseTerm].specPrice = specPrice;
          const obj = priceParameters
            .filter((v) => v.specPrice.length)
            .find((v) => v.specPrice.some((v) => v.price === undefined));
          if (obj && !_.isNull(obj.leaseTerm)) {
            return message.warning(`${rentDateData[obj.leaseTerm!].label}存在价格未配置`);
          }
          setPriceParameters([...priceParameters]);
          ProduceManageAPI['editProductSpecPrice'](
            priceParameters.filter((v) => v.specPrice.length),
          ).then(({ code }) => {
            if (code === '200') {
              message.success('操作成功');
              setCurrentLeaseTerm(0);
              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) => {
    const values = form.getFieldsValue();
    const specPrice = Object.getOwnPropertyNames(values)
      .filter((v) => !['leaseTerm', 'level'].includes(v))
      .reduce((pre: any, cur: string) => {
        return [...pre, { price: values[cur], cooperationTag: Number(cur) }];
      }, []);
    if (priceParameters) {
      priceParameters[currentLeaseTerm].specPrice = specPrice;
      setPriceParameters([...priceParameters]);
    }
    setCurrentLeaseTerm(Number(value));
    if (priceParameters && priceParameters[Number(value)].specPrice.length) {
      const Obj: any = priceParameters[Number(value)].specPrice.reduce((pre: any, cur) => {
        pre[cur.cooperationTag] = cur.price;
        return { ...pre };
      }, {});
      const levelNumber: number[] = priceParameters[Number(value)].specPrice
        .filter((v) => v.cooperationTag != 0)
        .map((v) => v.cooperationTag);
      //没有设置价格的清空
      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 });
      const arr = priceParameters[Number(value)].specPrice
        .map((i) => {
          return i.cooperationTag;
        })
        .filter((i: number) => i !== 0);
      setSelectList(arr);
    } else {
      const defaultObj = tagInfoList.reduce((pre: any, cur) => {
        pre[cur.id] = undefined;
        return pre;
      }, {});
      form.setFieldsValue({
        0: undefined,
        level: undefined,
        ...defaultObj,
      });
      setSelectList([]);
    }
  };
  // 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}>
              {rentDateData.map((v) => (
                <Select.Option value={v.value} key={v.value}>
                  {v.label}
                </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;
