import order from '@/api/order.api';
import {
  handlerCouponActivityInfoList,
  handlerSelectActivityInfo
} from '@/views/orders/createOrderAdapter';
import { deepCopy } from '@/service/utils.service';
import localStorage from '@/service/localStorage.service';

const createOrderStore = {
  namespaced: true,
  state: {
    // 订单信息
    orderInfo: null,
    preTag: 0 // 预加载标识 0 未预加载 1 预加载中 2 预加载完成
  },
  mutations: {
    setOrderInfo(state, order) {
      state.orderInfo = order;
    },
    setPreTag(state, preTag) {
      state.preTag = preTag;
    }
  },
  actions: {
    // 订单信息接口预加载
    fetchOrderInfoApi({ commit, dispatch }, data = null) {
      let reqObj = {};
      if (data) {
        reqObj = data;
      } else {
        const orderData = localStorage.get('orderData');
        const addressList = localStorage.get('addressList');
        if (addressList && orderData.addrReceiverId !== addressList.addrReceiverId) {
          orderData.addrReceiverId = addressList.addrReceiverId || '';
        }
        reqObj = {
          ...orderData,
          cartInfoList: [
            {
              activityInfo: null,
              skus: orderData.selectedSkuList
            }
          ]
        };
      }
      commit('setPreTag', 1);
      return dispatch('fetchOrderInfo', reqObj);
    },
    // 获取订单信息 并对数据做适配处理
    async fetchOrderInfo({ commit, state }, reqObj) {
      const [data] = await order.confirmOrder(reqObj);
      // 异常流直接返回
      if (!data) {
        return;
      }
      if (data) {
        const {
          generalProp,
          addrReceiverInfo,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList,
          shipmentTypeList = []
          // generalProp
        } = data;
        const orderInfo = {
          addrReceiverInfo,
          couponActivityInfoList: handlerCouponActivityInfoList(data),
          calcFeeInfo,
          invalidSkuList,
          shopSkuList: [],
          // 将三个结果信息放到OrderInfo中
          selectActivityInfo: handlerSelectActivityInfo(data?.couponActivityInfoList || []),
          shipmentTypeList,
          generalProp
        };

        shopSkuList.forEach(item => {
          item && (orderInfo.shopSkuList = deepCopy([...orderInfo.shopSkuList, ...item.skuList]));
        });
        commit('setOrderInfo', orderInfo);
      } else {
        commit('setOrderInfo', null);
      }
      if (state.preTag === 1) {
        commit('setPreTag', 2);
      }
      return data;
    }
  },
  getters: {
    orderInfo: state => state.orderInfo,
    preTag: state => state.preTag
  }
};

export default createOrderStore;
