import React, { FC, useEffect, useState } from 'react';
import { Form, Input, message, Modal, Select, Row, Col, Button, ModalProps, Card } 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;
}

const { Option } = Select;

const SetProduceSpecPriceModal: FC<ModalProps & PropsType> = ({ open, onCancel, data }) => {
  const tabList = [
    {
      key: '0',
      tab: '销售价格',
    },
    {
      key: '1',
      tab: '租赁价格',
    },
  ];
  //当前tab
  const [currentTab, setCurrentTab] = useState<string>('0');
  // 表格事件
  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) {
        form.setFieldsValue({ ...Obj, level: levelNumber });
      } else {
        form.setFieldsValue({
          0: undefined,
          level: undefined,
        });
      }
      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 = () => {
    setCurrentTab('0');
    const data = Object.fromEntries(
      selectList.map((i) => {
        return [i, undefined];
      }),
    );
    form.setFieldsValue({
      0: undefined,
      ...data,
    });
    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: Number(currentTab),
          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();
  };

  //tab change
  const onTabChange = (key: string) => {
    form.resetFields();
    switch (key) {
      case '0':
        getProductSpecPrice(Number(key), data?.id);
        break;
      case '1':
        getProductSpecPrice(Number(key), data?.id, 0);
        break;
    }
    setSelectList([]);
    setCurrentTab(key);
  };
  //租期选择
  const rentDateChange = (value: string) => {
    getProductSpecPrice(Number(currentTab), data?.id, Number(value));
  };
  // componentsDidMounted
  useEffect(() => {
    if (data) {
      getTagNameList();
      getProductSpecPrice(Number(currentTab), data?.id);
    }
  }, [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>,
      ]}
    >
      <Card tabList={tabList} onTabChange={onTabChange}>
        <Form
          name='form'
          form={form}
          layout='horizontal'
          labelWrap
          initialValues={{ leaseTerm: 0 }}
        >
          {currentTab === '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>
      </Card>
    </Modal>
  );
};
export default SetProduceSpecPriceModal;
