/* eslint-disable consistent-return */
/* eslint-disable react/no-array-index-key */
/* eslint-disable no-shadow */
import React, {
  useContext,
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef,
} from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Checkbox,
  Radio,
  Space,
  Switch,
  Row,
  Col,
  InputNumber,
  Cascader,
  Divider,
  DatePicker,
  message,
} from 'antd';
import moment from 'moment';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Title } from './CommonTemplate';
import { formItemLayout, ENUM_REPERTORY, ENUM_SET_REPERTORY, ENUM_WEEK } from '../config';
import { ServiceContext } from '../context';
import { debounce } from '@/utils/utils';
import { isCheckPriceTwoDecimal, isIntegerNotZero } from '@/utils/validator';
import UploadImage from './UploadImage';
import styles from '../common.less';
import AddRepertoryModal from './AddRepertoryModal';
import { apiTagList, apiUnits } from '../service';
import { localAutoSaveKey, calcDescartes } from '../utils';
import localStorage from '@/utils/localStorage';

const createInitValues = () => ({
  description: '', // 商品描述
  detailImageList: [], // 商品图片
  stock: '1', // 库存类型
  saleTimeType: 0, // 售卖时间
  singleDelivery: 1, // 单点不送
  list: 1, // 列出商品
  label: [],
  minPurchaseNum: 1,
});
const format = 'HH:mm';
const { RangePicker } = DatePicker;
const TakeawayGoodsInfo = forwardRef((props, ref) => {
  const { editData, infoMation } = props;
  const [form] = Form.useForm();
  const [initValue, setInitValue] = useState(createInitValues());
  const customer = useContext(ServiceContext);
  const [detailImageList, setDetailImageList] = useState([]);
  const addSellTimeRef = useRef(null);
  const AddRepertoryRef = useRef(null);
  const AddMultiSpecRef = useRef(null);
  const [saleDates, setSaleDates] = useState({
    saleDates: [],
    saleTimes: [],
  }); // 可售日期
  const [timeType, setTimeType] = useState(0);
  const [repertoryType, setRepertoryType] = useState('1');
  const [tagList, setTagList] = useState([]);
  const [unitsList, setUnitsList] = useState([]);
  const [takeawayData, setTakeawayData] = useState({});
  // eslint-disable-next-line prefer-const
  let [multiSpu, setMultiSpu] = useState([]);
  const [singularSpu, setSingularSpu] = useState([]);
  const [intactData, setIntactData] = useState({});
  const [repertoryState, setRepertoryState] = useState('');
  const [repertoryModel, setRepertoryModel] = useState({});
  const [tempMultiSpu, setTempMultiSpu] = useState([]);
  const [tempWeight, setTempWeight] = useState([]);
  const [tempSpecs, setTempSpecs] = useState([]);
  const [weightUnits, setWeightUnits] = useState([]);
  const [peopleUnits, setPeopleUnits] = useState([]);
  const [isRequired, setIsRequired] = useState(true);
  const [initMultiSpu, setInitMultiSpu] = useState([]); // 初始化sku 作对比

  // 自定义加入菜单
  const showModal = () => {
    addSellTimeRef.current.setOpen(true);
  };
  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      return {
        ...values,
        temp: 'takeawayItem',
        intactData,
      };
    } catch (errorInfo) {
      return null;
    }
  };
  // 过滤单位
  const filterUnit = unit =>
    (Array.isArray(unit) && unit?.length && unit?.slice(1).toString()) || unit;
  // 商品基本信息编辑商品名称
  const takeawayCalc = takeawayData => {
    const { infoMation: name, infoMation, takeawayItem } = takeawayData;
    //  weight 份量  specs规格 生成sku规则 weight * specs
    const {
      specs = [],
      weight = [],
      description,
      detailImageList,
      list,
      minPurchaseNum,
      saleDates,
      maxStock = 0,
      saleTimes = [],
      label,
      quantity,
      productStock = 0,
      salePrice,
      singleDelivery,
      saleTimeType,
      autoStock = 0,
      skuList,
      id,
      categoryId,
    } = takeawayItem;
    let { unit } = takeawayItem;
    unit = (unit && filterUnit(unit)) || unit;
    const singularSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 单规格
    const multiSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 多规格

    let singularSpuData = []; // 单库存spu
    const saleTimesTemp = [];
    if (saleTimes.length) {
      saleTimes.forEach(item => {
        const startTime = item ? moment(item[0]).format(format) : '';
        const endTime = item ? moment(item[1]).format(format) : '';
        saleTimesTemp.push({ startTime, endTime });
      });
    }
    const temp = {
      salePrice: salePrice || 0,
      productStock,
      list: 1,
      id: skuList?.length === 1 ? skuList[0].id : '', // 单规格默认取第一个
      serviceItem: {
        description, //  商品描述
        maxStock, // 最大库存
        productStock,
        minPurchaseNum, // 最少购买
        saleTimeType, // 售卖时间
        singleDelivery, // 单点不送
        list, // 是否列出 1 是 0 否（外卖商品必填）
        label, // 商品标签id
        saleDates, // 可售日期 1-8
        saleTimes: saleTimesTemp, // 可售日期 时间段
        autoStock, // 弹框设置---自动补足
      },
    };

    // 单规格
    if (+repertoryType === 1) {
      const specs = {
        salePrice,
        maxStock,
        quantity,
        // unit: (Array.isArray(unit) && unit?.length && unit?.splice(unit?.length - 1)[0]) || unit,
        unit,
        productStock,
        specGroupName: '份量',
      };
      if (peopleUnits.includes(specs.unit)) {
        delete specs.quantity;
      }
      singularSpecList[0].specs = [specs];
      singularSpuData = [{ ...temp, specs: [specs] }];
      setSingularSpu(singularSpuData);
    }

    // 多规格
    if (+repertoryType === 2) {
      // if (name || editData.name) {
      if (weight.length) {
        let tempSku = [];
        multiSpecList[0].specs = weight; // 处理specList
        if (specs.length) {
          specs.forEach((specsItem, specsIndex) => {
            if (specsItem && !specsItem.generateSku) {
              specsItem.generateSku = 1;
            }
            if (specsItem?.specGroupName) {
              specsItem.specs.forEach(itm => {
                itm.specGroupName = specsItem?.specGroupName;
              });
            }
            multiSpecList.push(specsItem);
          });
        }
        const sepcx = specs.map(item => item.specs);
        sepcx.map(item => {
          item.unit = '';
          return item;
        });
        // 生成 specs 规格sku
        tempSku = [[...weight], ...sepcx].reduce(
          (x, y) => {
            const arr = [];
            x.forEach(x => y.forEach(y => arr.push(x.concat([y]))));
            return arr;
          },
          [[]],
        );
        multiSpu = tempSku.map((item, index) => {
          const obj = {};
          obj.salePrice = salePrice;
          obj.productStock = productStock;
          obj.list = list;
          obj.id = multiSpu?.[index]?.id || '';
          obj.serviceItem = {
            ...temp.serviceItem,
            productStock: multiSpu?.[index]?.serviceItem?.productStock || productStock,
            maxStock: multiSpu?.[index]?.serviceItem?.maxStock || maxStock,
            autoStock: multiSpu?.[index]?.serviceItem?.autoStock || autoStock,
          };
          obj.unique = '';
          multiSpecList.forEach((itm, idx) => {
            if (item[idx] && !item[idx]?.specGroupName) {
              if (multiSpecList[idx].specGroupName) {
                item[idx].specGroupName = multiSpecList[idx].specGroupName;
              }
            }
          });
          obj.specs = [...item];
          return obj;
        });
      }

      multiSpu.forEach(item => {
        item.salePrice = 0;
        item.unique = '';
        item.unique = item?.specs
          .map(itm => {
            if (itm?.unit) {
              itm.unit =
                itm?.unit &&
                (Array.isArray(itm?.unit) ? itm?.unit.slice(itm?.unit.length - 1)[0] : itm?.unit);
            }
            if (itm?.unit && peopleUnits.includes(itm.unit)) {
              delete itm.quantity;
            }
            if (itm?.specGroupName && itm?.specName) {
              return `${itm?.specGroupName + itm.specName}`;
            }
            return itm;
          })
          .toString();
      });

      // 编辑数据
      if (customer.isEdit) {
        const uniqueArr = tempMultiSpu.map(item => item.unique);
        const multiSpuUnique = multiSpu.map(item => item.unique);
        const newArrLen = Array.from(new Set(multiSpuUnique)).length;
        if (newArrLen < multiSpuUnique.length) {
          message.error('份量名称不能重复！');
        }
        // 新增对比数据
        multiSpu.forEach((item, index) => {
          if (!uniqueArr.includes(item.unique)) {
            tempMultiSpu.push({
              ...item,
              serviceItem: { ...temp.serviceItem, maxStock: 0, autoStock: 0, productStock: 0 },
              id: '',
            });
          }
        });

        // // 删除对比数据
        while (multiSpu.length !== tempMultiSpu.length) {
          tempMultiSpu.forEach((item, index) => {
            if (!multiSpuUnique.includes(item.unique)) {
              tempMultiSpu.splice(index, 1);
            }
          });
        }
        // 同步库存设置
        multiSpu.map(item => {
          tempMultiSpu.forEach(itm => {
            if (item.unique === itm.unique) {
              // 修改商品售卖信息参数
              const params = {
                saleDates: temp.serviceItem.saleDates,
                saleTimes: temp.serviceItem.saleTimes,
                saleTimeType: temp.serviceItem.saleTimeType,
                minPurchaseNum: temp.serviceItem.minPurchaseNum,
              };
              item.serviceItem = { ...item.serviceItem, ...itm.serviceItem, ...params };
              itm.specs = [...item.specs];
            }
          });
          return item;
        });

        setTempMultiSpu(tempMultiSpu);
        setMultiSpu(JSON.parse(JSON.stringify(multiSpu)));
      }
      // 新增
      if (!customer.isEdit) {
        setTempMultiSpu(multiSpu);
        setMultiSpu(multiSpu);
      }
    }
    // +repertoryType === 1 单规格 2多规格
    const intactDataTemp = {
      ...takeawayItem,
      id,
      type: 5, // 外卖类型
      ...infoMation,
      label: label && label.toString(),
      list,
      description,
      detailImageList,
      repertoryType,
      singleDelivery,
      specList: +repertoryType === 1 ? singularSpecList : multiSpecList, // 单库存和多库存specList
      items: +repertoryType === 1 ? singularSpuData : JSON.parse(JSON.stringify(multiSpu)),
      initMultiSpu,
    };

    setIntactData(intactDataTemp);
    return intactData;
  };

  const onChange = () => {};
  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    props.onValuesChange({
      takeawayItem: JSON.parse(JSON.stringify(Object.assign(values, { multiSpu }))), //  { multiSpu }草稿箱回显使用
    });
    const takeawayData = customer.isEdit
      ? { takeawayItem: Object.assign({}, editData, values) }
      : localStorage.get(localAutoSaveKey) || {};
    // : { takeawayItem: values };
    setTakeawayData(takeawayData);
    takeawayCalc(takeawayData);
  }, 400);
  // 设置库存
  const modifiedInventory = (type, idx, values) => {
    const { productStock, maxStock, autoStock } = values;
    if (type === 'multi') {
      tempMultiSpu.map(item => {
        if (item.unique === idx) {
          item.serviceItem.productStock = productStock;
          item.serviceItem.autoStock = autoStock;
          item.serviceItem.maxStock = maxStock;
        }
        return item;
      });
    }
    if (type === 'all') {
      tempMultiSpu.map(item => {
        item.serviceItem.productStock = productStock;
        item.serviceItem.autoStock = autoStock;
        item.serviceItem.maxStock = maxStock;
        return item;
      });
    }
    setTempMultiSpu(tempMultiSpu);
    getFormValues();
    return false;
  };

  const filterCategoryOptions = (inputValue, path) =>
    path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);

  useImperativeHandle(ref, () => ({
    onCheck,
    reset: () => {
      setInitValue(createInitValues());
      form.resetFields();
    },
  }));

  const startTime = moment(moment().format(format));
  const endTime = moment(moment().format(format));
  // 上传图片
  const onCardSuccessImageList = imgList => {
    setDetailImageList(imgList);
    form.setFieldsValue({
      detailImageList: imgList,
    });
  };
  // 自定义菜单下拉
  const dropdownRender = menus => (
    <div>
      {menus}
      <Divider
        style={{
          margin: 0,
        }}
      />
      <div
        style={{
          padding: 8,
          background: '#1890ff',
          color: '#fff',
          textAlign: 'center',
        }}
        onClick={showModal}
      >
        添加自定售卖时间
      </div>
    </div>
  );
  // 切换库存
  const onChangeRepertory = e => {
    const { value } = e.target;
    setRepertoryType(`${value}`);
    if (+value === 1) {
      form.setFieldsValue({ weight: [] });
      form.setFieldsValue({ specs: [] });
    } else {
      const params = {
        quantity: '',
        unit: [],
        salePrice: '',
        productStock: '',
        maxStock: '',
        autoStock: false,
      };
      form.setFieldsValue(params);
    }
  };
  // 勾选库存设置
  const onChangeSetRepertory = e => {
    setRepertoryState(`${e.target.value}`);
    if (+e.target.value === 0) {
      form.setFieldsValue({
        productStock: 0,
      });
    } else {
      const { maxStock } = form.getFieldsValue(['maxStock']);
      form.setFieldsValue({
        productStock: maxStock,
      });
    }
    getFormValues();
  };
  // 最大库存设置
  const onChangeMaxStock = e => {
    // 已经勾选最大库存 自动更新剩余库存
    if (+repertoryState === 1) {
      form.setFieldsValue({
        productStock: e,
      });
    }
  };
  // 切换时间
  const onChangeTime = e => {
    setTimeType(e.target.value);
  };
  // 自动补全
  const onChangeAutoStock = e => {
    form.setFieldsValue({
      autoStock: e ? 1 : 0,
    });
    setIsRequired(!e);
  };
  // 显示加入库存弹框
  const showAddRepertoryModal = (type, idx, item) => {
    AddRepertoryRef.current.setOpenRepertory(true);
    setRepertoryModel({ type, idx, item });
  };

  // 拼接sku 名称
  const calcLabelName = item => {
    let firstName = '';
    let lastName = '';
    if ((item?.unique || item?.specs?.length >= 0) && item?.unique !== '[object Object]') {
      const tempQuantity = `(${
        item?.specs[0]?.unit
          ? (weightUnits.includes(filterUnit(item.specs[0]?.unit)) && '约') || ''
          : ''
      } ${
        peopleUnits.includes(filterUnit(item.specs[0]?.unit)) ? '' : item.specs[0]?.quantity || ''
      }`;
      const tempUnit = `${item.specs[0]?.unit || ''} ${item.specs[0]?.unit ? ')' : ''}`;
      const uniqueName = item?.unique?.split(',') || [];
      if (uniqueName && uniqueName?.length) {
        firstName = uniqueName[0] || '';
        lastName = uniqueName?.slice(1).join(' ') || '';
      }
      return `${firstName} ${tempQuantity} ${tempUnit} ${lastName.replace('[object Object]', '')}`;
    }
  };
  const init = async () => {
    if (!tagList.length) {
      const res = await apiTagList();
      setTagList(res.data || []);
    }
    if (!unitsList?.length) {
      const res = await apiUnits();
      setUnitsList(res.data || []);
      const tempWeight = res.data.filter(item => item.name === '准确重量单位');
      const tempPeople = res.data.filter(item => item.name === '适用人数');

      if (tempWeight?.length && tempWeight[0]?.children) {
        const tempWeightName = tempWeight[0]?.children.map(item => item.name);
        sessionStorage.setItem('weightUnits', JSON.stringify(tempWeightName || []));
        setWeightUnits(tempWeightName);
      }
      if (tempPeople?.length && tempPeople[0]?.children) {
        const tempPeopleName = tempPeople[0]?.children.map(item => item.name);
        sessionStorage.setItem('peopleUnits', JSON.stringify(tempPeopleName || []));
        setPeopleUnits(tempPeopleName);
      }
    }
    // setTempMultiSpu([]);// 回显时候库存无法展示
    return false;
  };
  useEffect(() => {
    if (customer.isEdit && !customer.isUseCache) {
      if (!editData) return;
      const {
        label,
        firstCategoryId,
        secondCategoryId,
        thirdCategoryId,
        id,
        saleTimes,
        saleTimeType,
      } = editData;
      editData.label = label && label.split(',')?.map(item => +item);
      const specList = editData?.specList;
      const weight = specList?.filter(item => item.specGroupName === '份量');
      const specs = specList?.filter(item => item.specGroupName !== '份量');
      const tempWeightName = JSON.parse(sessionStorage.getItem('weightUnits'));
      if (weight?.length) {
        weight.forEach(item => {
          if (item?.specs?.length) {
            item.specs.forEach(itm => {
              if (itm?.unit && tempWeightName.includes(itm?.unit)) {
                itm.quantity =
                  itm?.quantity.indexOf('约') > -1 ? itm?.quantity.slice(1) : itm?.quantity || '';
              }
            });
          }
        });
      }
      editData.saleTimes = saleTimes?.length
        ? saleTimes.map(item => [moment(item?.startTime, format), moment(item?.endTime, format)])
        : [];
      if (editData?.skuList?.length) {
        // 单规格
        if (editData?.skuList?.length === 1) {
          const {
            productStock,
            shopId,
            specs,
            serviceItem: { maxStock, id, autoStock },
          } = editData?.skuList[0];
          const { quantity, unit, salePrice } = specs[0];
          editData.productStock = productStock;
          editData.quantity = `${quantity}`.indexOf('约') > -1 ? quantity.slice(1) : quantity || '';
          editData.unit = unit;
          editData.salePrice = salePrice;
          editData.maxStock = maxStock;
          editData.categoryId = [firstCategoryId, secondCategoryId, thirdCategoryId];
          editData.autoStock = +autoStock === 1;
          editData.productRefShopId = editData.shopId;
          editData.skuId = id;
          form.setFieldsValue(editData);
        } else {
          // 多规格
          setRepertoryType('2');
          const specList = editData?.specList;
          const weight = specList.filter(item => item?.specGroupName === '份量');
          const tempWeightName = JSON.parse(sessionStorage.getItem('weightUnits'));
          if (weight?.length) {
            weight.forEach(item => {
              if (item?.specs?.length) {
                item.specs.forEach(itm => {
                  if (itm?.unit && tempWeightName?.includes(itm?.unit)) {
                    itm.quantity =
                      itm?.quantity?.indexOf('约') > -1
                        ? itm?.quantity.slice(1)
                        : itm?.quantity || '';
                  }
                });
              }
            });
          }
          editData.categoryId = [firstCategoryId, secondCategoryId, thirdCategoryId];
          editData.productRefShopId = editData.shopId;
          // setTempWeight(weight)
          // setTempSpecs(specs)
          form.setFieldsValue({ weight: weight[0].specs });
          form.setFieldsValue(editData);
          form.setFieldsValue({ specs });
          const tempMultiSpu = editData?.skuList.map(item => {
            if (item) {
              item.serviceItem.productStock = item.productStock;
              const weightIndex = item.specs.findIndex(itm => itm.specGroupName === '份量');
              const tempQuantity = item.specs[weightIndex].quantity;
              const tempUnit = item.specs[weightIndex].unit;
              const specsNameList = item.specs.map(itm => itm.specName);
              const lastName = specsNameList.slice(1)?.join(' ');
              // item.unique = item?.specs.map(itm => itm.specName).toString();
              // item.uniqueAll = item?.specs.map(itm => `${itm.specGroupName + itm.specName}`).toString();
              item.unique = item?.specs
                .map(itm => `${itm.specGroupName + itm.specName}`)
                .toString();
            }
            return item;
          });
          setTempMultiSpu(tempMultiSpu || []);
          setInitMultiSpu(JSON.parse(JSON.stringify(tempMultiSpu)) || []);
          setMultiSpu(JSON.parse(JSON.stringify(tempMultiSpu)) || []);
        }
        setTimeType(saleTimeType);
        form.setFieldsValue({ productRefShopId: editData.shopId });
        onCardSuccessImageList(editData?.detailImageList);
        getFormValues();
      }
    }
    if (customer.isUseCache) {
      props.onValuesChange(editData, !0);
      let tempEdit = JSON.parse(JSON.stringify(editData));
      tempEdit = Object.assign({}, editData, { ...tempEdit.takeawayItem, ...tempEdit.infoMation });
      if (Object.keys(tempEdit).length) {
        if (tempEdit?.saleTimes) {
          tempEdit.saleTimes = tempEdit?.saleTimes?.length
            ? tempEdit?.saleTimes?.map(item => [moment(item[0]), moment(item[1])])
            : [];
        }
        if (tempEdit?.stock === '1') {
          setRepertoryType('1');
        }
        if (tempEdit?.stock === '2') {
          setRepertoryType('2');
          form.setFieldsValue({ weight: tempEdit?.weight });
          form.setFieldsValue({ specs: tempEdit?.specs });
          setTempMultiSpu(JSON.parse(JSON.stringify(tempEdit?.multiSpu)));
        }
        if (tempEdit?.detailImageList) {
          onCardSuccessImageList(tempEdit?.detailImageList);
        }
        setTimeType(tempEdit?.saleTimeType);
        form.setFieldsValue(tempEdit);
        getFormValues();
      }
    }
  }, [customer.isEdit, editData]);
  useEffect(() => {
    setIntactData(intactData);
  }, [intactData]);
  useEffect(() => {
    init();
  }, []);
  useEffect(() => {
    getFormValues();
  }, [repertoryType]);
  useEffect(() => {}, [tempMultiSpu]);
  return (
    <>
      <Form
        {...formItemLayout}
        form={form}
        name="takeaway"
        initialValues={initValue}
        scrollToFirstError
        onValuesChange={getFormValues}
      >
        <Title title="商品详细信息" />
        <Form.Item name="description" label="商品描述">
          <Input.TextArea
            showCount
            maxLength={200}
            style={{ width: 400 }}
            placeholder="请输入商品描述"
          />
        </Form.Item>
        <Form.Item
          name="detailImageList"
          label="商品图片"
          extra="支持.jpg/png格式图片，建议单张图片宽750像素，大小200kb左右，您可以拖拽图片调整顺序，最多上传5张。"
        >
          <UploadImage
            name="detailImageList"
            limit={5}
            disabled={customer.isDisabled}
            pictures={detailImageList}
            limitPicHeight="true"
            setPictureList={list => onCardSuccessImageList(list)}
          />
        </Form.Item>

        <Title title="商品售卖信息" />
        <Form.Item
          name="minPurchaseNum"
          label="最少购买"
          rules={[
            { required: true, message: '请输入最少购买数' },
            {
              validator: isIntegerNotZero,
              type: 'number',
              message: '请输入大于0的整数',
            },
          ]}
        >
          <InputNumber min={1} max={999999999} style={{ width: 200 }} placeholder="请输入购买量" />
        </Form.Item>
        <Form.Item
          name="saleTimeType"
          label="售卖时间"
          // rules={[{ type: 'array', required: true, message: '请输入售卖时间!' }]}
        >
          <Radio.Group onChange={onChangeTime}>
            <Radio value={0}>全时段</Radio>
            <Radio value={1}>自定义售卖时间</Radio>
          </Radio.Group>
        </Form.Item>
        {+timeType === 1 && (
          <>
            <Form.Item name="saleDates" label="售卖时期(可多选)">
              <Checkbox.Group>
                <Row>
                  <Col className={styles.colRow} span={8}>
                    {ENUM_WEEK.map((item, index) => (
                      <Checkbox value={item.value}>{item.label}</Checkbox>
                    ))}
                  </Col>
                </Row>
              </Checkbox.Group>
            </Form.Item>

            <Form.Item label="售卖时段">
              <Form.List name="saleTimes" initialValue={[[]]}>
                {(fields, { add, remove }) => (
                  <>
                    {fields.map((field, index) => (
                      <Form.Item required={false} key={field.key} className={styles.deal}>
                        <Form.Item
                          className={styles.deal}
                          {...field}
                          rules={[
                            {
                              required: true,
                              message: '请输入售卖时间',
                            },
                          ]}
                        >
                          <RangePicker
                            picker="time"
                            defaultPickerValue={[startTime, endTime]}
                            format={format}
                            onChange={onChange}
                            showTime={{
                              format: 'HH:mm',
                              // defaultValue: [moment('00:00', 'HH:mm'), moment('00:00', 'HH:mm')],
                              hideDisabledOptions: true,
                            }}
                            disabledTime={() => ({
                              disabledMinutes: () => {
                                const result = [];
                                for (let i = 1; i < 60; i++) {
                                  if (i !== 30) {
                                    result.push(i);
                                  }
                                }
                                return result;
                              },
                            })}
                          />
                        </Form.Item>
                        {fields.length > 1 ? (
                          <MinusCircleOutlined
                            className="dynamic-delete-button"
                            onClick={() => remove(field.name)}
                          />
                        ) : null}
                      </Form.Item>
                    ))}

                    <Form.Item>
                      {fields.length < 5 ? (
                        <Button
                          type="dashed"
                          onClick={() => add()}
                          style={{ width: '60%' }}
                          icon={<PlusOutlined />}
                        >
                          新增售卖时段
                        </Button>
                      ) : null}
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </>
        )}
        <Form.Item name="label" label="商品标签">
          <Select
            // mode="multiple"
            allowClear
            placeholder="请选择商品标签"
            style={{ width: 400 }}
            disabled={customer.isEdit && customer.isNormal}
            // showSearch={{ filter: filterCategoryOptions }}
            fieldNames={{ label: 'tagName', value: 'tagId' }}
            // onChange={props.onCategoryChange}
            options={tagList}
          />
        </Form.Item>
        <Form.Item
          name="singleDelivery"
          label="是否单点不送"
          extra="选择单点不送后顾客点该商品不可单独下单"
        >
          <Radio.Group>
            <Radio value={1}>单点送</Radio>
            <Radio value={0}>单点不送</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="list" label="列出商品" extra="开启后平台展示商品">
          <Radio.Group>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>
        </Form.Item>
        <Title title="规格信息" />
        {!customer.isEdit && (
          <Form.Item label="库存" name="stock">
            <Radio.Group
              options={ENUM_REPERTORY}
              onChange={onChangeRepertory}
              value="1"
              buttonStyle="solid"
              optionType="button"
            />
          </Form.Item>
        )}
        {/* 单规格 */}
        {repertoryType === '1' && (
          <>
            <Form.Item label="份量" className={styles.required}>
              {form.getFieldValue(['unit']) &&
                weightUnits.includes(filterUnit(form.getFieldValue(['unit']))) && (
                  <span className="ant-form-text"> 约</span>
                )}
              <Form.Item
                // noStyle
                shouldUpdate={(prevValues, curValues) => false}
              >
                {form => {
                  let unit = form.getFieldValue('unit') || '';
                  unit = filterUnit(unit);
                  if (!peopleUnits.includes(unit)) {
                    return (
                      <Form.Item
                        name="quantity"
                        style={{
                          display: 'inline-block',
                        }}
                        rules={[
                          { required: true, message: '请输入分量!' },
                          {
                            validator: isCheckPriceTwoDecimal,
                            type: 'number',
                            message: '保留两位小数',
                          },
                        ]}
                      >
                        <InputNumber
                          min={1}
                          max={999999999}
                          style={{ width: 200 }}
                          placeholder="请输入数字"
                        />
                      </Form.Item>
                    );
                  }
                }}
              </Form.Item>

              <Form.Item
                name="unit"
                rules={[{ required: true, message: '请选择单位' }]}
                // rules={[{ type: 'array', required: true, message: '请选择单位' }]}
                style={{
                  display: 'inline-block',
                  margin: '0 8px',
                }}
              >
                <Cascader
                  placeholder="请选择单位"
                  disabled={customer.isEdit && customer.isNormal}
                  showSearch={{ filter: filterCategoryOptions }}
                  fieldNames={{ label: 'name', value: 'name', children: 'children' }}
                  onChange={() => {
                    const unit = form.getFieldValue('unit') || [];
                    if (unit && peopleUnits.includes(unit[1])) {
                      form.setFieldsValue({ quantity: '' });
                    }
                  }}
                  options={unitsList}
                />
              </Form.Item>
            </Form.Item>
            <Form.Item
              name="salePrice"
              label="销售价格"
              rules={[{ required: true, message: '请输入销售价格' }]}
            >
              <InputNumber
                min={0}
                max={999999999}
                precision={2}
                style={{ width: 200 }}
                placeholder="元"
              />
            </Form.Item>
            <Form.Item className={styles.itemInline}>
              <Form.Item
                name="productStock"
                label="剩余库存"
                style={{
                  display: 'flex',
                  marginRight: '8px',
                }}
                rules={[
                  { required: true, message: '请填写剩余库存' },
                  {
                    validator: isIntegerNotZero,
                    type: 'number',
                    message: '请输入大于0的整数',
                  },
                ]}
              >
                <InputNumber
                  min={0}
                  max={999999999}
                  style={{ width: 200, display: 'inline-block' }}
                  placeholder="请输入"
                />
              </Form.Item>
              <Form.Item style={{ width: 200, display: 'inline-block' }}>
                <Radio.Group value={repertoryState} onChange={onChangeSetRepertory}>
                  <Radio.Button value="0">清空</Radio.Button>
                  <Radio.Button value="1">最大</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Form.Item>
            <Form.Item
              name="maxStock"
              label="最大库存"
              rules={[
                { required: !isRequired, message: '请填写最大库存' },
                {
                  validator: isIntegerNotZero,
                  type: 'number',
                  message: '请输入大于0的整数',
                },
              ]}
            >
              <InputNumber
                max={999999999}
                min={0}
                style={{ width: 200 }}
                placeholder="请输入"
                onChange={onChangeMaxStock}
              />
            </Form.Item>
            <Form.Item name="autoStock" label="自动补足" valuePropName="checked">
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                // defaultUnChecked
                onChange={onChangeAutoStock}
              />
            </Form.Item>
            <div className={styles.rowWarp}>
              {singularSpu.length > 0 &&
                singularSpu[0]?.specs[0]?.unit &&
                singularSpu.map((item, index) => (
                  <div className={styles.specsSingularBetween}>
                    <Form.Item label={calcLabelName(item)}>
                      <div className={styles.specsSingularBetween}>
                        <span className={styles.repertoryLimit}>
                          {item?.specs[0]?.productStock}/{item?.specs[0]?.maxStock}
                        </span>
                        {/* <div
                          className={styles.specRepertory}
                          onClick={() => {
                            showAddRepertoryModal('singular', index); // 单规格库存
                          }}
                        >
                          设置库存
                        </div> */}
                      </div>
                    </Form.Item>
                  </div>
                ))}
            </div>
          </>
        )}
        {/* 多规格 */}
        {repertoryType === '2' && (
          <>
            <Form.Item>
              <div>份量(如大小/小份、微辣/特辣等)</div>
              <Form.List name="weight" initialValue={[{}]}>
                {(weightFields, { add: weightAdd, remove: weightRemove }) => (
                  <>
                    {weightFields.map((weightField, index) => (
                      <Space key={weightField.key} align="baseline" className={styles.conBg}>
                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'specName']}
                          rules={[
                            {
                              required: true,
                              message: '请输入名称',
                            },
                          ]}
                        >
                          <Input style={{ width: '200px' }} placeholder="名称" />
                        </Form.Item>

                        {weightUnits.includes(
                          filterUnit(form.getFieldValue(['weight'])?.[index]?.unit),
                        ) && <span className="ant-form-text"> 约</span>}
                        <Form.Item
                          // noStyle
                          shouldUpdate={(prevValues, curValues) => false}
                        >
                          {form => {
                            let unit = form.getFieldValue(['weight'])?.[index]?.unit || '';
                            unit = filterUnit(unit);
                            if (!peopleUnits.includes(unit)) {
                              return (
                                <Form.Item
                                  style={{
                                    display:
                                      peopleUnits.includes(
                                        form.getFieldValue(['weight'])?.[index]?.unit,
                                      ) && 'none',
                                  }}
                                  {...weightField}
                                  name={[weightField.name, 'quantity']}
                                  rules={[
                                    {
                                      required: !peopleUnits.includes(
                                        form.getFieldValue(['weight'])?.[index]?.unit,
                                      ),
                                      message: '份量',
                                    },
                                    {
                                      validator: isIntegerNotZero,
                                      type: 'number',
                                      message: '请输入大于0的整数',
                                    },
                                  ]}
                                >
                                  <InputNumber
                                    style={{ width: '120px' }}
                                    max={999999999}
                                    min={0}
                                    placeholder="约 份量（数字）"
                                  />
                                </Form.Item>
                              );
                            }
                          }}
                        </Form.Item>
                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'unit']}
                          rules={[
                            {
                              // type: 'array',
                              required: true,
                              message: '请选择单位',
                            },
                          ]}
                        >
                          <Cascader
                            placeholder="请选择单位"
                            disabled={customer.isEdit && customer.isNormal}
                            showSearch={{ filter: filterCategoryOptions }}
                            fieldNames={{
                              label: 'name',
                              value: 'name',
                              children: 'children',
                            }}
                            // onChange={props.onCategoryChange}
                            options={unitsList}
                          />
                        </Form.Item>
                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'salePrice']}
                          rules={[
                            {
                              required: true,
                              message: '销售价',
                            },
                          ]}
                        >
                          <InputNumber
                            max={999999999}
                            min={0}
                            precision={2}
                            style={{ width: '120px' }}
                            placeholder="销售价（元）"
                          />
                        </Form.Item>
                        {/* <Form.Item
                          {...weightField}
                          name={[weightField.name, 'activityPrice']}
                          rules={[
                            {
                              required: false,
                              message: '活动价',
                            },
                          ]}
                        >
                          <InputNumber
                            max={999999999}
                            min={0}
                            precision={2}
                            style={{ width: '120px' }}
                            placeholder="活动价（元）"
                          />
                        </Form.Item> */}
                        {weightFields.length > 1 ? (
                          <MinusCircleOutlined onClick={() => weightRemove(weightField.name)} />
                        ) : null}
                      </Space>
                    ))}

                    <Form.Item>
                      <Button
                        type="primary"
                        onClick={() => weightAdd()}
                        block
                        style={{ width: '400px' }}
                        icon={<PlusOutlined />}
                      >
                        新增份量
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
            {
              <>
                <Form.Item>
                  <div>添加规格(如加料、甜度、辣度等)</div>
                  <Form.List name="specs" initialValue={[]}>
                    {(specsFields, { add, remove }) => (
                      <>
                        {specsFields.map((specsField, index) => (
                          <Form.Item key={specsField.key} className={styles.conBg}>
                            <Form.Item
                              {...specsField}
                              name={[specsField.name, 'specGroupName']}
                              rules={[
                                {
                                  required: true,
                                  whitespace: true,
                                  message: '请输入规格名称',
                                },
                              ]}
                              noStyle
                            >
                              <Input placeholder="规格名称" className={styles.nameWidth} />
                            </Form.Item>
                            <MinusCircleOutlined
                              className="dynamic-delete-button"
                              onClick={() => remove(specsField.name)}
                            />
                            <Form.List
                              {...specsField}
                              name={[specsField.name, 'specs']}
                              initialValue={[{}]}
                            >
                              {(specsInfoFields, { add: specsAdd, remove: specsRemove }) => (
                                <>
                                  {specsInfoFields.map(specsInfofield => (
                                    <Space key={specsInfofield.key} align="baseline">
                                      <Form.Item
                                        {...specsInfofield}
                                        name={[specsInfofield.name, 'specName']}
                                        rules={[
                                          {
                                            required: true,
                                            message: '请输入加价名称',
                                          },
                                        ]}
                                      >
                                        <Input style={{ width: '200px' }} placeholder="加价名称" />
                                      </Form.Item>
                                      <Form.Item
                                        {...specsInfofield}
                                        name={[specsInfofield.name, 'salePrice']}
                                        rules={[
                                          {
                                            required: true,
                                            message: '请输入加价金额（元）',
                                          },
                                        ]}
                                      >
                                        <InputNumber
                                          max={999999999}
                                          min={0}
                                          precision={2}
                                          style={{ width: '200px' }}
                                          placeholder="加价名称金额（元）"
                                        />
                                      </Form.Item>
                                      {specsInfoFields.length > 1 ? (
                                        <MinusCircleOutlined
                                          onClick={() => specsRemove(specsInfofield.name)}
                                        />
                                      ) : null}
                                    </Space>
                                  ))}
                                  <Form.Item>
                                    <Button
                                      type="dashed"
                                      onClick={() => specsAdd()}
                                      block
                                      style={{ width: '400px' }}
                                      icon={<PlusOutlined />}
                                    >
                                      新增加价
                                    </Button>
                                  </Form.Item>
                                </>
                              )}
                            </Form.List>
                          </Form.Item>
                        ))}
                        <Form.Item>
                          <Button
                            type="primary"
                            onClick={() => add()}
                            style={{ width: '400px' }}
                            icon={<PlusOutlined />}
                          >
                            新增规格
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                </Form.Item>
                <div className={styles.textStyle}>修改成功后，原库存将被替换，请谨慎操作！</div>

                <Form.Item
                  name="receptionVolume"
                  label="多规格库存"
                  className={styles.multiSpecification}
                >
                  <Button
                    size="small"
                    danger
                    style={{ marginBottom: '10px' }}
                    onClick={() => {
                      showAddRepertoryModal('all'); // 统一库存
                    }}
                    shape="round"
                  >
                    统一设置库存
                  </Button>
                  <div className={styles.rowWarp}>
                    {tempMultiSpu.length > 0 &&
                      tempMultiSpu?.map((item, idx) => (
                        <>
                          {item.unique && (
                            <>
                              <div key={idx} className={styles.specsBetween}>
                                <Form.Item>
                                  <div className={styles.specsBetween}>
                                    <div>{calcLabelName(item)} ：</div>
                                    <span className={styles.repertoryLimit}>
                                      {item?.serviceItem?.productStock}/
                                      {item?.serviceItem?.maxStock}
                                    </span>
                                    <div
                                      className={styles.specRepertory}
                                      onClick={() => {
                                        showAddRepertoryModal('multi', `${item.unique}`, item); // 多个库存
                                      }}
                                    >
                                      去设置
                                    </div>
                                  </div>
                                </Form.Item>
                              </div>
                            </>
                          )}
                        </>
                      ))}
                  </div>
                </Form.Item>
              </>
            }
          </>
        )}
      </Form>
      {/* 加入库存 */}
      <AddRepertoryModal
        ref={AddRepertoryRef}
        modifiedInventory={modifiedInventory}
        intactData={intactData}
        repertoryModel={repertoryModel}
      />
    </>
  );
});

export default TakeawayGoodsInfo;
