import Store from 'herculex';

export default new Store({
  connectGlobal: true,
  state: {
    cityTabs: [],
    currentCityIndex: 0,
    currentAreaIndex: 0,
  },
  actions: {
    async loadCityData({ commit, global }) {
      const { mktCode, regionList, regionCode } = global;
      if (mktCode) {
        let currentCityIndex = 0;
        let currentAreaIndex = 0;
        const matchItem = regionList.find((item, index) => {
          if (item.code === mktCode) {
            currentCityIndex = index;
            item.subRegions.find((item2, index2) => {
              if (item2.code === regionCode) {
                currentAreaIndex = index2;
                return true;
              }
              return false;
            });
            return true;
          }
          return false;
        });
        matchItem && commit({
          currentCityIndex,
          currentAreaIndex,
        });
      }
      return commit({ cityTabs: regionList });
    },
    updateStoreData({ commit }, payload) {
      return commit({
        currentCityIndex: payload.currentCityIndex,
      });
    },
    async updateAreaData({ commit, state }, payload) {
      const { currentCityIndex, cityTabs } = state;
      const { data } = payload;
      const app = getApp();
      app.globalData.regionCode = data.code;
      if (data.name === state.$global.cityName) {
        return commit('$global:updateState', {
          noCache: false,
        });
      }
      return commit('$global:updateState', {
        cityName: data.name,
        regionCode: data.code,
        mktCode: cityTabs[currentCityIndex].code,
        noCache: true,
        // cityCode: cityTabs[currentCityIndex].code,
        templateUUID: data.templateUUID,
      });
    },
  },
});
