/* eslint-disable complexity */
/* eslint-disable max-len */
import { getIn } from 'herculex/dist/utils/manipulate';
import { toast } from '../../../../utils';
import { promisify } from '../../../../utils/jsapi';
import request from '../../../../utils/request';
import { openCardUrl, getMemberInfoUrl, getOpenCardUrl, universeUrl, openNewCardUrl, getCardLevelUrl } from '../../../../utils/constants';

async function getMemberInfoService(payload) {
  try {
    // eslint-disable-next-line no-undef
    const app = getApp();
    const { ticket } = app.globalData.ticketData;
    const data = { ...payload, ticket };
    const [error, response] = await request({ data, url: getMemberInfoUrl });
    if (error) throw error;
    return [undefined, response];
  } catch (error) {
    return [error, undefined];
  }
}

// 会员卡相关方法
export async function addCard({ dispatch }, e) {
  const applyUrl = getIn(e, ['applyUrl'], '');
  const cardTemplateId = getIn(e, ['cardTemplateId'], '');
  const regionCode = getIn(e, ['regionCode'], '');
  const card = getIn(e, ['card'], '');
  const type = getIn(e, ['type'], '');

  const errMsg = '开卡失败';
  const [, res] = await promisify(my.addCardAuth)({ url: applyUrl });
  const { code, success, result } = res || {};
  if (success && result) {
    const openCardRes = await dispatch('openCard', {
      result,
      cardTemplateId,
      regionCode,
      card,
      type,
    });
    return openCardRes;
  } else if (code === 'USER_BACK') {
    return { code: 'USER_BACK' };
  } else {
    toast(errMsg);
    return 'addCardFail';
  }
}

export async function getCardLevel({ commit }) {
  const [err, res] = await request({
    data: {},
    method: 'get',
    url: universeUrl + getCardLevelUrl,
  });
  if (err) {
    commit('$global:updateState', {
      memberLevel: 'NONE',
    });
  } else {
    const { level } = res;
    commit('$global:updateState', {
      memberLevel: level,
    });
  }
}

export async function getOpeMemberCardUrl() {
  const [err, res] = await request({
    data: {},
    method: 'get',
    url: getOpenCardUrl,
  });
  return [err, res];
}

export async function openCard({ commit, dispatch, state }, { result, cardTemplateId, regionCode, card, type }) {
  try {
    const { auth_code, template_id, request_id, out_string } = result;
    my.showLoading();
    const [err, res] = await request({
      headers: {
        regionCode,
      },
      data: {
        auth_code,
        template_id,
        request_id,
        out_string,
      },
      url: card === 'newMemberCardComponent' ? openNewCardUrl : openCardUrl,
    });
    if (err) throw err;
    // 将卡会员信息更新到会员卡组件中, 找到对应的id
    const { componentList = [] } = state;
    let index = '';
    for (let i = 0; i < componentList.length; i++) {
      const { componentData: { componentType, componentExtInfo = {}, componentConfigure = {} } } = componentList[i];
      const desId = componentExtInfo.cardTemplateId || componentConfigure.cardTemplateId;
      if ((componentType === 'memberCardComponent' || componentType === 'memberCardUserCenter' || componentType === 'ownerGetCard' || componentType === 'ownerGetCardNew' || componentType === 'advertiseComponent' || componentType === 'newMemberCardComponent') && desId === cardTemplateId) {
        index = i;
        break;
      }
    }
    commit('updateMemberCard', {
      item: {
        ...res,
        index,
      },
    });
    // eslint-disable-next-line no-empty
    if (card === 'newMemberCardComponent') {
      commit('updateNewMemberCardComponent', res);
    } else if (card === 'memberCardUserCenter') {
      commit('updateMemberCardUserCenter', res);
    } else {
      commit('updateMemberCardComponent', res);
    }
    // 如果没有登录 成功开卡之后检查登录态
    if (state.userInfo && !state.userInfo.isLogin) {
      await dispatch('$global:checkUserLogin');
    }
    my.hideLoading();
    // 商场单独开卡
    if (type === 'mall') {
      commit('$global:updateState', {
        memberRes: res,
      });
    }
    return 'addCardSuccess';
  } catch (error) {
    my.hideLoading();
    toast(error.msg);
    return 'addCardFail';
  }
}

export async function getMemberInfo(_, { componentType, componentData, index }) {
  try {
    const { componentExtInfo = {}, componentConfigure = {} } = componentData;
    const cardTemplateId = componentExtInfo.cardTemplateId || componentConfigure.cardTemplateId;
    const [err, res] = await getMemberInfoService({
      cardTemplateId,
    });
    if (err) throw err;

    return {
      ...res,
      index,
      cardTemplateId,
      componentType,
      // flag: res.flag,
      // point: res.point,
      // level: res.level,
      // cardNo: res.cardNo,
      // passId: res.passId,
    };
  } catch (error) {
    return {
      err: true,
      index,
      flag: false,
    };
  }
}

export async function customerCheck({ state, dispatch }, payload) {
  let { memberCardComponent } = payload || {};
  memberCardComponent = memberCardComponent || state.memberCardComponent;
  if (!memberCardComponent) return 'addCardFail'; // 没有配置会员卡
  const checkResult = await dispatch('getCardTemplateId', memberCardComponent);
  return checkResult;
}

export async function getCardTemplateId({ dispatch }, data = {}) {
  const applyUrl = getIn(data, ['componentExtInfo', 'applyUrl'], '');
  const cardTemplateId = getIn(data, ['componentExtInfo', 'cardTemplateId'], '');
  const flag = getIn(data, ['componentExtInfo', 'memberInfo', 'flag'], '');
  if (flag || !applyUrl) return 'addCardSuccess';
  const res = await dispatch('addCard', { applyUrl, cardTemplateId });
  return res; // addCardFail || addCardSuccess
}
