/* 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,
  Modal,
  Switch,
  Row,
  Col,
  InputNumber,
  Cascader,
  Divider,
  DatePicker,
} 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 UploadImage from './UploadImage';
import AddSellTimeModal from './AddSellTimeModal';
import styles from '../common.less';
import AddRepertoryModal from './AddRepertoryModal';
import AddMultiSpecModal from './AddMultiSpecModal';
import { apiTagList, apiUnits } from '../service';
import { localAutoSaveKey } from '../utils';
import localStorage from '@/utils/localStorage';

const createInitValues = () => ({
  description: '', // 商品描述
  detailImageList: [], // 商品图片
  stock: '1', // 库存类型
  saleTimeType: 0, // 售卖时间
  singleDelivery: 0, // 单点不送
  list: 1, // 列出商品
  label: '',
});
const format = 'HH:mm';
const { RangePicker } = DatePicker;
const TakeawayGoodsInfo = forwardRef((props, ref) => {
  const { editData } = 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({});
  const [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 initialDealValue = [
    {
      specGroupName: '',
    },
  ];

  // 自定义加入菜单
  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 takeawayCalc = takeawayData => {
    // 商品基本信息编辑商品名称
    const { infoMation: name, infoMation, takeawayItem } = takeawayData;
    console.log('i========', infoMation, takeawayItem, repertoryType);
    //  weight 份量  specs规格 生成sku规则 weight * specs
    const {
      specs = tempSpecs,
      weight = tempWeight,
      description,
      detailImageList,
      list,
      minPurchaseNum = 0,
      saleDates,
      maxStock = 0,
      saleTimes = [],
      label,
      unit,
      quantity,
      productStock = 0,
      salePrice,
      singleDelivery,
      saleTimeType,
      autoStock = 0,
      skuList,
      id,
      categoryId,
    } = takeawayItem;
    console.log('skuList====', infoMation, takeawayItem, skuList);
    const singularSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 单规格
    const multiSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 多规格
    // const multiSpu = customer.isEdit ? skuList:[]; // 多库存spu、
    const multiSpu = []; // 多库存spu、

    let singularSpu = []; // 单库存spu
    const saleTimesTemp = [];
    let initIndex = 0;
    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,
        productStock,
        specGroupName: '份量',
      };
      singularSpecList[0].specs = [specs];
      singularSpu = [{ ...temp, specs: [specs] }];
      setSingularSpu(singularSpu);
    }
    // 多规格
    if (+repertoryType === 2) {
      if (name || editData.name) {
        if (weight.length) {
          weight.forEach((item, weightIndex) => {
            if (item?.unit && item?.unit.length) {
              item.unit =
                item?.unit &&
                (Array.isArray(item?.unit) ? item.unit.slice(item.unit.length - 1)[0] : item.unit);
            }
            if (item && !item.specGroupName) {
              item.specGroupName = '份量';
            }
            if (item && !item.generateSku) {
              item.generateSku = 1;
            }
            multiSpecList[0].specs = weight; // 处理specList
            // 循环一次 插入规则列表
            let isFirstLoops = true;

            if (specs.length) {
              specs.forEach((specsItem, specsIndex) => {
                if (specsItem && !specsItem.generateSku) {
                  specsItem.generateSku = 1;
                }
                if (isFirstLoops && multiSpecList.length < specs.length + 1) {
                  multiSpecList.push(specsItem); // 处理specList
                }
                if (specsItem.specs.length > 1) {
                  specsItem.specs.forEach((itm, idx) => {
                    const params = {
                      initIndex,
                      unique: `${item.specName}-${specsItem.specGroupName}-${specsItem.specs[idx].specName}`,
                      ...JSON.parse(JSON.stringify(temp)),
                      // ...intactData?.items[initIndex],
                      specs: [
                        { ...item },
                        { ...specsItem.specs[idx], specGroupName: specsItem.specGroupName },
                      ],
                    };

                    multiSpu.push(params); // 处理spu
                    initIndex++;
                  });
                } else {
                  const params = {
                    initIndex,
                    unique: `${item.specName}-${specsItem.specGroupName}-${specsItem.specs[0].specName}`,
                    ...JSON.parse(JSON.stringify(temp)),
                    // ...intactData?.items[initIndex],
                    specs: [
                      { ...item },
                      { ...specsItem.specs[0], specGroupName: specsItem.specGroupName },
                    ],
                  };
                  multiSpu.push(params); // 处理spu
                  initIndex++;
                }
              });
              isFirstLoops = false;
            } else {
              const params = {
                initIndex,
                unique: `${item?.specName}`,
                ...JSON.parse(JSON.stringify(temp)),
                // ...intactData?.items[initIndex],
                specs: [{ ...item }],
              };
              multiSpu.push(params); // 处理spu
              initIndex++;
            }
          });
        }
      }

      if (tempMultiSpu.length) {
        multiSpu.forEach((item, index) => {
          tempMultiSpu.forEach((itm, idx) => {
            if (item.unique === itm.unique) {
              item.serviceItem = objectComparison(item.serviceItem, itm);
              item.id = itm.id;
            }
          });
        });
      }
      console.log(multiSpu, tempMultiSpu, 'multiSpumultiSpu');
      setMultiSpu(multiSpu);
    }
    // +repertoryType === 1 单规格 2多规格
    const intactDataTemp = {
      ...takeawayItem,
      id,
      type: 5, // 外卖类型
      ...infoMation,
      label: label && label.toString(),
      list,
      description,
      detailImageList,
      singleDelivery,
      specList: +repertoryType === 1 ? singularSpecList : multiSpecList, // 单库存和多库存specList
      items: +repertoryType === 1 ? singularSpu : JSON.parse(JSON.stringify(multiSpu)),
      // categoryId:
      //   (
      //     infoMation?.categoryId &&
      //     infoMation?.categoryId?.slice(infoMation?.categoryId?.length - 1)
      //   )?.toString() ||
      //   (Array.isArray(categoryId) && categoryId?.slice(categoryId?.length - 1)?.toString()),
    };

    setIntactData(intactDataTemp);
    console.log('intactData======>', form.getFieldsValue(), intactDataTemp);
    return intactData;
  };
  // 过滤对象
  const objectComparison = (item, itm) => {
    let {
      serviceItem: { maxStock, autoStock, productStock },
    } = itm;
    let params = { maxStock, autoStock, productStock: productStock || itm.productStock };
    let temp = { ...item, ...params };
    return temp;
  };
  const onChange = () => {};
  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    console.log('values', values);
    props.onValuesChange({ takeawayItem: JSON.parse(JSON.stringify(values)) });
    const takeawayData = customer.isEdit
      ? { takeawayItem: Object.assign({}, editData, values) }
      : localStorage.get(localAutoSaveKey) || {};
    setTakeawayData(takeawayData);
    takeawayCalc(takeawayData);
  }, 400);
  // 设置库存
  const modifiedInventory = (type, idx, values) => {
    const { productStock, maxStock, autoStock } = values;
    if (type === 'multi') {
      multiSpu.map(item => {
        if (item.unique === idx) {
          item.serviceItem.productStock = productStock;
          item.serviceItem.autoStock = autoStock;
          item.serviceItem.maxStock = maxStock;
        }
        return item;
      });
      let temp = JSON.parse(JSON.stringify(multiSpu));
      tempMultiSpu.push(...temp);
      setTempMultiSpu(tempMultiSpu);
      setMultiSpu(temp);
    }
    if (type === 'all') {
      multiSpu.map(item => {
        item.serviceItem.productStock = productStock;
        item.serviceItem.autoStock = autoStock;
        item.serviceItem.maxStock = maxStock;
        return item;
      });
      let temp = JSON.parse(JSON.stringify(multiSpu));
      tempMultiSpu.push(...temp);
      setTempMultiSpu(tempMultiSpu);
      setMultiSpu(multiSpu);
    }
    console.log('=========', multiSpu, 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 => {
    setRepertoryType(`${e.target.value}`);
  };
  // 勾选库存设置
  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,
    });
  };
  // 显示加入库存弹框
  const showAddRepertoryModal = (type, idx, item) => {
    AddRepertoryRef.current.setOpenRepertory(true);
    setRepertoryModel({ type, idx, item });
  };
  const onFinish = values => {
    console.log('Received values of form:', values);
  };
  // 拼接sku 名称
  const calcLabelName = (intactData, item) => {
    const tempName = `${intactData?.name || ''}`;
    const tempSpecName = `${item?.specs[0]?.specName || ''}`;
    const tempQuantity = `(${item.specs[0]?.quantity || ''}`;
    const tempUnit = `${item.specs[0]?.unit || ''})`;
    const tempSecondSpecName = `${item.specs[1]?.specName || ''}`;
    const isShow = tempQuantity && tempUnit && '+';
    return `${tempName} ${tempSpecName} ${tempQuantity} ${isShow} ${tempUnit} ${tempSecondSpecName}`;
  };
  const init = async () => {
    if (!tagList.length) {
      const res = await apiTagList();
      setTagList(res.data || []);
    }
    if (!unitsList.length) {
      const res = await apiUnits();
      setUnitsList(res.data || []);
    }

    setTempMultiSpu([]);
    return false;
  };
  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (!editData) return;
      let { label, firstCategoryId, secondCategoryId, thirdCategoryId, id } = editData;
      editData.label = label.split(',');
      if (editData?.skuList.length) {
        editData.minPurchaseNum = editData?.skuList[0]?.serviceItem.minPurchaseNum;
        // 单规格
        if (editData?.skuList.length === 1) {
          let {
            productStock,
            shopId,
            specs,
            serviceItem: { maxStock, saleTimeType, saleDates, saleTimes, id },
          } = editData?.skuList[0];
          let { quantity, unit, salePrice } = specs[0];
          editData.productStock = productStock;
          editData.quantity = quantity;
          editData.unit = unit;
          editData.salePrice = salePrice;
          editData.maxStock = maxStock;
          editData.categoryId = [firstCategoryId, secondCategoryId, thirdCategoryId];
          editData.saleTimeType = saleTimeType;
          editData.saleDates = saleDates;
          editData.saleTimes = saleTimes.length
            ? saleTimes.map(item => {
                return [moment(item?.startTime, format), moment(item?.endTime, format)];
              })
            : [];
          editData.productRefShopId = editData.shopId;
          editData.skuId = id;
          form.setFieldsValue(editData);

          setTimeType(saleTimeType);
        } else {
          // 多规格
          setRepertoryType(`2`);
          let {
            serviceItem: { saleTimeType, saleDates, saleTimes },
          } = editData?.skuList[0];
          let specList = editData?.specList;
          let weight = specList.filter(item => item.specGroupName === '份量');
          let specs = specList.filter(item => item.specGroupName !== '份量');
          editData.categoryId = [firstCategoryId, secondCategoryId, thirdCategoryId];
          editData.saleTimeType = saleTimeType;
          editData.saleDates = saleDates;
          editData.saleTimes = saleTimes.length
            ? saleTimes.map(item => {
                return [moment(item?.startTime, format), moment(item?.endTime, format)];
              })
            : [];
          editData.productRefShopId = editData.shopId;
          // setTempWeight(weight)
          // setTempSpecs(specs)

          setTimeType(saleTimeType);
          form.setFieldsValue({ weight: weight[0].specs });
          form.setFieldsValue(editData);
          form.setFieldsValue({ specs });
          console.log('editData?.skuList', editData?.skuList);

          const tempMultiSpu = editData?.skuList.map(item => {
            if (item) {
              let weightIdx = item.specs.findIndex(itm => itm.specGroupName === '份量');
              console.log('weightIdx', weightIdx);
              let specsIdx = item.specs.findIndex(itm => itm.specGroupName !== '份量');
              console.log('specsIdx', specsIdx);
              item.unique = `${item.specs[weightIdx]?.specName}-${item.specs[specsIdx]?.specGroupName}-${item.specs[specsIdx]?.specName}`;
            }
            return item;
          });
          setTempMultiSpu(tempMultiSpu || []);
        }

        form.setFieldsValue({ productRefShopId: editData.shopId });
        onCardSuccessImageList(editData?.detailImageList);
        getFormValues();
        // setInitValue({ ...editData });
      }
    }
  }, [customer.isEdit, editData]);
  useEffect(() => {
    setIntactData(intactData);
  }, [intactData]);
  useEffect(() => {
    init();
  }, []);
  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}
            setPictureList={list => onCardSuccessImageList(list)}
          />
        </Form.Item>

        <Title title="商品售卖信息" />
        <Form.Item
          name="minPurchaseNum"
          label="最少购买"
          // rules={[{ required: true, message: '每日最低接待量' }]}
        >
          <InputNumber min={1} 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>
                      <Button
                        type="dashed"
                        onClick={() => add()}
                        style={{ width: '60%' }}
                        icon={<PlusOutlined />}
                      >
                        新增售卖时段
                      </Button>
                    </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.Item
                name="quantity"
                style={{
                  display: 'inline-block',
                }}
                rules={[{ required: true, message: '请输入分量' }]}
              >
                <InputNumber min={1} style={{ width: 200 }} placeholder="请输入数字" />
              </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={props.onCategoryChange}
                  options={unitsList}
                />
              </Form.Item>
            </Form.Item>
            <Form.Item
              name="salePrice"
              label="销售价格"
              rules={[{ required: true, message: '请输入销售价格' }]}
            >
              <InputNumber min={0} 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: '请填写剩余库存' }]}
              >
                <InputNumber
                  min={0}
                  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: true, message: '请填写最大库存' }]}
            >
              <InputNumber
                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 &&
                (takeawayData?.infoMation?.name || takeawayData.takeawayItem.name) &&
                singularSpu.map((item, index) => (
                  <div className={styles.specsBetween}>
                    <Form.Item label={calcLabelName(intactData, item, 'singular')}>
                      <div className={styles.specsBetween}>
                        <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 => (
                      <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>

                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'quantity']}
                          rules={[
                            {
                              required: true,
                              message: '份量',
                            },
                          ]}
                        >
                          <Input style={{ width: '200px' }} placeholder="约 份量（数字）" />
                        </Form.Item>
                        <span className="ant-form-text"> 约</span>
                        <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: '销售价',
                            },
                          ]}
                        >
                          <Input style={{ width: '200px' }} placeholder="销售价（元）" />
                        </Form.Item>
                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'activityPrice']}
                          rules={[
                            {
                              required: true,
                              message: '活动价',
                            },
                          ]}
                        >
                          <Input style={{ width: '200px' }} placeholder="活动价（元）" />
                        </Form.Item>
                        <MinusCircleOutlined onClick={() => weightRemove(weightField.name)} />
                      </Space>
                    ))}

                    <Form.Item>
                      <Button
                        type="primary"
                        onClick={() => weightAdd()}
                        block
                        style={{ width: '400px' }}
                        icon={<PlusOutlined />}
                      >
                        新增份量
                      </Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
            {/* takeawayData?.takeawayItem?.weight?.length > 0 && */}
            {
              <>
                <Form.Item>
                  <div>添加规格(如加料、甜度、辣度等)</div>
                  <Form.List
                    name="specs"
                    initialValue={
                      [
                        // {
                        //   specGroupName: '',
                        //   specs: [],
                        // },
                      ]
                    }
                  >
                    {(specsFields, { add, remove }) => (
                      <>
                        {specsFields.map((specsField, index) => (
                          <Form.Item key={specsField.key} className={styles.conBg}>
                            <Form.Item
                              {...specsField}
                              validateTrigger={['onChange', 'onBlur']}
                              name={[specsField.name, 'specGroupName']}
                              rules={[
                                {
                                  required: true,
                                  whitespace: true,
                                  message: '请输入规格名称',
                                },
                              ]}
                              noStyle
                            >
                              <Input placeholder="规格名称" className={styles.nameWidth} />
                            </Form.Item>
                            {/* {specsFields.length > 1 ? ( */}
                            <MinusCircleOutlined
                              className="dynamic-delete-button"
                              onClick={() => remove(specsField.name)}
                            />
                            {/* ) : null} */}
                            <Form.List
                              {...specsField}
                              name={[specsField.name, 'specs']}
                              initialValue={[
                                {
                                  specName: '',
                                  salePrice: '',
                                },
                              ]}
                            >
                              {(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
                                          style={{ width: '200px' }}
                                          placeholder="加价名称金额（元）"
                                        />
                                      </Form.Item>

                                      <MinusCircleOutlined
                                        onClick={() => specsRemove(specsInfofield.name)}
                                      />
                                    </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}>
                    {multiSpu.length > 0 &&
                      multiSpu?.map((item, idx) => (
                        <>
                          {item.unique && (
                            <>
                              <div key={idx} className={styles.specsBetween}>
                                <Form.Item label={calcLabelName(intactData, item)}>
                                  <div className={styles.specsBetween}>
                                    <span className={styles.repertoryLimit}>
                                      {item?.serviceItem?.productStock}/
                                      {item?.serviceItem?.maxStock}
                                    </span>
                                    <div
                                      className={styles.specRepertory}
                                      onClick={() => {
                                        showAddRepertoryModal('multi', `${item.unique}`, item); // 多个库存
                                      }}
                                    >
                                      设置库存{item.unique}
                                    </div>
                                  </div>
                                </Form.Item>
                              </div>
                            </>
                          )}
                        </>
                      ))}
                  </div>
                </Form.Item>
              </>
            }
          </>
        )}
      </Form>
      {/* 加入库存 */}
      <AddRepertoryModal
        ref={AddRepertoryRef}
        modifiedInventory={modifiedInventory}
        intactData={intactData}
        repertoryModel={repertoryModel}
      />
      {/* 加入多规格 */}
      <AddMultiSpecModal ref={AddMultiSpecRef} />
    </>
  );
});

export default TakeawayGoodsInfo;
