/**
 * 业务逻辑处理
 */
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/index';
// 获取自提点列表
export const getPickSelf = async (setPickSelfList, setVisible) => {
  const res = await apiEnterprisePickSelf({});
  if (res && res.data && res.data.records) {
    const data = res.data.records;
    const json = {};
    data.forEach(item => {
      json[item.id] = item.pickselfName;
    });
    setPickSelfList(json);
    setVisible(true);
  }
};

// 风险提示
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 };
};
/**
 * 接口获取数据转换为表单数据 消费限额 mealLimit
 * 接口来源数据： [{mealPeriodType: '1', limit: [{mealType: '1', limit: 100}，{mealType: '2', limit: 200}]}]
 * 转换后表单结构：mealLimit: { limit1: {1: 100, 2: 200}, limit2: {1: 100, 2: 200}}
 */
const transformMealLimit = mealLimit => {
  const mealLimitMap = {};
  mealLimit.forEach(item => {
    const { mealPeriodType, limit } = item;

    mealLimitMap[`limit${mealPeriodType}`] = limit.reduce(
      (acc, t) => ({
        ...acc,
        [t.mealType]: t.limit,
      }),
      {},
    );
  });
  return mealLimitMap;
  // return mealLimit;
};

/**
 * 3. 数据模型转换-接口获取数据转换为表单数据
 */
export const transformToFormData = 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);
  const mealLimitMap = transformMealLimit(mealLimit);

  formData.mealTimePeriod = mealTimePeriodArr;
  formData.mealLimit = mealLimitMap;
  formData.mealTimePeriodMap = mealTimePeriodMap;
  console.log('formData :>> ', formData);
  return formData;
};

/*
 * 5. 表单数据转换-表单数据转换为接口数据
 */
export const transformToApiParams = async (res, selectedMealTypes, meals) => {
  console.log('res :>> ', res);
  const params = {
    hideImage: 0, // 隐藏图片：默认0 不隐藏 必传
    hidePrice: 0, // 隐藏价格：默认0 不隐藏 必传
    ...res,
  };
  if (params.pickSelfIds) {
    params.pickselfIds = 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 && meals[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;
  /**
   * 处理限额数据
   * 表单来源数据 mealLimit: { limit1: {1: 100, 2: 200}, limit2: {1: 100, 2: 200}}
   *         mealLimit: { limit餐品类型: {餐段类型: 限额}}
   * 转换后数据结构：[{mealPeriodType: '1', limit: [{mealType: '1', limit: 100}]}]
   * mealPeriodType 餐段类型：（1早餐，2午餐，4晚餐）
   * mealType       餐品类型：（1外卖 2 自助餐 4到店）
   */
  console.log('res.mealLimit :>> ', res.mealLimit);
  console.log('selectedMealTypes :>> ', selectedMealTypes);
  const limits = [];
  res.mealLimit &&
    Object.keys(res.mealLimit).forEach(item => {
      const mealPeriodType = item.replace('limit', '');
      if (meals[mealPeriodType]) {
        const json = {
          mealPeriodType,
          limit: [],
        };
        Object.keys(res.mealLimit[item]).forEach(t => {
          if (selectedMealTypes.includes(t)) {
            json.limit.push({
              mealType: t,
              limit: res.mealLimit[item][t],
            });
          }
        });
        limits.push(json);
      }
    });
  params.mealLimit = limits;
  console.log(params, '.....');
  return params;
};
