/* 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: $t('portion.size'), generateSku: 1, specs: [] }]; // 单规格
    const multiSpecList = [{ specGroupName: $t('portion.size'), 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: $t('portion.size'),
      };
      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($t('portion.name.must.be.unique'));
        }
        // 新增对比数据
        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}
      >{$t('add.custom.sale.time')}</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)) && $t('approx')) || ''
          : ''
      } ${
        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 === $t('precise.weight.unit'));
      const tempPeople = res.data.filter(item => item.name === $t('suitable.for'));

      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 === $t('portion.size'));
      const specs = specList?.filter(item => item.specGroupName !== $t('portion.size'));
      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($t('approx')) > -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($t('approx')) > -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 === $t('portion.size'));
          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($t('approx')) > -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 === $t('portion.size'));
              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={$t('product.details')} />
        <Form.Item name="description" label={$t('product.description')}>
          <Input.TextArea
            showCount
            maxLength={200}
            style={{ width: 400 }}
            placeholder={$t('enter.product.description')}
          />
        </Form.Item>
        <Form.Item
          name="detailImageList"
          label={$t('product.image')}
          extra={$t('supports.jpgpng.750px.wide.200kb.max.5.images')}
        >
          <UploadImage
            name="detailImageList"
            limit={5}
            disabled={customer.isDisabled}
            pictures={detailImageList}
            limitPicHeight="true"
            setPictureList={list => onCardSuccessImageList(list)}
          />
        </Form.Item>

        <Title title={$t('product.sales.info')} />
        <Form.Item
          name="minPurchaseNum"
          label={$t('minimum.purchase')}
          rules={[
            { required: true, message: $t('enter.min.purchase') },
            {
              validator: isIntegerNotZero,
              type: 'number',
              message: $t('enter.integer.0'),
            },
          ]}
        >
          <InputNumber min={1} max={999999999} style={{ width: 200 }} placeholder={$t('enter.purchase.quantity')} />
        </Form.Item>
        <Form.Item
          name="saleTimeType"
          label={$t('sale.time')}
          // rules={[{ type: 'array', required: true, message: '请输入售卖时间!' }]}
        >
          <Radio.Group onChange={onChangeTime}>
            <Radio value={0}>{$t('all.day')}</Radio>
            <Radio value={1}>{$t('custom.sale.time')}</Radio>
          </Radio.Group>
        </Form.Item>
        {+timeType === 1 && (
          <>
            <Form.Item name="saleDates" label={$t('sale.period.multiple.allowed')}>
              <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={$t('sale.period')}>
              <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: $t('enter.sale.time'),
                            },
                          ]}
                        >
                          <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 />}
                        >{$t('add.sale.period')}</Button>
                      ) : null}
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </>
        )}
        <Form.Item name="label" label={$t('product.tags')}>
          <Select
            // mode="multiple"
            allowClear
            placeholder={$t('select.product.tag')}
            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={$t('singleitem.delivery')}
          extra={$t('no.standalone.orders')}
        >
          <Radio.Group>
            <Radio value={1}>{$t('singleitem.deliverable')}</Radio>
            <Radio value={0}>{$t('singleitem.not.deliverable')}</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item name="list" label={$t('list.products')} extra={$t('show.product.when.enabled')}>
          <Radio.Group>
            <Radio value={1}>{$t('yes')}</Radio>
            <Radio value={0}>{$t('no')}</Radio>
          </Radio.Group>
        </Form.Item>
        <Title title={$t('spec.info')} />
        {!customer.isEdit && (
          <Form.Item label={$t('inventory')} name="stock">
            <Radio.Group
              options={ENUM_REPERTORY}
              onChange={onChangeRepertory}
              value="1"
              buttonStyle="solid"
              optionType="button"
            />
          </Form.Item>
        )}
        {/* 单规格 */}
        {repertoryType === '1' && (
          <>
            <Form.Item label={$t('portion.size')} className={styles.required}>
              {form.getFieldValue(['unit']) &&
                weightUnits.includes(filterUnit(form.getFieldValue(['unit']))) && (
                  <span className="ant-form-text">{$t('approx')}</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: $t('enter.portion') },
                          {
                            validator: isCheckPriceTwoDecimal,
                            type: 'number',
                            message: $t('keep.2.decimal.places'),
                          },
                        ]}
                      >
                        <InputNumber
                          min={1}
                          max={999999999}
                          style={{ width: 200 }}
                          placeholder={$t('numbers.required')}
                        />
                      </Form.Item>
                    );
                  }
                }}
              </Form.Item>

              <Form.Item
                name="unit"
                rules={[{ required: true, message: $t('select.unit') }]}
                // rules={[{ type: 'array', required: true, message: '请选择单位' }]}
                style={{
                  display: 'inline-block',
                  margin: '0 8px',
                }}
              >
                <Cascader
                  placeholder={$t('select.unit')}
                  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={$t('sales.price')}
              rules={[{ required: true, message: $t('enter.sale.price') }]}
            >
              <InputNumber
                min={0}
                max={999999999}
                precision={2}
                style={{ width: 200 }}
                placeholder={$t('cny')}
              />
            </Form.Item>
            <Form.Item className={styles.itemInline}>
              <Form.Item
                name="productStock"
                label={$t('remaining.stock')}
                style={{
                  display: 'flex',
                  marginRight: '8px',
                }}
                rules={[
                  { required: true, message: $t('enter.remaining.stock') },
                  {
                    validator: isIntegerNotZero,
                    type: 'number',
                    message: $t('enter.integer.0'),
                  },
                ]}
              >
                <InputNumber
                  min={0}
                  max={999999999}
                  style={{ width: 200, display: 'inline-block' }}
                  placeholder={$t('input.required')}
                />
              </Form.Item>
              <Form.Item style={{ width: 200, display: 'inline-block' }}>
                <Radio.Group value={repertoryState} onChange={onChangeSetRepertory}>
                  <Radio.Button value="0">{$t('clear')}</Radio.Button>
                  <Radio.Button value="1">{$t('max')}</Radio.Button>
                </Radio.Group>
              </Form.Item>
            </Form.Item>
            <Form.Item
              name="maxStock"
              label={$t('max.stock')}
              rules={[
                { required: !isRequired, message: $t('enter.max.stock') },
                {
                  validator: isIntegerNotZero,
                  type: 'number',
                  message: $t('enter.integer.0'),
                },
              ]}
            >
              <InputNumber
                max={999999999}
                min={0}
                style={{ width: 200 }}
                placeholder={$t('input.required')}
                onChange={onChangeMaxStock}
              />
            </Form.Item>
            <Form.Item name="autoStock" label={$t('autoreplenish')} valuePropName="checked">
              <Switch
                checkedChildren={$t('enable')}
                unCheckedChildren={$t('close')}
                // 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>{$t('portion.size.eg.largesmall.mildspicy')}</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: $t('enter.name'),
                            },
                          ]}
                        >
                          <Input style={{ width: '200px' }} placeholder={$t('name')} />
                        </Form.Item>

                        {weightUnits.includes(
                          filterUnit(form.getFieldValue(['weight'])?.[index]?.unit),
                        ) && <span className="ant-form-text">{$t('approx')}</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: $t('portion.size'),
                                    },
                                    {
                                      validator: isIntegerNotZero,
                                      type: 'number',
                                      message: $t('enter.integer.0'),
                                    },
                                  ]}
                                >
                                  <InputNumber
                                    style={{ width: '120px' }}
                                    max={999999999}
                                    min={0}
                                    placeholder={$t('approx.portions')}
                                  />
                                </Form.Item>
                              );
                            }
                          }}
                        </Form.Item>
                        <Form.Item
                          {...weightField}
                          name={[weightField.name, 'unit']}
                          rules={[
                            {
                              // type: 'array',
                              required: true,
                              message: $t('select.unit'),
                            },
                          ]}
                        >
                          <Cascader
                            placeholder={$t('select.unit')}
                            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: $t('selling.price'),
                            },
                          ]}
                        >
                          <InputNumber
                            max={999999999}
                            min={0}
                            precision={2}
                            style={{ width: '120px' }}
                            placeholder={$t('price')}
                          />
                        </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 />}
                      >{$t('add.portion')}</Button>
                    </Form.Item>
                  </>
                )}
              </Form.List>
            </Form.Item>
            {
              <>
                <Form.Item>
                  <div>{$t('add.specs.eg.toppings.sweetness.spiciness')}</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: $t('enter.spec.name'),
                                },
                              ]}
                              noStyle
                            >
                              <Input placeholder={$t('spec.name')} 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: $t('enter.markup.name'),
                                          },
                                        ]}
                                      >
                                        <Input style={{ width: '200px' }} placeholder={$t('surcharge.name')} />
                                      </Form.Item>
                                      <Form.Item
                                        {...specsInfofield}
                                        name={[specsInfofield.name, 'salePrice']}
                                        rules={[
                                          {
                                            required: true,
                                            message: $t('enter.markup.amount'),
                                          },
                                        ]}
                                      >
                                        <InputNumber
                                          max={999999999}
                                          min={0}
                                          precision={2}
                                          style={{ width: '200px' }}
                                          placeholder={$t('surcharge.amount')}
                                        />
                                      </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 />}
                                    >{$t('add.markup')}</Button>
                                  </Form.Item>
                                </>
                              )}
                            </Form.List>
                          </Form.Item>
                        ))}
                        <Form.Item>
                          <Button
                            type="primary"
                            onClick={() => add()}
                            style={{ width: '400px' }}
                            icon={<PlusOutlined />}
                          >{$t('add.spec')}</Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                </Form.Item>
                <div className={styles.textStyle}>{$t('warning.original.inventory.will.be.overwritten.after.edit')}</div>

                <Form.Item
                  name="receptionVolume"
                  label={$t('multispec.inventory')}
                  className={styles.multiSpecification}
                >
                  <Button
                    size="small"
                    danger
                    style={{ marginBottom: '10px' }}
                    onClick={() => {
                      showAddRepertoryModal('all'); // 统一库存
                    }}
                    shape="round"
                  >{$t('bulk.inventory.setup')}</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); // 多个库存
                                      }}
                                    >{$t('go.to.settings')}</div>
                                  </div>
                                </Form.Item>
                              </div>
                            </>
                          )}
                        </>
                      ))}
                  </div>
                </Form.Item>
              </>
            }
          </>
        )}
      </Form>
      {/* 加入库存 */}
      <AddRepertoryModal
        ref={AddRepertoryRef}
        modifiedInventory={modifiedInventory}
        intactData={intactData}
        repertoryModel={repertoryModel}
      />
    </>
  );
});

export default TakeawayGoodsInfo;
