import React, { useState, useEffect } from 'react';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Select, Input, Card, notification } from 'antd';
import style from '../index.less';
import { apiDeliveriesAdd } from '../service';

const FormItem = Form.Item;
const { Option } = Select;

const LogisticsForm = props => {
  const { modalVisible, onCancel, company = [], skuList, onSubmit } = props;
  const { getFieldDecorator } = props.form;
  const [result, setResult] = useState(() => props.value);
  const formData = async (formDataList, fieldsValue, suffixes) => {
    // 数据聚合
    suffixes.forEach(suffixe => {
      const formObj = {};
      // eslint-disable-next-line no-restricted-syntax
      for (const key in fieldsValue) {
        if (key.startsWith(suffixe)) {
          formObj[key.split('-')[1]] = fieldsValue[key];
        }
      }
      formDataList.push(formObj);
    });

    // 参数整合
    const resultData = [];
    formDataList.forEach(data => {
      data.selectedGoods.forEach(orderSkuId => {
        resultData.push({
          orderSkuId,
          expressCompanyCode: data.selectedCompany.split('-')[0],
          expressCompanyName: data.selectedCompany.split('-')[1],
          deliveryNo: data.orderNum,
          serialNumber: data.serialNumber || '',
        });
      });
    });
    // 校验重复商品
    let orderSkuIds = [];
    formDataList.forEach(data => {
      orderSkuIds = [...orderSkuIds, ...data.selectedGoods];
    });
    if (orderSkuIds.length !== Array.from(new Set(orderSkuIds)).length) {
      notification.error({ message: '商品选择重复！' });
      return;
    }

    if (skuList.length !== orderSkuIds.length) {
      notification.error({ message: '该订单下的所有商品必须设置物流信息！' });
      return;
    }
    await apiDeliveriesAdd(resultData);
    onSubmit();
  };

  const handleSubmit = () => {
    props.form.validateFields((err, fieldsValue) => {
      const suffixes = [];
      const formDataList = [];
      if (err) return;
      Object.keys(fieldsValue).forEach(key => {
        const suffixe = key.split('-')[0];
        if (!suffixes.includes(suffixe)) suffixes.push(suffixe);
      });
      formData(formDataList, fieldsValue, suffixes);
    });
  };

  const addForm = () => {
    setResult([...result, {}]);
  };

  const rmForm = () => {
    if (result.length === 1) return;
    setResult(result.slice(0, result.length - 1));
  };
  useEffect(() => {
    setResult(props.value);
  }, props.value);

  return (
    <Modal
      destroyOnClose
      title="物流操作确认"
      visible={modalVisible}
      onCancel={() => onCancel()}
      onOk={handleSubmit}
      afterClose={() => setResult([{}])}
    >
      <Form>
        {result &&
          result.length &&
          result.map((v, i) => (
            // eslint-disable-next-line react/no-array-index-key
            <Card key={i}>
              <FormItem>
                {getFieldDecorator(`${i}-selectedGoods`, {
                  initialValue: v.selectedGoods,
                  rules: [
                    {
                      required: true,
                      message: '请选择该订单下的商品!',
                    },
                  ],
                })(
                  <Select mode="multiple" placeholder="请选择该订单下的商品">
                    {skuList.map(item => (
                      <Option value={item.orderSkuId} key={item.orderSkuId}>
                        {item.skuName + (item.skuAttr || '')}
                      </Option>
                    ))}
                  </Select>,
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator(`${i}-selectedCompany`, {
                  initialValue: v.selectedCompany,
                  rules: [
                    {
                      required: true,
                      message: '请选择物流公司!',
                    },
                  ],
                })(
                  <Select showSearch placeholder="请选择物流公司">
                    {company?.map(item => (
                      <Option
                        value={`${item.expressCompanyCode}-${item.expressCompanyName}`}
                        key={item.expressCompanyCode}
                      >
                        {item.expressCompanyName}
                      </Option>
                    )) || []}
                  </Select>,
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator(`${i}-orderNum`, {
                  initialValue: v.orderNum,
                  rules: [
                    {
                      required: true,
                      message: '请填写物流单号!',
                    },
                  ],
                })(<Input maxLength={30} placeholder="请填写物流单号" />)}
              </FormItem>
              <FormItem>
                {getFieldDecorator(`${i}-serialNumber`, {
                  initialValue: v.serialNumber,
                  rules: [
                    {
                      pattern: new RegExp(/^[0-9a-zA-Z-_]{6,32}$/, 'g'),
                      message: '序列号格式不正确!',
                    },
                  ],
                })(<Input placeholder="请填写序列号" />)}
              </FormItem>
            </Card>
          ))}
        <div className={style.logistics}>
          <PlusCircleOutlined className={style.logisticsIcon} onClick={addForm} />
          <MinusCircleOutlined className={style.logisticsIcon} onClick={rmForm} />
        </div>
      </Form>
    </Modal>
  );
};

export default Form.create()(LogisticsForm);
