/* 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, apiGetShopDetail } from '../service';
import { localAutoSaveKey } from '../utils';
import localStorage from '@/utils/localStorage';

const createInitValues = () => ({
  description: '', // 商品描述
  detailImageList: [], // 商品图片
  stock: '1', // 库存类型
  saleTimeType: 0, // 售卖时间
  singleDelivery: 0, // 单点不送
  list: 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 [newCategoryList, setNewCategoryList] = useState({});
  const addSellTimeRef = useRef(null);
  const AddRepertoryRef = useRef(null);
  const AddMultiSpecRef = useRef(null);
  const [saleDates, setSaleDates] = useState({
    saleDates: [],
    saleTimes: [],
    // saleTimes: [[moment('22-02', 'HH:mm'), moment('23-02', 'HH:mm')]],
  }); // 可售日期
  const [timeType, setTimeType] = useState(0);
  const [repertoryType, setRepertoryType] = useState('1');
  const [tagList, setTagList] = useState([]);
  const [unitsList, setUnitsList] = useState([]);
  const [takeawayData, setTakeawayData] = useState({});
  // const [multiSpecList, setMultiSpecList] = useState([]);
  // const [singularSpecList, setSingularSpecList] = 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 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;
    //  weight 份量  specs规格 生成sku规则 weight * specs
    const {
      specs = [],
      weight = [],
      description,
      detailImageList,
      list,
      minPurchaseNum = 0,
      saleDates,
      maxStock = 0,
      saleTimes = [],
      label,
      unit = [],
      quantity,
      productStock = 0,
      salePrice,
      singleDelivery,
      saleTimeType,
      autoStock = 0,
    } = takeawayItem;
    const singularSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 单规格
    const multiSpecList = [{ specGroupName: '份量', generateSku: 1, specs: [] }]; // 多规格
    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,
      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: (unit && unit.splice(unit.length - 1)[0]) || '',
        productStock,
        specGroupName: '份量',
      };
      singularSpecList[0].specs = [specs];
      singularSpu = [{ ...temp, specs: [specs] }];
      setSingularSpu(singularSpu);
    }
    // 多规格
    if (+repertoryType === 2) {
      if (name) {
        console.log('weight', weight);
        if (weight.length) {
          weight.forEach((item, weightIndex) => {
            console.log('eee====', item);
            if (item?.unit && item.unit.length) {
              item.unit = item.unit.slice(item.unit.length - 1).toString();
            }
            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++;
            }
          });
        }
      }
      // console.log('multiSpu', multiSpu);

      console.log('multiSpu===1111', multiSpu);
      if (tempMultiSpu.length) {
        multiSpu.forEach((item, index) => {
          tempMultiSpu.forEach((itm, idx) => {
            if (item.unique === itm.unique) {
              item.serviceItem = objectComparison(item.serviceItem, itm);
            }
          });
        });
      }

      // debugger
      console.log('multiSpu===2222', multiSpu);

      setMultiSpu(multiSpu);
    }
    // debugger
    // +repertoryType === 1 单规格 2多规格
    const intactDataTemp = {
      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(),
    };
    console.log('intactData======>', intactData);
    setIntactData(intactDataTemp);
    return intactData;
  };
  // 过滤对象
  const objectComparison = (item, itm) => {
    let {
      serviceItem: { maxStock, autoStock, productStock },
    } = itm;
    let params = { maxStock, autoStock, productStock };
    let temp = { ...item, ...params };
    return temp;
  };
  const onChange = () => {};
  const onDealFinish = values => {
    console.log('Received values of form:', values);
  };
  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
    console.log('values========', values);
    props.onValuesChange({ takeawayItem: values });
    const takeawayData = localStorage.get(localAutoSaveKey);
    console.log('takeawayData', takeawayData);
    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);
      console.log('33333========>', multiSpu, tempMultiSpu);

      // if (intactData?.items.length) {
      //   intactData.items[+idx].serviceItem.productStock = productStock;
      //   intactData.items[+idx].serviceItem.autoStock = autoStock;
      //   intactData.items[+idx].serviceItem.maxStock = maxStock;
      //   console.log('index===2222', +idx, intactData);
      //   const temp = { ...intactData };
      //   setIntactData(temp);
      // }
    }
    if (type === 'all') {
      if (intactData?.items.length) {
        intactData?.items.forEach(item => {
          item.serviceItem.productStock = productStock;
          item.serviceItem.autoStock = autoStock;
          item.serviceItem.maxStock = maxStock;
          return item;
        });
        const temp = { ...intactData };
        setIntactData(temp);
      }
    }

    return false;
  };
  const querGetShopDetail = async () => {
    let params = {
      id: '638899799727110',
      shopId: 15,
    };
    const result = await apiGetShopDetail(params);
    console.log('result', result);
  };
  const fileterBrandOptions = (input, options) => options.children.includes(input);

  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 radioChangeEvent = key => {
    const value = form.getFieldValue(key);
    setInitValue({
      ...initValue,
      [key]: value,
    });
  };
  // 自定义菜单下拉
  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 => {
    console.log('e=======', 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 || []);
    }
    querGetShopDetail();
    setTempMultiSpu([])
    return false;
  };
  useEffect(() => {
    if (customer.isEdit || customer.isUseCache) {
      if (!editData) return;
      form.setFieldsValue(editData);
      setInitValue({ ...editData });
    }
  }, [customer.isEdit, customer.isUseCache, 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={[[]]}
                // rules={[
                //   {
                //     validator: async (_, times) => {
                //       if (!times || times.length < 2) {
                //         return Promise.reject(new Error('At least 2 passengers'));
                //       }
                //     },
                //   },
                // ]}
              >
                {(fields, { add, remove }) => (
                  <>
                    {fields.map((field, index) => (
                      <Form.Item
                        // {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                        required={false}
                        key={field.key}
                        className={styles.deal}
                      >
                        <Form.Item
                          className={styles.deal}
                          {...field}
                          // validateTrigger={['onChange', 'onBlur']}
                          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="商品标签"
          // rules={[{ type: 'array', required: true, message: '请输入售卖时间!' }]}
        >
          <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="规格信息" />

        {/* <Form.Item label="限购" name="limitPurchase" valuePropName="checked">
        <Checkbox onChange={() => radioChangeEvent('limitPurchase')}>
          <b style={{ marginLeft: 10 }}>启用限购</b>
          <span style={{ marginLeft: 10 }} className="ant-form-text">
            限制每人可购买数量
          </span>
        </Checkbox>
      </Form.Item> */}

        <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={[{ 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 &&
                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="deal">
                {(dealFields, { add, remove }) => (
                  <>
                    {dealFields.map((field, index) => (
                      <Form.Item key={field.key} className={styles.conBg}>
                        <Form.Item
                          {...field}
                          validateTrigger={['onChange', 'onBlur']}
                          name={[field.name, 'specGroupName']}
                          rules={[
                            {
                              required: true,
                              whitespace: true,
                              message: '请输入名称例如（份量）',
                            },
                          ]}
                          noStyle
                        >
                          <Input
                            placeholder="请输入名称"
                            style={{
                              width: '60%',
                            }}
                          />
                        </Form.Item>
                        {dealFields.length > 1 ? (
                          <MinusCircleOutlined
                            className="dynamic-delete-button"
                            onClick={() => remove(field.name)}
                          />
                        ) : null} */}
              <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>
                    ))} */}

              {/* <Form.Item>
                      <Button
                        type="primary"
                        onClick={() => add()}
                        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">
                    {(specsFields, { add, remove }) => (
                      <>
                        {specsFields.map((field, index) => (
                          <Form.Item key={field.key} className={styles.conBg}>
                            <Form.Item
                              {...field}
                              validateTrigger={['onChange', 'onBlur']}
                              name={[field.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(field.name)}
                              />
                            ) : null}
                            <Form.List
                              {...field}
                              name={[field.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;
