import React, { forwardRef, useImperativeHandle, useState, useRef, useEffect } from 'react';
import { Modal, Select, notification, Form, Input, Button, Checkbox } from 'antd';
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { userEnabled, userDisabled, userDelete } from '@/pages/systemManage/service';
import { apiDeliveriesAdd, apiDeliveriesEdit } from '../../service';
import styles from './index.less';

const FormComponent = (props, ref) => {
  const { record = {}, companys = [], minPackageCount = 1, maxPackageCount = 10 } = props;
  const { mchOrderSkuVoList, packageList } = record;
  const [form] = Form.useForm();
  const [addPackageList, setAddPackageList] = useState({
    expressCompanyCode: null,
    expressCompanyName: '',
    expressNo: '',
    serialNumber: '',
    skuInfoList: mchOrderSkuVoList.map(item => ({})),
  });

  const [initPackageList, setInitPackageList] = useState(() => {
    // 新增
    if (packageList.length === 0) {
      return [
        {
          // 默认选中所有商品
          skuInfoList: mchOrderSkuVoList.map(item => ({
            skuNo: [item.skuNo],
            quantity: item.count,
          })),
        },
      ];
    }
    // 编辑
    return packageList.map(item => ({
      ...item,
      // 渲染所有商品选项，通过查找editData 是否存在判断是否选中
      skuInfoList: mchOrderSkuVoList.map((skuInfo, index) => {
        const skuNo = skuInfo.skuNo?.toString();
        const editData = item.skuInfoList?.find(ele => ele.skuNo?.toString() === skuNo);
        if (editData) {
          return {
            ...editData,
            skuNo: [skuInfo.skuNo],
          };
        }
        return {};
      }),
    }));
  });

  // eslint-disable-next-line consistent-return
  const onCheckSkuInfoList = async (_, names) => {
    let hasNotCount = 0;
    const count = names.filter(item => {
      if (item.skuNo && item.skuNo.length > 0 && !item.quantity) {
        hasNotCount++;
      }
      return item.skuNo && item.skuNo.length;
    }).length;

    if (hasNotCount) {
      return Promise.reject(new Error('请填写选择发货商品的数量'));
    }
    if (count === 0) {
      return Promise.reject(new Error('至少选择一个商品'));
    }
  };

  const formLayout = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
  };
  const formRules = {
    skuInfoList: [{ validator: onCheckSkuInfoList }],
    expressCompanyCode: [{ required: true, message: '请选择物流公司' }],
    expressNo: [{ required: true, message: '请填写物流单号' }],
    // serialNumber: [{ required: true, message: '请填写序列号' }],
  };

  useImperativeHandle(ref, () => ({
    form,
  }));

  const getSkuOptions = (index, parentIndex) => {
    const { skuNo, skuName } = mchOrderSkuVoList[index];
    return (
      <Checkbox.Group>
        <Checkbox value={skuNo}>{skuName}</Checkbox>
      </Checkbox.Group>
    );
  };

  const onInput = e => {
    if (e.target.value === '') {
      return;
    }
    if (e.target.value <= 0) {
      e.target.value = 1;
    }
  };

  const SkuFormList = skuProps => {
    const { skuFields, parentFields, errors } = skuProps;
    return (
      <div className={styles['sku-list-box']}>
        {skuFields.map(field => (
          <div key={field.key} className={styles['sku-list']}>
            <Form.Item className={styles['sku-list__goods-name']} name={[field.name, 'skuNo']}>
              {getSkuOptions(field.name, parentFields.name)}
            </Form.Item>
            <Form.Item className={styles['sku-list__goods-count']} name={[field.name, 'quantity']}>
              <Input type="number" onInput={onInput} placeholder="数量" />
            </Form.Item>
          </div>
        ))}
        <Form.ErrorList errors={errors} />
      </div>
    );
  };

  // 选择物流可搜索
  const filterOption = (inputValue, option) => option.expressCompanyName.includes(inputValue);

  return (
    <Form
      form={form}
      {...formLayout}
      initialValues={{
        packageList: initPackageList,
      }}
    >
      <Form.List name="packageList" rules={[]}>
        {(fields, { add, remove }, { errors }) => (
          <>
            {fields.map((field, index) => (
              <div key={field.key} className={styles['sku-list-module']}>
                <div className={styles['sku-list-module__index']}>包裹 {index + 1}</div>
                <Form.List name={[field.name, 'skuInfoList']} rules={formRules.skuInfoList}>
                  {(skuFields, actions, { errors: err }) => (
                    <SkuFormList
                      key={field.key}
                      skuFields={skuFields}
                      parentFields={field}
                      errors={err}
                    />
                  )}
                </Form.List>
                <Form.Item
                  name={[field.name, 'expressCompanyCode']}
                  rules={formRules.expressCompanyCode}
                >
                  <Select
                    placeholder="请选择物流公司"
                    showSearch
                    filterOption={filterOption}
                    fieldNames={{ label: 'expressCompanyName', value: 'expressCompanyCode' }}
                    options={companys}
                  ></Select>
                </Form.Item>
                <Form.Item name={[field.name, 'expressNo']} rules={formRules.expressNo}>
                  <Input placeholder="请填写物流单号" />
                </Form.Item>
                <Form.Item name={[field.name, 'serialNumber']} rules={formRules.serialNumber}>
                  <Input placeholder="请填写序列号" />
                </Form.Item>
              </div>
            ))}

            <div className={styles.operation}>
              <PlusCircleOutlined
                style={{ color: fields.length >= maxPackageCount ? '#ccc' : '' }}
                onClick={() => {
                  if (fields.length >= maxPackageCount) return;
                  const currentPackageList = form.getFieldValue('packageList');
                  form.setFieldsValue({
                    packageList: [...currentPackageList, addPackageList],
                  });
                }}
              />
              <MinusCircleOutlined
                style={{ color: fields.length <= minPackageCount ? '#ccc' : '' }}
                onClick={() => {
                  if (fields.length <= minPackageCount) return;
                  remove(fields[fields.length - 1].name);
                }}
              />
            </div>
          </>
        )}
      </Form.List>
    </Form>
  );
};
const FormWarpper = forwardRef(FormComponent);

const UpdateStatusModal = (props, ref) => {
  const { companys } = props;
  const formRef = useRef();
  const [visible, setVisible] = useState(false);
  const [renderModal, setRenderModal] = useState(true);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [record, setRecord] = useState();
  const [oldPackageList, setOldPackageList] = useState();
  const [actionRef, setActionRef] = useState();

  // 提交前处理数据结构将skuNo的值从[skuNo]=>skuNo
  const onFilterParams = packageList => {
    const currentPackageList = JSON.parse(JSON.stringify(packageList));
    return currentPackageList.map(item => {
      const { skuInfoList } = item;
      /**
       * 参数结构
       * @var {object} item { expressCompanyCode, expressNo, serialNumber, skuInfoList }
       * @var {array} skuInfoList [{skuNo, quantity}]
       * @var {object} company { expressCompanyCode, expressCompanyName }
       */
      const company = companys.find(ele => ele.expressCompanyCode === item.expressCompanyCode);
      return {
        ...item,
        ...company,
        skuInfoList: skuInfoList
          .filter(skuInfo => skuInfo.skuNo?.length)
          .map(skuInfo => ({
            skuNo: Number(skuInfo.skuNo[0]),
            quantity: Number(skuInfo.quantity),
          })),
      };
    });
  };

  const open = (item, tableRef) => {
    setRenderModal(true);
    setActionRef(tableRef);
    setVisible(true);
    setOldPackageList(JSON.parse(JSON.stringify(item.packageList)));
    setRecord(item);
  };

  const onCancel = () => {
    formRef.current.form.resetFields();
    setConfirmLoading(false);
    setVisible(false);
    setTimeout(() => {
      setRenderModal(false);
      setRecord(null);
    }, 500);
  };

  const onOk = async () => {
    const submitApi = oldPackageList.length === 0 ? apiDeliveriesAdd : apiDeliveriesEdit;
    formRef.current.form.validateFields().then(async values => {
      const packageList = onFilterParams(values.packageList);

      // 对比修改差异
      oldPackageList.forEach((item, index) => {
        if (!packageList[index]) return;
        const updateAttr = () => {
          packageList[index].preExpressCompanyCode = item.expressCompanyCode;
          packageList[index].preExpressCompanyName = item.expressCompanyName;
          packageList[index].preExpressNo = item.expressNo;
        };

        // eslint-disable-next-line no-restricted-syntax
        // for (const key in item) {
        //   if (typeof item[key] !== 'object' && item[key] !== packageList[index][key]) {
        //     console.log('修改了物流信息');
        //     updateAttr();
        //     break;
        //   } else if (
        //     typeof item[key] === 'object' &&
        //     JSON.stringify(item[key]) !== JSON.stringify(packageList[index][key])
        //   ) {
        //     console.log('修改了选择的商品');
        //     updateAttr();
        //     break;
        //   }
        // }
        updateAttr();
      });

      const params = {
        orderNo: record.orderNo,
        packageList,
      };
      setConfirmLoading(true);
      const res = await submitApi(params);
      setConfirmLoading(false);
      if (res.code === '0000' && res.businessCode === '0000') {
        notification.success({
          message: '提交成功',
        });
        onCancel();
        actionRef.current.reload();
      }
    });
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  const modalProps = {
    title: '填写物流信息',
    height: 500,
    visible,
    confirmLoading,
    onCancel,
    onOk,
  };

  const formProps = {
    record,
    companys,
    minPackageCount: oldPackageList?.length || 1,
  };

  return renderModal ? (
    <Modal {...modalProps}>{record ? <FormWarpper ref={formRef} {...formProps} /> : ''}</Modal>
  ) : (
    ''
  );
};

export default forwardRef(UpdateStatusModal);
