import React, { useState, useEffect } from 'react';
import { Checkbox, Space, message, Modal, notification } from 'antd';
import { weekOptions } from '../staticData/goods';
import { apiMealInfoUpdate } from '../service';

const SaleDateModal = props => {
  const [value, setValue] = useState([]);

  // 关闭弹窗
  const handleCancel = () => {
    props.handleClose(false);
  };

  const onChangeWeek = e => {
    setValue(e);
  };

  // 提交
  const handleConfirm = async () => {
    if (!value || value.length < 1) {
      message.error('请选择可售日期');
      return;
    }
    if (props.id) {
      const params = {
        id: props.id,
        saleDateList: value,
      };
      await apiMealInfoUpdate(params);
      notification.success({ message: '保存成功' });
    }
    handleCancel();
    props.handleRefresh(value);
  };

  useEffect(() => {
    if (props.visible) {
      let v = [];
      const dateList = props.item?.saleDateList || props.item?.saleDate;
      if (dateList && dateList.length) {
        v = dateList.map(item => {
          if (typeof item === 'object') {
            return `${item.code}`;
          }
          return `${item}`;
        });
      }
      setValue(v);
    }
  }, [props.visible]);

  return (
    <Modal
      title={props.title || '设置可售日期'}
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="200px"
      okText="保存"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Checkbox.Group onChange={onChangeWeek} value={value}>
        <Space direction="vertical">
          {Object.keys(weekOptions).map(key => (
            <Checkbox key={key} value={key}>
              {weekOptions[key]}
            </Checkbox>
          ))}
        </Space>
      </Checkbox.Group>
    </Modal>
  );
};
export default SaleDateModal;
