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($t('edit.successful'));
        handleCancel(true);
      }
    });
  };

  return (
    <>
      <Modal
        title={$t('food.type')}
        onOk={onOk}
        visible={editVisible}
        onCancel={() => handleCancel(false)}
      >
        <Form layout="vertical" form={form}>
          <Form.Item
            label={$t('merchant.meal.types.at.pickup')}
            rules={[{ required: true, message: $t('select.meal.type') }]}
            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}>{$t('update.products.after.switching.meal.type')}</p>
            </Radio.Group>
          </Form.Item>

          {isStore && (
            <Form.Item label={$t('enable.meal.types')} name="store">
              <Checkbox.Group>
                <Space direction="vertical">
                  <Checkbox value={4}>{$t('instore')}</Checkbox>
                </Space>
                <p className={styles.tip}>{$t('toggling.off.instore.will.delete.associated.items')}</p>
              </Checkbox.Group>
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  );
};

export default EditRepastModal;
