import request from '../../utils/request';
import { getTitleBarHeight, getLoaction, getServerTime, storageAPI, getAppId } from '../../utils/jsapi';
import { getSettintsUrl, getRegionListUrl, scopesType, authLoginType, getTabBarDetailUrl, pageDataKey } from '../../utils/constants';
import { checkUserInfo, getPageInfo } from '../../utils/service';

async function getRegionList(data) {
  const [err, res] = await request({
    url: getRegionListUrl,
    data,
    noNeedTicket: true,
  });
  return [err, res];
}

function findParentCode(defauleRegionCode, regionList) {
  try {
    if (!defauleRegionCode || !regionList || !Array.isArray(regionList)) return '';
    const matchItem = regionList.find((item) => {
      if (item.code === defauleRegionCode) {
        return true;
      } else {
        const isMatchCode = item.subRegions.some(el => el.code === defauleRegionCode);
        return isMatchCode;
      }
    });
    // console.log('寻找regionList里面的父级code===', matchItem);
    return matchItem ? matchItem.code : '';
  } catch (error) {
    return '';
  }
}

export async function getLabs(type = 1) {
  const [err, res] = await getLoaction({
    type,
  });
  if (err) return [err, null];
  const { cityAdcode = '', accuracy = '', longitude = '', latitude = '' } = res || {};
  // eslint-disable-next-line no-undef
  const app = getApp();
  app.globalData.regionData = {
    accuracy,
    longitude,
    latitude,
    cityAdcode,
  };
  return [undefined, res];
}

async function getTime({ commit }) {
  try {
    const [err, res] = await getServerTime();
    const hours = err ? new Date().getHours() : new Date(res.time).getHours();
    let timeTxt = '';
    if (hours >= 5 && hours <= 11) {
      timeTxt = '早上好！';
    } else if (hours >= 12 && hours <= 18) {
      timeTxt = '下午好！';
    } else {
      timeTxt = '晚上好！';
    }
    commit('updateTimetxt', {
      timeTxt,
    });
  } catch (error) {
    //
  }
}

export async function getPageDataFromCache(pageUuid, pageCode) {
  const [err, { data: pageData }] = await storageAPI.getStorage({ key: pageDataKey });
  if (err) return;
  if (Array.isArray(pageData)) {
    if (pageUuid) {
      return Array.isArray(pageData) && pageData.find(item => item.pageUuid === pageUuid);
    }
    if (pageCode) {
      return Array.isArray(pageData) && pageData.find(item => item.pageCode === pageCode);
    }
  }
}


export default {
  async getSettings({ commit }) {
    // eslint-disable-next-line no-undef
    const app = getApp();
    const [err, res] = await request({ url: getSettintsUrl, noNeedTicket: true });
    if (err) throw err;
    if (res) {
      res.forEach((item) => {
        if (item.key === 'userLoginType') {
          commit({
            loginType: authLoginType[item.value],
            scopes: scopesType[item.value],
          });
        } else if (item.key === 'showRegion') {
          app.globalData.showRegion = item.value;
          commit({
            showRegion: item.value,
          });
        } else if (item.key === 'appPublicKey') {
          app.globalData.appPublicKey = item.value;
          commit({
            appPublicKey: item.value,
          });
        } else {
          app.globalData[item.key] = item.value;
        }
      });
    }
  },

  async getRegions({ commit }) {
    const [err] = await getLabs();
    // eslint-disable-next-line no-undef
    const app = getApp();
    if (err) console.log(err);
    if (err && app.globalData.showRegion === 'N') return;
    const [regionErr, regionRes] = await getRegionList({
      cityAdcode: app.globalData.regionData.cityAdcode,
      accuracy: app.globalData.regionData.accuracy,
      longitude: app.globalData.regionData.longitude,
      latitude: app.globalData.regionData.latitude,
    });
    if (regionErr) return [regionErr, null];
    // if (!regionRes) return [new Error(), null];
    const { defauleRegionCode, defauleRegionName, regions } = regionRes || {};
    app.globalData.regionData.regionCode = defauleRegionCode;
    const mktCode = findParentCode(defauleRegionCode, regions);
    app.globalData.regionData.regionList = regions;
    app.globalData.regionData.mktCode = mktCode;
    app.globalData.regionData.cityName = defauleRegionName;
    // cityCode 和 mktCode放在globalState中
    commit({
      regionCode: defauleRegionCode,
      cityCode: app.globalData.regionData.cityAdcode,
      cityName: defauleRegionName,
      regionList: regions,
      mktCode,
    });
    return [null, regionRes];
  },

  async getTabBarDetail(_, payload) {
    const { regionCode } = payload;
    const [err, res] = await request({
      url: getTabBarDetailUrl,
      data: { regionCode },
    });
    if (err) throw err;
    const { tabbar = [], pages = [] } = res;
    // 对tabbar数据进行处理
    const transformedTabBar = Array.isArray(tabbar) ? tabbar.map(item => ({
      ...item,
      url: item.link,
      urlType: item.linkType,
      appId: item.appid,
    })) : [];
    // eslint-disable-next-line no-undef
    const app = getApp();
    app.globalData.tabBar = transformedTabBar;
    app.globalData.pageCacheList = pages || [];
  },

  // 获取页面信息
  async requestPageData({ commit, state }, payload) {
    // 先尝试从缓存中取数据
    const { pageUuid, pageCode, regionCode, noCache, extParams } = payload;
    if ((pageUuid || pageCode) && !noCache) {
      const pageData = await getPageDataFromCache(pageUuid, pageCode);
      if (pageData) return [null, pageData];
    }
    // 没有缓存则需要重新请求
    const [err, res] = await getPageInfo({ pageUuid, pageCode, regionCode, ...extParams });
    if (err || !res) return [err, null];
    // 将数据缓存
    // eslint-disable-next-line max-len
    const {
      pages,
      tabbar,
      currentTabIndex,
      templateUUID,
      templateName,
      bannerUrl,
      bannerColor,
      extInfoObj,
    } = res;
    const newPages = pages.map(item => {
      return {
        ...item,
        templateUUID,
      };
    });
    commit({
      templateUUID,
      templateName,
      bannerUrl,
      bannerColor,
    });
    let [, { data: pageData }] = await storageAPI.getStorage({ key: pageDataKey });
    if (!pageData) pageData = [];
    if (Array.isArray(pageData)) {
      /*
      * 用新的数据替换缓存
      * */
      newPages.forEach((newPage) => {
        const pageIndex = pageData.findIndex((oldPage) => (
          oldPage.pageUuid === newPage.pageUuid
        ));
        if (pageIndex > -1) {
          pageData[pageIndex] = newPage;
        } else {
          pageData.push(newPage);
        }
      });

      const newPageData = [...pageData];
      await storageAPI.setStorage({ key: pageDataKey, data: newPageData });
    }
    const { pageConfig } = state;
    if (currentTabIndex === -1) {
      if (!pageConfig[templateUUID]) {
        commit({
          pageConfig: {
            ...pageConfig,
            [templateUUID]: {
              bannerUrl,
              bannerColor,
              templateName,
              templateUUID,
              tabbar: [],
              extInfoObj,
            },
          },
        });
      }
      return [null, newPages[0]];
    }
    const transformedTabBar = Array.isArray(tabbar) ? tabbar.map(item => ({
      ...item,
      url: item.link,
      urlType: item.linkType,
      appId: item.appid,
    })) : [];
    commit({ pageConfig: {
      ...pageConfig,
      [templateUUID]: {
        bannerUrl,
        bannerColor,
        templateName,
        templateUUID,
        tabbar: transformedTabBar,
        /*
        * 增加extInfoObj字段，里面包含页面的一些全局属性
        * */
        extInfoObj,
      },
    },
    tabbar: transformedTabBar,
    });
    const uuid = transformedTabBar[currentTabIndex].pageUuid;
    const result = newPages.find(item => item.pageUuid === uuid);
    return [err, result];
  },

  async initialize1({ commit, dispatch }) {
    const app = getApp();
    const { isInitialized } = app.globalData;
    if (isInitialized) return;
    await storageAPI.removeStorage({ key: pageDataKey });
    const [, { data: logout }] = await storageAPI.getStorage({ key: 'logout' });
    const appId = getAppId();
    app.globalData.appId = appId;
    // 处理获取失败提示
    if (!appId) {
      const err = { error: 'APPID_GET_FAILED', msg: '获取appId失败' };
      throw err;
    }
    await checkUserInfo().then(([err, res]) => {
      if (err) throw err;
      if (!logout && res.userInfo) {
        commit({ userInfo: { ...res.userInfo, isLogin: true } });
      }
    });
    await getTitleBarHeight().then(titleBarHeight => {
      commit({
        titleBarHeight,
      });
    });
    getTime({ commit });
    await dispatch('getSettings');

    if (app.globalData.showRegion === 'Y') {
      await dispatch('getRegions');
    }
    // await dispatch('getTabBarDetail', { regionCode: state.regionCode });
    app.globalData.isInitialized = true;
  },

  async initialize({ commit, dispatch }) {
    // eslint-disable-next-line no-undef
    const app = getApp();
    const { isInitialized } = app.globalData;
    if (isInitialized) return;
    await storageAPI.removeStorage({ key: pageDataKey });
    const [, { data: logout }] = await storageAPI.getStorage({ key: 'logout' });
    const appId = getAppId();
    app.globalData.appId = appId;
    // 处理获取失败提示
    if (!appId) {
      const err = { error: 'APPID_GET_FAILED', msg: '获取appId失败' };
      throw err;
    }
    const [err, res] = await checkUserInfo();
    if (err) throw err;
    if (!logout && res.userInfo) {
      commit({ userInfo: { ...res.userInfo, isLogin: true } });
    }
    const titleBarHeight = await getTitleBarHeight();
    await getTime({ commit });
    commit({
      titleBarHeight,
    });
    await dispatch('getSettings');

    if (app.globalData.showRegion === 'Y') {
      await dispatch('getRegions');
    }
    // await dispatch('getTabBarDetail', { regionCode: state.regionCode });
    app.globalData.isInitialized = true;
  },
};
