import {
  certIdentity,
  userIdentity,
  getCurrentStore,
  checkCertifyTimeout,
  getUserInfoByStore,
} from './index';

import { alert } from './jsapi';

const certifiedState = {
  errorType: 'NOCERTIFIED',
  errorMsg: '还未完成实名认证',
  errorBrief: '请先完成实名认证',
  operations: [{
    btnText: '去认证',
    handleName: 'jumpToAlipayPage',
    url: 'https://custweb.alipay.com/certify/personal/LIFE_PAY',
  }],
};

const isObj = (value) => (
  Object.prototype.toString.call(value) === '[object Object]'
);

/* 静默授权 */
const accessAuthUser = (dispatchGlobal, scopesList) => {
  const scopes = 'auth_user';
  return dispatchGlobal('doLogin', { scopes, scopesList });
};

// eslint-disable-next-line complexity
const accessModeCheck = async function (payload) {
  const {
    pageUuid,
    accessMode,
    serviceUUID,
    serviceUuid,
    currentScope,
    compoundType,
    isPageAccess = false,
    customerCheckInPage,
  } = payload;
  const {
    none,
    cert,
    login,
    identity,
    realName,
    customer,
    compoundAuth,
    phoneNumber,
  } = accessMode || {};

  let certifyId = '';
  let cardTemplateId = '';
  const currentStore = getCurrentStore();
  const { commit, dispatch, dispatchGlobal } = currentStore;
  const isNeedLogin = Object.values(accessMode).some((val) => val);
  /* 静默授权 */
  if (none) {
    /* 这里静默忽略 */
    // const success = await accessAuthUser(dispatchGlobal);
    // if (!success) return { success, isNeedLogin };
  }
  /*
  * 这里是复合授权
  * */
  if (compoundAuth) {
    const success = await accessAuthUser(dispatchGlobal, compoundType);
    if (!success) return { success, isNeedLogin };
  }
  /* 是获取用户基础信息 */
  if (login) {
    if (!getUserInfoByStore().isLogin) {
      const scopes = 'userInfo';
      /* 这里表示如果不是通过按钮触发的登录，需要打开按钮弹窗 */
      if (currentScope !== scopes) {
        /* 打开弹窗 */
        await dispatch.call(currentStore, 'launchLogin');
      }
      const success = await dispatchGlobal('doLogin', { scopes });
      /* 登录失败 */
      if (!success) return { success, isNeedLogin };
    }
  }
  /* 手机号码 */
  if (phoneNumber) {
    if (!getUserInfoByStore().phone) {
      const scopes = 'phoneNumber';
      /* 这里表示如果不是通过按钮触发的手机号登录，需要打开按钮弹窗 */
      if (currentScope !== scopes) {
        await dispatch.call(currentStore, 'launchPhone');
      }
      const success = await dispatchGlobal('doLogin', { scopes });
      /* 登录失败 */
      if (!success) return { success, isNeedLogin };
    }
  }
  /* 实名 */
  if (realName) {
    /* 当前用户没有实名，就进行登录 */
    const {
      isCertified,
      idCardNo,
    } = getUserInfoByStore();

    if (!isCertified && !idCardNo) {
      const success = await accessAuthUser(dispatchGlobal);
      if (!success) return { success, isNeedLogin };
    }

    /* 当前用户没有实名，弹窗提示实名 */
    if (isCertified === 'F') {
      /* 如果是页面触发 */
      if (isPageAccess) {
        commit(certifiedState);
      } else {
        alert('请先前往支付宝--我的，完成实名认证，再继续享受服务');
      }
      return { success: false, isNeedLogin };
    }
  }
  /* 人脸 */
  if (identity) {
    const checkPara = {};
    if (pageUuid) checkPara.pageUuid = pageUuid;
    if (serviceUuid) checkPara.serviceUuid = serviceUuid;
    if (serviceUUID) checkPara.serviceUUID = serviceUUID;
    const [err, res] = await checkCertifyTimeout(checkPara);
    if (err) return { success: false, isNeedLogin };
    if (res.valid) {
      certifyId = res.certifyId;
    } else {
      const [err2, res2] = await userIdentity(checkPara);
      if (err2) return { success: false, isNeedLogin };
      certifyId = res2.result.certifyId;
    }
  }
  /* 会员卡 */
  if (customer && customerCheckInPage) {
    /* 检查是否已经添加了会员卡 */
    cardTemplateId = await customerCheckInPage();
    /* 如果用户取消领卡返回失败 */
    let isBack = false;
    if (isObj(cardTemplateId)) {
      const { code } = cardTemplateId;
      isBack = code === 'USER_BACK';
    }
    /* 领卡失败，获取用户返回，都认为是登录失败 */
    if (cardTemplateId === 'addCardFail' || isBack) {
      return { success: false, isNeedLogin };
    }
  }
  /* 检查证件 */
  if (cert) {
    const para = { serviceUuid: serviceUUID };
    if (pageUuid) para.pageUuid = pageUuid;
    const [err, res] = await certIdentity(para);
    if (err) return { success: false };
    const { result, notAuthTypeValues = [] } = res;
    if (!result) {
      const card = notAuthTypeValues ? notAuthTypeValues.join('、') : '';
      alert('证件未激活', `请先激活${card}`);
      return { success: false, isNeedLogin };
    }
  }
  return { success: true, certifyId, cardTemplateId, isNeedLogin };
};

export default accessModeCheck;
