import React, { useEffect, useState } from 'react';
import { Form, Modal, Input, Switch, Alert, message } from 'antd';
import { apiCreateStorage, apiEditStorage, apiStorageInfo } from '../../service';
import { stringOrObjectTrim } from '@/utils/utils';

const GroupInfo = options => {
  const [form] = Form.useForm();
  const [isChecked, setIsChecked] = useState(false);

  // 关闭分组信息弹窗
  const handleCancel = () => {
    options.handleClose(false);
  };

  // 添加/保存分组
  const handleConfirm = async () => {
    const { name, necessary } = await form.validateFields();
    const api = options.id ? apiEditStorage : apiCreateStorage;
    const res = await api({
      name: stringOrObjectTrim(name),
      necessary: necessary ? 1 : 0,
      shopId: options.shopId,
      id: options.id,
    });
    if (res.code === '0000' && res.businessCode === '0000') {
      message.success('保存成功！');
      handleCancel();
      options.search();
    }
  };

  const getInfo = async id => {
    const res = await apiStorageInfo({
      shopId: options.shopId,
      id,
    });
    if (res && res.data && res.data.id) {
      const { name, necessary } = res.data;
      setIsChecked(+necessary === 1);
      form.setFieldsValue({
        name,
        necessary: +necessary === 1,
      });
    }
  };

  useEffect(() => {
    if (options.id && options.isModalOpen) {
      getInfo(options.id);
    }
  }, [options.id, options.isModalOpen]);

  const extra = <Alert message="选中后，顾客下单需至少选择1个“下单必选分组”" type="error" />;

  return (
    <Modal
      title="分组信息"
      visible={options.isModalOpen}
      destroyOnClose
      maskClosable={false}
      width="600px"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Form name="basic" form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
        <Form.Item
          label="分组名称"
          name="name"
          rules={[{ required: true, message: '请输入分组名称!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="下单必选分组" name="necessary" extra={extra}>
          <Switch
            checkedChildren="开启"
            checked={isChecked}
            unCheckedChildren="关闭"
            onChange={setIsChecked}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default GroupInfo;
