import {
  getAuthUser,
  getSilentAuthCode,
  navigateToMiniProgram,
  navigateToAlipayPage,
} from '../../utils/jsapi';
import { messageSubscribeNotify } from '../../utils/service';
import { authCodeKey, dynamicPageName } from '../../utils/constants';
import {
  checkTicketExpire,
  serviceReport,
  getPagesQuery,
  getAccessMode,
  setStorage,
  paramsParse,
  prefixPagePath,
  promisify,
} from '../../utils';

import accessModeCheck from '../../utils/accessModeCheck';

async function getAuthCodeParams({ accessMode, loginType }) {
  const { auth_user, realName } = accessMode;
  const isAuthUser = loginType === 'user' && (auth_user || realName);
  const func = isAuthUser ? getAuthUser : getSilentAuthCode;
  const result = await func();
  return result;
}

export function promisifyCallback(func) {
  return function wrapPromisifyCallback(args) {
    return new Promise((resolve) => {
      func({
        ...args,
        callback(res) {
          resolve(res);
        },
      });
    });
  };
}

const jumpToAlipay = async (url) => {
  if (typeof url === 'string' && url.indexOf('appCode') === 0) {
    // url = 'appCode:antForest?autoShowProps=1&a=1'
    const link = url.split(':')[1];
    const appCode = link.split('?')[0];
    const appParams = paramsParse(link);
    navigateToAlipayPage({
      appCode,
      appParams,
    });
  } else if (typeof url === 'string' && url.indexOf('miniApi') === 0) {
    // url = miniApi:openMerchantVoucherList?partnerId=2088501624560335
    const link = url.split(':')[1];
    const type = link.split('?')[0];
    const appParams = paramsParse(link);
    switch (type) {
      case 'openMerchantVoucherList':
        my.openMerchantVoucherList({ partnerId: appParams.partnerId });
        break;
      case 'openVoucherList':
        my.openVoucherList();
        break;
      case 'openTicketList':
        my.openTicketList();
        break;
      case 'openMerchantTicketList':
        my.openMerchantTicketList({ partnerId: appParams.partnerId });
        break;
      case 'openCardList':
        my.openCardList();
        break;
      default:
        break;
    }
  } else {
    navigateToAlipayPage({
      path: url,
    });
  }
};

const getActiveIndex = (pageUuid, tabBar) => tabBar.findIndex(item => item.pageUuid === pageUuid);

// 处理页面传参
function handleUrlParams(urlQuery) {
  let pageQueryStr = '';
  const pageQueryArr = urlQuery && urlQuery.split('&');
  if (pageQueryArr && pageQueryArr.length) {
    pageQueryArr.forEach(item => {
      if (item.indexOf('{') > -1 && item.indexOf('}') > -1) {
        // 动态参数
        const _arr = item.split('=');
        const name = _arr[1].slice(1, _arr[1].length - 1);
        pageQueryStr += `&${_arr[0]}=${getPagesQuery(name)}`;
      } else {
        pageQueryStr += `&${item}`;
      }
    });
  }
  return pageQueryStr;
}

export default {
  // eslint-disable-next-line complexity
  async  handleJumpService({ state, commit }, payload) {
    const {
      uuid,
      from,
      appId,
      urlType,
      urlQuery,
      currentScope,
      serviceUUID = '',
      serviceCode = '',
      templateUUID = '',
      compoundType = '',
      customerCheckInPage,
      pageUuid: _pageUuid,
      accessMode: _accessMode,
      subscribeMessageTemplates,
    } = payload || {};

    let { url = '' } = payload;
    const { loginType } = state;
    /* 这里兼容老的模式 */
    const accessMode = getAccessMode(_accessMode);
    const checkPara = {
      accessMode,
      serviceUUID,
      compoundType,
      currentScope,
      pageUuid: _pageUuid,
      customerCheckInPage,
    };
    /*
    * 检查进入状态
    * */
    const {
      certifyId,
      cardTemplateId,
      success: checkSuccess,
    } = await accessModeCheck.call(this, checkPara);

    if (!checkSuccess) return;

    // eslint-disable-next-line no-undef
    const app = getApp();
    /* 上报改为并行 */
    await serviceReport({
      serviceCode,
      formId: state.formId,
      serviceUUID: serviceUUID || uuid,
      regionCode: app.globalData.regionCode,
    });

    // 如果配置了消息模板，调用插件获取用户同意
    if (subscribeMessageTemplates && typeof subscribeMessageTemplates === 'string' && my.loadPlugin) {
      const [, res] = await promisify(my.loadPlugin)({ plugin: '2021001155639035@*' });
      if (res) {
        commit({
          isMessagePluginLoad: true,
        });
        // eslint-disable-next-line
        const msgPlugin = requirePlugin('dynamic-plugin://2021001155639035') || {};
        const { requestSubscribeMessage } = msgPlugin;
        if (typeof requestSubscribeMessage === 'function') {
          const promisifyRequestSubscribeMessage = promisifyCallback(requestSubscribeMessage);
          const templatesObj = JSON.parse(subscribeMessageTemplates) || {};
          const longTermMessage = templatesObj.longTerm;
          const oneTimeMessage = templatesObj.oneTime;
          if (longTermMessage && longTermMessage.length) {
            const longIds = longTermMessage.map(msg => {
              return msg.split(';')[1] || '';
            });
            const longRes = await promisifyRequestSubscribeMessage({ entityIds: longIds });
            messageSubscribeNotify({ userResult: longRes, templateIds: longTermMessage });
          }
          if (oneTimeMessage && oneTimeMessage.length) {
            const oneIds = oneTimeMessage.map(msg => {
              return msg.split(';')[1] || '';
            });
            const oneRes = await promisifyRequestSubscribeMessage({ entityIds: oneIds });
            messageSubscribeNotify({ userResult: oneRes, templateIds: oneTimeMessage });
          }
        }
      }
    }

    // 处理页面传参
    let pageQueryStr = handleUrlParams(urlQuery);

    if (urlType === 'app_inside') {
      if (url.indexOf(':') > -1) {
        url = url.split(':')[1];
      } else if (url.indexOf('?') > -1) {
        return my.navigateTo({ url: `${url}&serviceCode=${serviceCode}${pageQueryStr}` });
      } else {
        return my.navigateTo({ url: `${url}?serviceCode=${serviceCode}${pageQueryStr}` });
      }
      const pageUuid = url;
      if (from === 'webview') {
        return my.redirectTo({
          url: `${prefixPagePath}/${dynamicPageName}/index?pageUuid=${pageUuid}&serviceCode=${serviceCode}${pageQueryStr}`,
        });
      }
      if (from === 'tabBar') {
        // 如果pageUuid不在tabBar内，则直接navigator
        const { tabbar } = state.pageConfig[templateUUID];
        if (getActiveIndex(pageUuid, tabbar) === -1) {
          return my.navigateTo({
            url: `${prefixPagePath}/${dynamicPageName}/index?pageUuid=${pageUuid}&serviceCode=${serviceCode}${pageQueryStr}`,
          });
        }
        // 将componentData置为pageUuid的，更新activeIndex。
        return payload.handleTabBarChange(pageUuid);
      }
      if (url === 'logout') {
        commit({
          userInfo: {},
        });
        app.globalData.isUserLogin = true;
        app.globalData.userInfo = {};
        await setStorage('logout', true);
        return;
      }
      return my.navigateTo({
        url: `${prefixPagePath}/${dynamicPageName}/index?pageUuid=${pageUuid}&serviceCode=${serviceCode}${pageQueryStr}`,
      });
    }
    const [err] = await checkTicketExpire();
    if (err) return;
    const { ticket = '' } = app.globalData.ticketData;
    const mineAppId = app.globalData.appId;
    switch (urlType) {
      case 'h5': {
        if (url.indexOf('?') > -1) {
          // 带参数
          const _index = url.indexOf('?');
          pageQueryStr = handleUrlParams(url.slice(_index + 1));
          url = url.slice(0, _index);
        }
        const [error, { authCode }] = await getAuthCodeParams({ accessMode, loginType });
        if (error) return;
        let _url;
        // 兼容hash路由
        let str = `ticket=${ticket}&${authCodeKey}=${authCode}&appId=${mineAppId}&certifyId=${certifyId}&serviceCode=${serviceCode}`;
        str += pageQueryStr;
        if (url.indexOf('#') > -1) {
          _url = url.replace(/(?=#)/, `?${str}`);
        } else {
          _url = `${url}${url.indexOf('?') > -1 ? '&' : '?'}${str}`;
        }
        if (accessMode.customer && cardTemplateId) {
          _url += `&cardTemplateId=${cardTemplateId}`;
        }
        console.log('_url', _url);
        if (from === 'webview') {
          return {
            url: _url,
          };
        }
        my.navigateTo({
          url: `${prefixPagePath}/h5/index?url=${encodeURIComponent(_url)}&serviceUUID=${serviceUUID}&serviceCode=${serviceCode}${pageQueryStr}`,
        });
        break;
      }
      case 'app_outer': {
        const [error, { authCode }] = await getAuthCodeParams({
          accessMode,
          loginType,
        });
        if (error) return;
        const extraData = {
          ...paramsParse(url),
          [authCodeKey]: authCode,
          appId: mineAppId,
        };
        if (accessMode.customer && cardTemplateId) {
          extraData.cardTemplateId = cardTemplateId;
        }
        const _path = (paramsParse(url) || {}).page || '';
        // if (from === 'webview') {
        //   return {
        //     appId,
        //     path: _path,
        //     extraData,
        //   };
        // }
        navigateToMiniProgram({
          appId,
          path: _path,
          extraData,
        });
        break;
      }
      case 'alipay': {
        await jumpToAlipay(url);
        break;
      }
      case 'text': {
        if (url) {
          my.showToast({ content: url });
        }
        break;
      }
      default:
        break;
    }
  },
};
