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: $t('duplicate.product.selection') });
      return;
    }

    if (skuList.length !== orderSkuIds.length) {
      notification.error({ message: $t('all.order.items.require.logistics') });
      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={$t('logistics.confirmation')}
      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: $t('order.items.required'),
                    },
                  ],
                })(
                  <Select mode="multiple" placeholder={$t('select.order.items')}>
                    {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: $t('logistics.required'),
                    },
                  ],
                })(
                  <Select showSearch placeholder={$t('select.logistics')}>
                    {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: $t('enter.tracking.no'),
                    },
                  ],
                })(<Input maxLength={30} placeholder={$t('enter.tracking.no')} />)}
              </FormItem>
              <FormItem>
                {getFieldDecorator(`${i}-serialNumber`, {
                  initialValue: v.serialNumber,
                  rules: [
                    {
                      pattern: new RegExp(/^[0-9a-zA-Z-_]{6,32}$/, 'g'),
                      message: $t('invalid.serial.number.format'),
                    },
                  ],
                })(<Input placeholder={$t('enter.serial.no')} />)}
              </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);
