import React, { useState, forwardRef, useEffect, useImperativeHandle } from 'react';
import { Form, Button, Row, Col, Input, Select, Modal, notification, Popover } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import styles from '../common.less';
import { isIntegerNotZero, isCheckPriceOneDecimal } from '@/utils/validator';
import UUID from '@/utils/uuid';
import { debounce } from '@/utils/utils';
import localStorage from '@/utils/localStorage';
import { localAutoSaveKey } from '../utils';

const { Option } = Select;

const getCaiJson = gname => ({
  uuid: UUID.createUUID(),
  gName: gname,
  quantity: '',
  dishName: '',
  subtitle: '',
  unit: '份',
  price: '',
  skuId: '',
});

const FormCai = forwardRef((props, ref) => {
  const { gitem, groupName, groupkey, packageIndex, form, groupIndex } = props;
  const lists = form.getFieldValue('lists');
  const subTitles = lists[packageIndex].children[groupIndex].dishes.map(item => item.subtitle);
  const [subTitle, setSubTitle] = useState(subTitles);
  const onDel = (callback, name, key) => {
    // callback(name);
    props.onDelCai(packageIndex, groupkey, key);
  };

  const onChange = (e, i) => {
    const { value } = e.target;
    const arr = [...subTitle];
    arr[i] = value;
    setSubTitle(arr);
  };

  const onAdd = (callback, key) => {
    if (props.onAddCai(packageIndex, groupkey)) {
      callback(getCaiJson(groupName));
    }
  };

  return (
    <Form.List name={gitem}>
      {(items, { add, remove }) => (
        <>
          {items.map(({ key, name }, caiIndex) => (
            <Row gutter={24} key={`cai_${key}`} className={styles.caiRow}>
              <Col span={3}>
                <Form.Item name={[name, 'gName']}>
                  <Input readOnly hidden />
                  <span>{groupName}</span>
                </Form.Item>
              </Col>
              <Col span={3}>
                <Form.Item
                  name={[name, 'quantity']}
                  rules={[
                    { required: true, message: '请输入数量.' },
                    { validator: isIntegerNotZero, message: '请输入正确的数量' },
                  ]}
                >
                  <Input maxLength={10} />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Form.Item
                  name={[name, 'dishName']}
                  rules={[{ required: true, message: '请输入菜名.' }]}
                >
                  <Input maxLength={13} placeholder="最多13个字符" />
                </Form.Item>
              </Col>
              <Col span={2}>
                <Form.Item
                  mame={[name, 'unit']}
                  rules={[{ required: true, message: '请选择单位' }]}
                >
                  <Select defaultValue="份">
                    <Option value="份">份</Option>
                    <Option value="个">个</Option>
                    <Option value="瓶">瓶</Option>
                    <Option value="杯">杯</Option>
                    <Option value="串">串</Option>
                    <Option value="例">例</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={3}>
                <Form.Item
                  name={[name, 'price']}
                  rules={[
                    { required: true, message: '请输入价格.' },
                    { validator: isCheckPriceOneDecimal, message: '请输入正确的价格' },
                  ]}
                >
                  <Input maxLength={10} />
                </Form.Item>
              </Col>
              <Col span={4}>
                <Popover content={() => subTitle[caiIndex]} trigger="hover">
                  <Form.Item
                    name={[name, 'subtitle']}
                    onChange={e => onChange(e, caiIndex)}
                    // rules={[{ required: true, message: '请输入副标题' }]}
                  >
                    <Input maxLength={100} placeholder="最多100个字" />
                  </Form.Item>
                </Popover>
              </Col>
              <Col span={2}>
                <Button type="link" onClick={() => onDel(remove, name, key)}>
                  删除
                </Button>
              </Col>
              <Col span={3}>
                {caiIndex === 0 && (
                  <Button type="primary" icon={<PlusOutlined />} onClick={() => onAdd(add, key)}>
                    添加
                  </Button>
                )}
              </Col>
            </Row>
          ))}
        </>
      )}
    </Form.List>
  );
});

const FormGroup = forwardRef((props, ref) => {
  const { item, form, packageIndex, onAddCai, onDelCai } = props;
  const formInfo = form.getFieldsValue();
  return (
    <Form.List name={item}>
      {(items, { add, remove }) => (
        <>
          {items.map(({ key, name }, index) => (
            <div className={styles.groupMargin} key={`group_${key}`}>
              <Row gutter={24} className={styles.groupHeader}>
                <Col span={3}>组名</Col>
                <Col span={3}>数量</Col>
                <Col span={4}>标题</Col>
                <Col span={2}>单位</Col>
                <Col span={3}>价格</Col>
                <Col span={4}>副标题</Col>
                <Col span={2}>操作</Col>
                <Col span={3}>
                  <div>
                    <Form.Item name={[name, 'groupName']}>
                      <Input hidden readOnly />
                    </Form.Item>
                  </div>
                </Col>
              </Row>
              <FormCai
                gitem={[name, 'dishes']}
                packageIndex={packageIndex}
                groupIndex={index}
                form={form}
                groupkey={key}
                onAddCai={onAddCai}
                onDelCai={onDelCai}
                groupName={formInfo.lists[packageIndex].children[key].groupName}
              />
            </div>
          ))}
        </>
      )}
    </Form.List>
  );
});

const FormPackage = forwardRef((props, ref) => {
  const [visibleGroup, setVisibleGroup] = useState(false);
  const [groupName, setGroupName] = useState('');
  const [groupIndex, setGroupIndex] = useState(0);
  const [list, setList] = useState([]);
  const [form] = Form.useForm();

  const { validateFields, getFieldsValue } = form;

  const onCheck = async () => {
    try {
      const values = await validateFields();
      const arr = [];
      if (values && values.lists) {
        values.lists.forEach(item => {
          arr.push({
            setMealContent: [...item.children],
          });
        });
      }
      return arr;
    } catch {
      return null;
    }
  };

  const getValues = () => form.getFieldsValue();

  const getFormValues = debounce(() => {
    // const values = form.getFieldsValue();{ setMealContent: values }
    props.onValuesChange();
  }, 400);

  // 创建分组
  const onCreateGroup = () => {
    const str = groupName && groupName.trim();
    if (str) {
      const arr = [...list];
      const fieldsValue = getFieldsValue();
      const obj = {
        groupName: str,
        uuid: UUID.createUUID(),
        dishes: [getCaiJson(str)],
      };
      arr[groupIndex].children.push(obj);
      fieldsValue.lists[groupIndex].children.push(obj);
      setList(arr);
      form.setFieldsValue(fieldsValue);
      setVisibleGroup(!1);
    }
  };

  // 显示创建分组弹窗
  const onCreate = index => {
    setVisibleGroup(!0);
    setGroupIndex(index);
  };

  // 新增菜品
  const onAddCai = (i, j) => {
    const arr = [...list];
    const len = arr[i].children[j].dishes.length;
    if (len < 50) {
      arr[i].children[j].dishes.push(getCaiJson(arr[i].children[j].groupName));
      setList(arr);
      return true;
    }
    notification.error({
      message: '最多添加50个菜品',
    });
    return false;
  };
  // 删除菜品
  const onDelCai = (i, j, k) => {
    const arr = [...list];
    const arrList = getFieldsValue();
    const len = arr[i].children[j].dishes.length;
    if (len === 1) {
      arr[i].children.splice(j, 1);
      arrList.lists[i].children.splice(j, 1);
    } else {
      arr[i].children[j].dishes.splice(k, 1);
      console.log('arrList :>> ', [...arrList.lists]);
      arrList.lists[i].children[j].dishes.splice(k, 1);
    }
    setList(arr);
    form.setFieldsValue(arrList);
    getFormValues();
  };

  useEffect(() => {
    if (props.initData && props.initData.length) {
      if (props.initData.length !== list.length) {
        const arr = [];
        props.initData.forEach((item, i) => {
          let children = [];
          if (
            item.serviceItem &&
            item.serviceItem.setMealContent &&
            item.serviceItem.setMealContent.length
          ) {
            children = [...item.serviceItem.setMealContent];
          }
          arr.push({
            uuid: i,
            specName: `套餐${i + 1}`,
            children,
          });
        });
        setList(arr);
        form.setFieldsValue({
          lists: arr,
        });
      }
    } else {
      setList([]);
      form.setFieldsValue({
        lists: [],
      });
    }
  }, [props.initData]);

  useImperativeHandle(ref, () => ({
    onCheck,
    getValues,
  }));

  return (
    <div className={styles.formPackageBox}>
      <Form style={{ marginBottom: 10 }} form={form} onValuesChange={getFormValues}>
        <Form.List name="lists">
          {(fields, { add, remove }) => (
            <>
              {fields.map(({ name, key }, packageIndex) => (
                <div key={key}>
                  <div className={styles.subTitle}>
                    <Row gutter={24}>
                      <Col className={styles.subTitleTxt}>
                        <Form.Item key={`specName_${key}`} name={[name, 'specName']}>
                          <Input readOnly hidden />
                          <span>套餐{packageIndex + 1}</span>
                        </Form.Item>
                      </Col>
                      <Col span={3}>
                        <Button type="primary" size="small" onClick={() => onCreate(key)}>
                          新建分组
                        </Button>
                      </Col>
                    </Row>
                  </div>
                  <FormGroup
                    item={[name, 'children']}
                    onAddCai={onAddCai}
                    onDelCai={onDelCai}
                    packageIndex={packageIndex}
                    form={form}
                  />
                </div>
              ))}
            </>
          )}
        </Form.List>
      </Form>
      <Modal
        title="新建分组"
        visible={visibleGroup}
        destroyOnClose
        onOk={onCreateGroup}
        onCancel={() => setVisibleGroup(false)}
      >
        <Input
          placeholder="请输入分组名称，最多13个字"
          maxLength={13}
          onChange={e => setGroupName(e.target.value)}
        />
      </Modal>
    </div>
  );
});

export default FormPackage;
