/* eslint-disable prefer-const */
/* eslint-disable no-unused-vars */
import { getIn } from 'herculex/dist/utils/manipulate';

import {
  openNewVersion,
  debugTemplateUuid,
  debugNoCache,
} from '../../../../utils/constants';


import { loadPlugin } from './plugin';
import { getAccessMode, getStorage, setStorage, jumpPageLoginFailure } from '../../../../utils';
import { alert } from '../../../../utils/jsapi';
import { getMemberInfo } from './member';

import { getServiceDynamicList } from '../../../../utils/service';

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

async function handleEnterAdComponent({ commit, state }, { componentData, isCityChange }) {
  try {
    if (componentData && componentData.componentExtInfo) {
      const { showCount } = componentData.componentExtInfo;
      const adShowCount = +await getStorage('adShowCount') || 0;
      const isShowEnterAd = +showCount === -1 ? true : (adShowCount < +showCount);
      const { adShowed } = state.$global;
      commit({
        isShowEnterAd: !adShowed && isShowEnterAd && (isCityChange !== 'cityChange'),
        isLoading: false,
      });
    }
  } catch (error) {
    console.log(error);
  }
}

async function renderMain({ state, commit }, { setTitle }) {
  setTitle && my.setNavigationBar({
    title: state.pageName,
  });
  commit({
    isRenderMain: true,
    isLoading: false,
  });
}

// eslint-disable-next-line no-undef
const app = getApp();
// const hasPageCached = (pageUuid, pageList) => pageList.find(item => item.pageUuid === pageUuid);
const getActiveIndex = (pageUuid, tabBar) => tabBar.findIndex(item => item.pageUuid === pageUuid);

export default {
  async start({ dispatch, commit, dispatchGlobal, state }, payload) {
    const {
      pageUuid,
      pageCode,
      noCache,
      isPullRefresh = false,
    } = payload;
    commit({
      isLoading: true,
      errorType: null,
    });
    try {
      if (openNewVersion) {
        await dispatchGlobal('initialize1');
      } else {
        await dispatchGlobal('initialize');
      }
      const extParams = {};
      const { regionCode = '' } = state.$global;
      const _pageUuid = isPullRefresh ? state.pageUuid : pageUuid;
      if (debugNoCache) extParams.debugNoCache = debugNoCache;
      if (!_pageUuid) {
        if (debugTemplateUuid) {
          extParams.debugTemplateUuid = debugTemplateUuid;
        }
      }
      // 处理页面数据缓存
      const [err2, pageData = {}] = await dispatchGlobal('requestPageData', {
        pageUuid: _pageUuid,
        pageCode,
        regionCode,
        noCache,
        extParams,
      });
      if (err2) throw err2;
      await dispatch('resetStorage', {});
      await dispatch('handlePageData', { pageData, pageCode });
      const { tabbar } = state.$global.pageConfig[state.templateUUID] || { tabbar: [] };
      const activeIndex = getActiveIndex(pageData.pageUuid, tabbar);
      if (activeIndex !== -1) {
        commit({
          hasTabBar: true,
          activeIndex,
        });
      } else {
        commit({
          hasTabBar: false,
        });
      }
    } catch (e) {
      console.error('e', e);
      commit({
        isLoading: false,
        errorType: 'SYSTEM_ERROR',
        errorCode: e.error || e.code,
        errorMsg: e.msg,
      });
    }
  },

  // 对pageData的处理
  async handlePageData({ dispatch, state, commit }, payload) {
    const { pageData, pageCode } = payload;
    try {
      const {
        pageName,
        accessMode,
        pageUuid,
        compoundType,
        components,
        bottomTips,
        extInfoObj,
        templateUUID,
        accessDenyUrl,
        accessDenyBack,
        memberCardComponent,
        enablePullRefresh = true,
      } = pageData || {};
      /* 设置标题栏 */
      my.setNavigationBar({ title: pageName || '' });
      /* 页面是否开启下拉刷新 */
      my.setCanPullDown({ canPullDown: enablePullRefresh });
      const loginParams = {
        accessMode,
        pageUuid,
        pageCode,
        compoundType,
        memberCardComponent,
      };
      const {
        isNeedLogin,
        isLoginSuccess,
      } = await dispatch('handlePageInActiveLogin', loginParams);
      /*
      * 登录失败处理
      * */
      if (isNeedLogin && !isLoginSuccess) {
        alert('提示信息', '登录失败');
        /* 如果是tabBar跳转到第一个tabBar */
        if (getCurrentPages().length === 1 && accessDenyBack === 'back') {
          throw { message: '登录失败' };
          /* 下面逻辑会引起tabbar死循环，注释掉 */
          // const { tabbar = [] } = state.$global;
          // const { pageUuid: _pageUuid } = tabbar[0] || {};
          // if (_pageUuid) return this.dispatch('startInTabBar', { pageUuid: _pageUuid });
        }
        return jumpPageLoginFailure({ accessDenyBack, accessDenyUrl });
      }
      commit({
        pageUuid,
        pageName,
        bottomTips,
        accessDenyUrl,
        accessDenyBack,
        accessMode,
        templateUUID,
        memberCardComponent,
        componentList: components,
        activePageExtIfo: extInfoObj,
        bannerUrl: state.$global.bannerUrl,
        bannerColor: state.$global.bannerColor,
        templateName: state.$global.templateName,
      });
      await dispatch('handleComponentsEffects', {
        components, memberCardComponent,
      });
      commit({ isLoading: false });
    } catch (e) {
      commit({
        isLoading: false,
        errorType: 'SYSTEM_ERROR',
      });
    }
  },

  // tabBar页面根据pageUuid来处理componentData
  async startInTabBar({ dispatch, dispatchGlobal, state, commit }, payload) {
    const { pageUuid, pageCode } = payload;
    const { regionCode = '' } = state.$global;
    // 处理页面数据缓存
    const [err2, pageData = {}] = await dispatchGlobal('requestPageData', { pageUuid, pageCode, regionCode });
    if (err2) throw err2;
    // 同步memberCardComponent
    if (state.memberCardComponent) {
      const oldCardTemplateId = getIn(state, ['memberCardComponent', 'componentExtInfo', 'cardTemplateId']);
      const newCardTemplateId = getIn(pageData, ['memberCardComponent', 'componentExtInfo', 'cardTemplateId']);
      if (oldCardTemplateId === newCardTemplateId) {
        pageData.memberCardComponent = state.memberCardComponent;
      }
    }

    const { tabbar } = state.$global.pageConfig[state.templateUUID];
    const activeIndex = getActiveIndex(pageData.pageUuid, tabbar);
    if (activeIndex !== -1) {
      commit({
        hasTabBar: true,
        activeIndex,
      });
    } else {
      commit({
        hasTabBar: false,
      });
    }
    my.pageScrollTo({
      scrollTop: 0,
    });
    await dispatch('handlePageData', { pageData });
  },

  async handlePageInActiveLogin(store, payload) {
    const { dispatch } = store;
    const {
      pageUuid,
      accessMode,
      compoundType,
      serviceUuid = '',
      memberCardComponent,
    } = payload;
    const checkAccessPara = {
      pageUuid,
      serviceUuid,
      compoundType,
      isPageAccess: true,
      accessMode: getAccessMode(accessMode),
      /* 检查会员卡状态 */
      customerCheckInPage: async () => dispatch('customerCheck', { memberCardComponent }),
    };
    const {
      isNeedLogin,
      success: isLoginSuccess,
    } = await accessModeCheck.call(this, checkAccessPara);
    return { isNeedLogin, isLoginSuccess };
  },

  async handleComponentsEffects({ commit, state }, payload) {
    const { components, isCityChange, memberCardComponent } = payload;
    const pluginAction = []; // 插件
    const memberCardAction = []; // 会员卡
    const enterAdAction = [];
    const serviceAction = [];
    components.forEach((item, index) => {
      // 处理pugin组件
      if (item.componentType === 'pluginComponent' && item.componentData) {
        pluginAction.push(loadPlugin({
          index,
          componentData: item.componentData,
        }));
      }

      // 处理海报
      if (item.componentType === 'enterAdComponent') {
        commit({
          enterAdComponent: item.componentData || {},
        });
        enterAdAction.push(
          handleEnterAdComponent({ commit, state }, {
            componentData: item.componentData,
            isCityChange,
          }),
        );
      }

      // componentList中不包含memberInfo信息， 需要手动请求
      if (item.componentType === 'memberCardComponent' || item.componentType === 'memberCardUserCenter' || item.componentType === 'ownerGetCard' || item.componentType === 'ownerGetCardNew' || item.componentType === 'newMemberCardComponent' || item.componentType === 'advertiseComponent') {
        memberCardAction.push(getMemberInfo({}, {
          index,
          componentData: item.componentData,
          componentType: item.componentType,
        }));
        if (!memberCardComponent) {
          commit({
            memberCardComponent: item.componentData,
          });
        }
      }

      // 获取动态数据源
      if (item.componentData.whetherSetDynamicDatasource === 'Y') {
        serviceAction.push(getServiceDynamicList({
          index,
          componentUuid: item.componentData.componentUUID,
        }));
      }
    });

    // 处理海报
    if (isCityChange !== 'cityChange') {
      if (enterAdAction.length) {
        // isNeedShowHb = true;
        await Promise.all(enterAdAction);
      }
    }

    if (state.isShowEnterAd) {
      setTimeout(() => {
        renderMain({ state, commit }, {
          setTitle: true,
        });
      }, 3100);
    } else {
      renderMain({ state, commit }, {
        setTitle: false,
      });
    }

    if (memberCardAction.length) {
      await Promise.all(memberCardAction).then((memberCard) => {
        memberCard.forEach((el) => {
          commit('updateMemberCard', {
            item: el,
          });
          if (el.componentType === 'memberCardComponent') {
            commit('updateMemberCardComponent', el);
          } else if (el.componentType === 'memberCardUserCenter') {
            commit('updateMemberCardUserCenter', el);
          } else if (el.componentType === 'memberCardUserCenter') {
            commit('updateNewMemberCardComponent', el);
          }
        });
      });
    }
    if (pluginAction.length) {
      await Promise.all(pluginAction).then((pluginList) => {
        pluginList.forEach((el) => {
          commit('updatePlugin', {
            index: el.index,
            isReady: el.isReady,
          });
        });
      });
    }
    if (serviceAction.length) {
      await Promise.all(serviceAction).then((list) => {
        list.forEach((el) => {
          commit('updateComponentService', {
            item: el,
          });
        });
      });
    }
  },

  async resetStorage({ commit, state }, payload) {
    // 控制首页弹框组件
    let data = await getStorage('ADVERT_SHOW');
    if (!data || data.serviceUUID) return;
    Object.getOwnPropertyNames(data).forEach(item => {
      data[item].show = true;
    });
    await setStorage('ADVERT_SHOW', data);
  },
};
