/**
 * 业务逻辑处理
 */
import React from 'react';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import moment from 'moment';
import { apiEnterprisePickSelf } from './service';
import { mealSections } from './staticData';

// 获取自提点列表
export const getPickSelf = async () => {
  const res = await apiEnterprisePickSelf({});
  if (res && res.data && res.data.records) {
    const data = res.data.records;
    return data.map(item => ({
      label: item.pickselfName,
      value: item.id,
    }));
  }
  return [];
};

// 风险提示
const { confirm } = Modal;
export const checkConfirm = () => {
  const mt = '';
  return new Promise((resolve, reject) => {
    confirm({
      title: '风险提示',
      icon: <ExclamationCircleOutlined />,
      content: `确定关闭${mt}餐品类型？此餐品类型下关联的商户及商品将一并删除，不可逆请谨慎操作！`,
      onOk() {
        resolve(1);
      },
      onCancel() {
        reject(new Error());
      },
    });
  });
};

/**
 * 接口获取数据转换为表单数据 转换餐段 mealTimePeriod
 * 接口来源数据： [{mealPeriodType: '1', beginTime: '08:00', endTime: '09:00'}]
 * 转换后表单结构：[{mealPeriodType: '1', time: [moment('08:00'), moment('09:00')]}]
 */
const transformMealTimePeriod = mealTimePeriod => {
  const mealTimePeriodMap = {};
  const mealTimePeriodArr = Object.keys(mealSections).map(() => ({}));

  mealTimePeriod.forEach(item => {
    const { mealPeriodType, beginTime, endTime } = item;
    // 数据模型转换-餐段配置,转为 {餐段:餐段名称}
    // 把mealTimePeriod按mealPeriodType转为map
    const mealPeriodName = mealSections[mealPeriodType];
    mealTimePeriodMap[mealPeriodType] = mealPeriodName;

    // 数据模型转换-餐段和时间配置, [{餐段, time}, {}, {}]
    const index = Object.keys(mealSections).indexOf(`${mealPeriodType}`);
    if (index > -1) {
      mealTimePeriodArr[index] = {
        mealPeriodType: `${mealPeriodType}`,
        time: [
          moment(`${moment().format('YYYY-MM-DD')} ${beginTime}`),
          moment(`${moment().format('YYYY-MM-DD')} ${endTime}`),
        ],
      };
    }
  });
  return { mealTimePeriodMap, mealTimePeriodArr };
};

/**
 * 3. 数据模型转换-接口获取数据转换为表单数据
 */
export const transformVOToFormData = data => {
  const {
    hideImage,
    hidePrice,
    id,
    name,
    mealLimit,
    mealTimePeriod = [],
    mealType: type,
    weekPreview,
    endOrderTime,
  } = data;

  const formData = {
    id,
    name,
    weekPreview,
    mealType: type?.map(item => `${item}`) ?? [],
    hideInfo: [],
    endOrderTime,
  };

  if (+hidePrice) {
    formData.hideInfo.push('hidePrice');
  }
  if (+hideImage) {
    formData.hideInfo.push('hideImage');
  }

  const { mealTimePeriodMap, mealTimePeriodArr } = transformMealTimePeriod(mealTimePeriod);

  formData.mealTimePeriod = mealTimePeriodArr;
  formData.mealLimit = mealLimit;
  formData.mealTimePeriodMap = mealTimePeriodMap;
  return formData;
};

/*
 * 5. 表单数据转换-表单数据转换为接口数据
 */
export const transformFormDataToDTO = (res, selectedMealTypes, selectedMealSections) => {
  const params = {
    hideImage: 0, // 隐藏图片：默认0 不隐藏 必传
    hidePrice: 0, // 隐藏价格：默认0 不隐藏 必传
    ...res,
  };
  if (params.pickSelfIds) {
    params.pickselfIds = params.pickSelfIds;
    delete params.pickSelfIds;
  }
  /**
   * 处理餐段 mealTimePeriod
   * 表单来源数据：  [{mealPeriodType: '1', time: [moment('08:00'), moment('09:00')]}]
   * 转换后数据结构：[{mealPeriodType: '1', beginTime: '08:00', endTime: '09:00'}]
   */
  const arr = [];
  res.mealTimePeriod &&
    res.mealTimePeriod.forEach(item => {
      if (item && selectedMealSections[item.mealPeriodType]) {
        const obj = { ...item };
        obj.beginTime = moment(obj.time[0]).format('HH:mm');
        obj.endTime = moment(obj.time[1]).format('HH:mm');
        delete obj.time;
        arr.push(obj);
      }
    });
  params.mealTimePeriod = arr;
  /**
   * hidePrice 隐藏价格：0不隐藏；1隐藏
   * hideImage 隐藏图片：0不隐藏；1隐藏
   */
  if (res.hideInfo?.length) {
    params.hidePrice = res.hideInfo.includes('hidePrice') ? 1 : 0;
    params.hideImage = res.hideInfo.includes('hideImage') ? 1 : 0;
  }
  delete params.hideInfo;
  return params;
};
