import React, { useState, useEffect, forwardRef, useRef, useImperativeHandle } from 'react';
import { Button, Modal, Form, Switch, Input, Select } from 'antd';
import styles from '../common.less';
import { apiCreateShop } from '../service';

const AddMenusModal = (props, ref) => {
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [formProject] = Form.useForm();
  const [menusSwitch, setMenusSwitch] = useState(0); // 分组开启状态

  // const {
  //   queryShopList,
  // } = props;
  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    setOpen: newVal => {
      setOpen(newVal);
    },
  }));
  const handleOk = () => {
    formProject
      .validateFields()
      .then(async values => {
        console.log('valuse', values, menusSwitch);
        const params = {
          name: values?.name,
          necessary: menusSwitch,
        };
        const data = await apiCreateShop(params);
        if (data.code === '0000') {
          formProject.resetFields(); // 表单清除历史
          setConfirmLoading(true);
          setTimeout(() => {
            setOpen(false);
            setConfirmLoading(false);
          }, 2000);
        }
      })
      .catch(info => {
        // queryShopList()
        console.log('保存异常', info);
      });
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  const onChange = () => {
    if (menusSwitch === 0) {
      setMenusSwitch(1);
      return false;
    }
    setMenusSwitch(0);
    return false;
  };
  useEffect(() => {
    console.log('open', open);
  }, [open]);
  return (
    <>
      {open && (
        <Modal
          title="添加分组"
          visible={open}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          initialValues={{
            menusSwitch: 0,
          }}
          onCancel={handleCancel}
        >
          <Form form={formProject}>
            <Form.Item label="Select">
              <Select>
                <Select.Option value="shopId">Demo</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="分组名称" name="name" rules={[{ required: true }]}>
              <Input />
            </Form.Item>
            <Form.Item label="下单必选分组" name="necessary" valuePropName={menusSwitch}>
              <Switch
                defaultChecked={menusSwitch}
                checkedChildren="开启"
                unCheckedChildren="关闭"
                onChange={onChange}
              />
              <div className={styles.textStyle}>
                选中后，顾客下单需至少选择1个 “下单必须分组” 商品
              </div>
              <div className={styles.textStyle}>每店仅可设置1个必点分组</div>
            </Form.Item>
          </Form>
        </Modal>
      )}
    </>
  );
};

export default forwardRef(AddMenusModal);
