import Vue from 'vue';
import { detailInfo, getDetailPic, actAndCpn } from '@/api/goods.api';
import goodApi from '@/api/goods.api';
import { pickupCoupon, pickupCouponBySkuNo } from '@/api/coupon.api';
import address from '@/api/address.api';
import { subscribeAdd } from '@/api/browse.api';
import { initChildrenSku, isSelectSpec } from '../utils/sku';

// const SET_GOOD_DETAIL = 'SET_GOOD_DETAIL';
// // const SET_GOOD_DETAIL_BASE = 'SET_GOOD_DETAIL_BASE';
// const SET_GOOD_DETAIL_QUERY = 'SET_GOOD_DETAIL_QUERY';
// const SET_GOOD_STATE = 'SET_GOOD_STATE';
// const SET_DETAIL_IMG_LIST = 'SET_DETAIL_IMG_LIST';
// const SET_POPUP_STATE = 'SET_POPUP_STATE';
// const SET_POPUP_INFO = 'SET_POPUP_INFO';
// const SET_ACT_AND_CPN = 'SET_ACT_AND_CPN';
// const SET_ADDRESS_LIST = 'SET_ADDRESS_LIST';
// const SET_ADDRESS_INFO = 'SET_ADDRESS_INFO';
// const SET_SKU_NUM = 'SET_SKU_NUM';
// const SET_SIMILARITY_LIST = 'SET_SIMILARITY_LIST';

let specSelectedBack = [];
const btnTxts = {
  3: '立即购买',
  31: '领券购买',
  4: '查看其他商品',
  11: '区域受限'
};

export const namespaced = true;

export const state = {
  query: {
    skuNo: '',
    receiverId: '',
    count: 1,
    hidePrice: false
  },
  skuNum: 0,
  detail: {
    goodsStatus: 0 // 3,上架(立即购买)，31领券购买，4下架(无库存)，11区域受限，前端自定义: 41失效, 0加载中
  },
  detailImgList: [],
  activityAndCoupon: {},
  addressList: [],
  popupControl: {
    type: '',
    title: ''
  },
  showPopup: false,
  similarityList: []
};

export const getters = {
  swiperImgList: state => {
    if (state.detail.imageList) {
      return state.detail.imageList;
    }
    if (state.query.goodsOrgImage) {
      return [state.query.goodsOrgImage];
    }
    return [];
  },
  priceInfo: state => {
    const { salePrice, saleCount } = state.detail || {};
    return { salePrice, saleCount };
  },
  activityInfo: state => {
    const { activityType, activityShowInfo } = state.detail || {};
    return { activityType, ...activityShowInfo };
  },
  goodsStatus: state => state.detail.goodsStatus || 0,
  btnTxt: (_, getters) => btnTxts[getters.goodsStatus || 0],
  activityDescs: state => state.detail.activityShowInfo?.activityDescs || [],
  discountBarInfo: state => state.detail.discountBarInfo || {},
  subscribeInfo: state => state.detail.subscribeInfo || {},
  maxMemberInfo: state => state.detail.maxMemberInfo || {},
  title: state => {
    const { skuName, sellPoint, skuIcon } = state.detail || {};
    return { skuName, sellPoint, skuIcon };
  },
  commentInfo: state => state.detail.commentInfo || {},
  detailImgList: state => state.detailImgList || [],
  activityAndCoupon: state => state.activityAndCoupon || {},
  addressList: state => state.addressList || [],
  customerConf: state => state.detail.customerConf || {},
  skuAttrInfos: state => state.detail.skuAttrInfos || [],
  specChildList: state => state.detail.specChildList || [],
  specSelected: state => {
    const specSelected = [];
    (state.detail.skuAttrInfos || []).forEach(item => {
      item.attsValues.forEach(i => {
        if (i.isSelected) specSelected.push(i);
      });
    });
    return specSelected;
  },
  selectedSku: (state, getters) => {
    let spec = getters.specSelected.map(item => item.attsValue);
    if (spec.length < specSelectedBack.length) {
      spec = specSelectedBack;
    } else {
      specSelectedBack = spec;
    }
    return {
      imageUrl: (state.detail.imageList || [])[0] || '',
      salePrice: state.detail.salePrice,
      skuId: state.detail.skuNo,
      skuNum: state.skuNum,
      skuName: state.detail.skuName,
      skuSource: state.detail.skuSource,
      spec: spec.join('；')
    };
  },
  isSelectSpec: (state, getters) => {
    return isSelectSpec(state.detail.skuAttrInfos || [], getters.specSelected);
  },
  receiverInfo: state => {
    const { receiverInfo } = state.detail;
    return !receiverInfo
      ? { txt: '', id: '' }
      : {
          txt: `${receiverInfo.provinceName} ${receiverInfo.cityName} ${receiverInfo.countyName}`,
          id: receiverInfo.addrReceiverId
        };
  },
  limitCount: state => state.detail.activityLimitCount || state.detail.commonLimitCount || 0,
  hidePrice: state => state.query.hidePrice
};

export const actions = {
  async getGoodDetail({ commit, dispatch }, query) {
    // if ('' + query.skuNo === '' + state.query.skuNo) {
    //   return;
    // } else {
    !query.noReset && dispatch('reset');
    // }
    commit('SET_GOOD_DETAIL_QUERY', query);
    commit('SET_SKU_NUM', query.count || 1);
    dispatch('getSimilarityList', query.skuNo);
    delete query.goodsOrgImage;
    const [res, err] = await detailInfo(query);
    if (err) {
      commit('SET_GOOD_STATE', 41);
      return;
    }
    res.specChildList = initChildrenSku(res.skuAttrInfos || []);
    commit('SET_GOOD_DETAIL', res);
    dispatch('getGoodDetailImg', res.detailUrl);
  },
  async getGoodDetailImg({ commit }, detailUrl) {
    try {
      const detailImages = await getDetailPic(detailUrl);
      const imgReg = /<img.*?(?:>|\/>)/gi;
      // eslint-disable-next-line no-useless-escape
      const srcReg = /src=[\'"]?([^\'"]*)[\'"]?/i;
      const arr = (detailImages || '').match(imgReg);
      const srcArr = [];
      for (let i = 0; i < arr.length; i++) {
        let src = arr[i].match(srcReg)[1].replace('http://', 'https://');
        srcArr.push(src);
      }
      commit('SET_DETAIL_IMG_LIST', srcArr);
    } catch (error) {
      console.log(error);
    }
  },
  async getActivityAndCoupon({ state, commit }) {
    try {
      const { skuNo } = state.detail;
      const [res, err] = await actAndCpn({ skuNo });
      if (!err) {
        commit('SET_ACT_AND_CPN', res);
      }
    } catch (error) {
      console.log(error);
    }
  },
  async pickupCoupon({ state, commit }, index) {
    let couponPickupList = [];
    const coupons = state.activityAndCoupon?.coupons || [];
    if (!index && index !== 0) {
      couponPickupList = coupons.map(item => {
        const { id, couponCategory } = item;
        return {
          couponId: id,
          couponType: couponCategory,
          pickupNum: 1
        };
      });
    } else {
      const { id, couponCategory } = coupons[index];
      couponPickupList = [
        {
          couponId: id,
          couponType: couponCategory,
          pickupNum: 1
        }
      ];
    }
    if (!couponPickupList.length) {
      Vue.prototype.$toast('未选择优惠券');
      return;
    }
    const [res] = await pickupCoupon({
      couponPickupList,
      allowedPartFailed: true,
      systemSendCoupon: true
    });
    if (res) {
      state.activityAndCoupon.coupons = coupons.map(item => {
        item.pickupAble = true;
        return item;
      });
      commit('SET_ACT_AND_CPN', state.activityAndCoupon);
      // dispatch('getActivityAndCoupon');
      Vue.prototype.$toast('领取成功！');
    }
  },
  async pickupCouponBySkuNo({ state }) {
    await pickupCouponBySkuNo({
      skuNo: state.detail.skuNo,
      skuNum: state.skuNum
    });
  },
  async getAddr({ commit, state }) {
    if (state.addressList.length) return;
    const [addressInfo] = await address.getAddressList();
    if (addressInfo) {
      commit('SET_ADDRESS_LIST', addressInfo.addrReceiverList || []);
    }
  },
  async subscribeAdd({ state }) {
    const [res, err] = await subscribeAdd({
      type: 2,
      operateType: 1,
      skuNo: state.detail.skuNo,
      sourcePage: 3000
    });
    if (!err) {
      Vue.prototype.$toast(res?.result || '订阅成功');
    }
  },
  async getSimilarityList({ commit }, goodsId) {
    const [res, err] = await goodApi.goodsLike({
      goodsId
    });
    if (!err) {
      commit('SET_SIMILARITY_LIST', res.goodsList || []);
    }
  },
  setAddressInfo({ commit }, info) {
    commit('SET_ADDRESS_INFO', info);
    commit('SET_POPUP_STATE', false);
  },
  setPopupState({ commit, dispatch, rootGetters }, show) {
    if (typeof show === 'object') {
      if (show.type === 'discountBar') {
        dispatch('getActivityAndCoupon');
      }
      if (show.type === 'addr' && rootGetters.hasLogin) {
        dispatch('getAddr');
      }
      commit('SET_POPUP_INFO', show);
    } else {
      commit('SET_POPUP_INFO', {
        type: '',
        title: ''
      });
    }
    commit('SET_POPUP_STATE', !!show);
  },
  setSkuNum({ commit, rootGetters }, skuNum) {
    if (state.skuNum !== 0 && skuNum === rootGetters['goodDetail/limitCount']) {
      Vue.prototype.$toast(`您当前购买的商品限购${rootGetters['goodDetail/limitCount']}件`);
      return;
    }
    commit('SET_SKU_NUM', skuNum);
  },
  reset({ commit }) {
    specSelectedBack = [];
    commit('SET_GOOD_DETAIL', {
      goodsStatus: 0
    });
    commit('SET_GOOD_DETAIL_QUERY', {
      skuNo: '',
      receiverId: '',
      count: 1,
      hidePrice: false
    });
    commit('SET_GOOD_STATE', 0);
    commit('SET_DETAIL_IMG_LIST', []);
    commit('SET_POPUP_STATE', false);
    commit('SET_POPUP_INFO', {
      type: '',
      title: ''
    });
    commit('SET_ACT_AND_CPN', {});
    commit('SET_ADDRESS_LIST', []);
    commit('SET_ADDRESS_INFO', {});
    commit('SET_SKU_NUM', 0);
    commit('SET_SIMILARITY_LIST', []);
  }
};

export const mutations = {
  SET_GOOD_DETAIL(state, detail) {
    Vue.set(state, 'detail', detail);
  },
  SET_GOOD_DETAIL_QUERY(state, query) {
    query = { ...state.query, ...query };
    Vue.set(state, 'query', query);
  },
  SET_GOOD_STATE(state, goodsStatus) {
    Vue.set(state.detail, 'goodsStatus', goodsStatus);
  },
  SET_DETAIL_IMG_LIST(state, srcArr) {
    Vue.set(state, 'detailImgList', srcArr);
  },
  SET_POPUP_STATE(state, showPopup) {
    Vue.set(state, 'showPopup', showPopup);
  },
  SET_POPUP_INFO(state, popupControl) {
    Vue.set(state, 'popupControl', popupControl);
  },
  SET_ACT_AND_CPN(state, info) {
    Vue.set(state, 'activityAndCoupon', info);
  },
  SET_ADDRESS_LIST(state, addressList) {
    Vue.set(state, 'addressList', addressList);
  },
  SET_ADDRESS_INFO(state, info) {
    Vue.set(state.detail, 'receiverInfo', info);
  },
  SET_SKU_NUM(state, skuNum) {
    Vue.set(state, 'skuNum', skuNum);
  },
  SET_SIMILARITY_LIST(state, list) {
    if (list.length % 2 !== 0) {
      list.length = list.length - 1;
    }
    Vue.set(state, 'similarityList', list);
  }
};
