import React, { useState, useEffect } from 'react';
import { Modal, Radio, Form, Space, message, Checkbox } from 'antd';
import styles from '../index.less';
import { apiShopUpdate } from '../service.js';

const EditRepastModal = props => {
  const [form] = Form.useForm();
  const { editVisible, repastType, id, enterpriseId, isStore, selectMealType } = props;
  const handleCancel = status => {
    form.resetFields();
    props.onCancel(status, 'edit');
  };
  useEffect(() => {
    if (selectMealType.length) {
      let mealTypeList = selectMealType.filter(item => item !== 4);
      mealTypeList = (mealTypeList.length && Number(mealTypeList.join(','))) || '';
      const store = selectMealType.includes(4) ? [4] : [];
      form.setFieldsValue({ mealTypeList, store });
    }
  }, [selectMealType]);
  const onOk = () => {
    form.validateFields().then(async values => {
      const store = values?.store || '';
      let mealTypeList = [];
      if (values?.mealTypeList) {
        mealTypeList = [values?.mealTypeList, ...store];
      } else {
        mealTypeList = [...store];
      }
      const params = {
        id,
        mealTypeList,
      };
      const res = await apiShopUpdate(params);
      if (res.businessCode === '0000') {
        message.success('修改成功');
        handleCancel(true);
      }
    });
  };

  return (
    <>
      <Modal
        title="餐饮类型"
        onOk={onOk}
        visible={editVisible}
        onCancel={() => handleCancel(false)}
      >
        <Form layout="vertical" form={form}>
          <Form.Item
            label="取餐点下商户餐品类型"
            rules={[{ required: true, message: '请选择商户餐品类型' }]}
            name="mealTypeList"
          >
            <Radio.Group>
              <Space direction="vertical">
                {(repastType.length &&
                  repastType.map(item => (
                    <Radio value={item.value} key={item.value}>
                      {item.label}
                    </Radio>
                  ))) ||
                  ''}
              </Space>
              <p className={styles.tip}>切换餐品类型后，请及时维护商品</p>
            </Radio.Group>
          </Form.Item>

          {isStore && (
            <Form.Item label="是否开启餐品类型" name="store">
              <Checkbox.Group>
                <Space direction="vertical">
                  <Checkbox value={4}>到店</Checkbox>
                </Space>
                <p className={styles.tip}>关闭【到店】餐类时，关联到店企业商品将一并删除</p>
              </Checkbox.Group>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  );
};

export default EditRepastModal;
