import Vue from 'vue';
import Vuex from 'vuex';
import { Encrypt,Decrypt } from '@/utils/crypto';
import { crmQueryMemberInfo } from '@/utils/api-crm-member';
import uni from '@/utils/uniHooks';
import { kipAllCities,kipGetUserDetail,getVIPIntegral } from '@/utils/api-kip';
import cachedViews from './cachedViews';
import order from './order/index';
import invoice from './invoice';
import { lbsDictionary } from '@/common/js/BaseDictionary';
import { getGroupIdAndMallIdByLsbId } from '@/utils';
// import { parkingLots } from '@/utils/api-crm-ms';

Vue.use(Vuex);

function getValue( state,key ) {
  let value = state[key];
  if ( !value ) {
    value = uni.getStorageSync(key);
  }
  // console.log(1414141414141414, { key, value });
  return value;
}

const store = new Vuex.Store({
  state: {
    // groupId: '8a84819f7c6e260e017c72669bbe01c2',
    // kipUserId: '8a888aea82c9ac970182ecfa259a0ddf',
    // mallId: '8a8486a37f48f7bd017f4e5bddd10000',
    // openid: 'oudWQ5SCDElfn-IQH6eBR5JesOz4',
    // appId: 'wx92c3e55fbef6b2af',
    lbsId: '',
    groupId: '',
    kipUserId: '',
    mallId: '',
    openid: '',
    appId: '',
    member: {},
    userInfo: {},
    mobile: '',
    custTypeId: 0, // 0 默认版本，1 上海静安 2 上海浦东 3 KIP:默认版本 4: 新的baseUI
    paramsScene: {},
    parkFee: {},
    marketList: [],
    projectId: '',
    isLogin: '1', // 1: 未登录，2：已登录，3：拒绝登录
    accessToken: '', // 用户的token
    tempParkingOrder: {},
    tempParkingMoney: '',
    // 停车缴费
    bonusCopy: 0,
    source: '', // 访问方：微信小程序：（CRM|KIP|JINGAN|PUDONG|ALIPAY）
    brandInfo: {},
    curMarket: {},
    isInit: false, // 当内嵌在小程序中的H5页面，没有接收到小程序数据时，默认显示骨架屏幕
    // 无牌车
    unlicensedInfo: '',
    // 防止用户在无牌车流程中卡死
    endlessLoop: ''
  },
  mutations: {
    SET_GROUP_ID( state,payload ) {
      uni.setStorageSync('groupId',payload);
      state.groupId = payload;
    },
    SET_KIP_USER_ID( state,payload ) {
      uni.setStorageSync('kipUserId',payload);
      state.kipUserId = payload;
    },
    SET_MALL_ID( state,payload ) {
      uni.setStorageSync('mallId',payload);
      state.mallId = payload;
    },
    SET_OPENID( state,payload ) {
      uni.setStorageSync('openid',payload);
      state.openid = payload;
    },
    SET_WX_ACCESS_TOKEN( state,payload ) {
      uni.setStorageSync('wxAccessToken',payload);
      state.access_token = payload;
    },
    SET_WX_REFRESH_TOKEN( state,payload ) {
      uni.setStorageSync('wxRefreshToken',payload);
      state.refresh_token = payload;
    },
    SET_MEMBER( state,payload ) {
      uni.setStorageSync('member',payload);
      state.member = payload;
    },
    SET_USER_INFO( state,payload ) {
      uni.setStorageSync('userInfo',payload);
      state.userInfo = payload;
    },
    SET_MOBILE( state,payload ) {
      uni.setStorageSync('mobile',payload);
      state.mobile = payload;
    },
    SET_PARAMS_SCENE( state,payload ) {
      uni.setStorageSync('paramsScene',payload);
      state.paramsScene = payload;
    },
    SET_PARK_FEE( state,payload ) {
      state.parkFee = payload;
    },
    SET_MARKET_LIST( state,payload ) {
      state.marketList = payload;
    },
    SET_PROJECT_ID( state,payload ) {
      uni.setStorageSync('projectId',payload);
      state.projectId = payload;
    },
    SET_IS_LOGIN( state,payload ) {
      state.isLogin = payload;
      // uni.setStorageSync('passLogin', payload);
    },
    SET_ACCESS_TOKEN( state,payload ) {
      state.accessToken = payload;
      // uni.setStorageSync('accessToken', payload);
      uni.setStorageSync('kipAccessToken',payload);
    },
    setTempParkingOrder( state,payload ) {
      state.tempParkingOrder = payload;
    },
    setTempParkingMoney( state,payload ) {
      state.tempParkingMoney = payload;
    },
    // setbonusCopy
    SET_BONUS_COPY( state,payload ) {
      state.bonusCopy = payload;
    },
    SET_CUST_TYPE_ID( state,payload ) {
      uni.setStorageSync('custTypeId',payload);
      state.custTypeId = payload;
    },
    SET_SOURCE( state,payload ) {
      uni.setStorageSync('source',payload);
      state.source = payload;
    },
    SET_APPID( state,payload ) {
      uni.setStorageSync('appId',payload);
      state.appId = payload;
    },
    SET_BRAND_INFO( state,payload ) {
      uni.setStorageSync('brandInfo',payload);
      state.brandInfo = payload;
    },
    SET_CUR_MARKET( state,payload ) {
      uni.setStorageSync('curMarket',payload);
      state.curMarket = payload;
    },
    SET_IS_INIT( state,payload ) {
      // TODO: 与小程序通信时打开
      state.isInit = payload;
    },
    SET_LBS_ID( state,payload ) {
      uni.setStorageSync('lbsId',payload);
      uni.setStorageSync('mallId',payload);
      state.lbsId = payload;
    },
    SET_BRAND_ID( state,payload ) {
      state.brandId = payload;
    },
    // 无牌车
    SET_UNLICENSED_INFO( state,payload ) {
      console.log(163, payload);
      state.unlicensedInfo = payload;
    },
    SET_ENDLESS_LOOP( state,payload ) {
      state.endlessLoop = payload;
    },
  },
  actions: {
    async baseInit( {commit,dispatch},{options,callback} ) {
      try {
        // console.log(
        //   'Encrypt',
        //   Encrypt(
        //     // '8a8480487c96d58f017c9b7bab7d0020_8a84811682cf02420182ed5fb8c4000d_8a8485067ce4da2d017ce555e9b20000_ozdsB4yx3I7ez2Ba3DgEmeSR-CFY_15267617473'
        //     '8aaa81947c6e1ca0017c7201e82d0001#8aaa80cc7d4fc7b3017d55c4d6120000#8aaa80b47c784020017c78b00d060022#ozdsB4yx3I7ez2Ba3DgEmeSR-CFY#13601829387'
        //   )
        // );
        console.log(128,options);
        // if (!pageId) return;
        let {
          groupId = '',
          mallId = '',
          kipUserId = '',
          custTypeId = '',
          brandId = '',

          openid = '',
          mobile = '',
          lbsId = '',
          lbsName = '',
          isLogin = false,
          accessToken = '',
          source = '',
          appId = 'wx92c3e55fbef6b2af',
          // 无牌车逻辑
          unlicensedInfo,
          // CRM
          // brandInfo = {},
          // curMarket = {}
        } = options;
        console.log({lbsId});

        /* {
         buildingId: mallId,
         projectId: groupId,
         openId: openid,
         }
         * */
        // const resp = await parkingLots();
        // console.log(171171, resp);
        commit('SET_SOURCE',source);
        commit('SET_APPID',appId);

        // let { groupId, mallId } =
        if (!/CRM|PUDONG|JINGAN/.test(source)) {
          const groupIdAndMallId = getGroupIdAndMallIdByLsbId(lbsId);
          groupId = groupIdAndMallId.groupId;
          mallId = groupIdAndMallId.mallId;
          // console.log('lbsId', groupIdAndMallId)
          commit('SET_LBS_ID',mallId);
        } else {
          commit('SET_LBS_ID',lbsId);
        }
        
        commit('SET_CUST_TYPE_ID',custTypeId);
        // 如果为 false，则表示当前用户是从小程序端未登录进入的
        if ( !isLogin ) {
          // 如果用户未登录，清理原来的数据, 小程序入口不需要处理
        }
        const href = window.location.href;
        commit('SET_GROUP_ID',groupId);
        commit('SET_MALL_ID',mallId);
        commit('SET_BRAND_ID',brandId);
        // console.log('用户扫码进入的', unlicensedInfo, unlicensedInfo?.type);
        // 如果是无牌车
        if ( unlicensedInfo?.type ) {
          // console.log('用户扫码进入的', unlicensedInfo);
          commit('SET_UNLICENSED_INFO',unlicensedInfo)
          // commit('SET_ENDLESS_LOOP', true)
        }
        /*if (/dev-|8080|qa-/.test(href)) {
         commit('SET_GROUP_ID', groupId);
         commit('SET_MALL_ID', mallId);
         } else {
         commit('SET_GROUP_ID', '8a8884e77cc9e70a017cca1c77e80004');
         groupId = '8a8884e77cc9e70a017cca1c77e80004';
         mallId = '8a888aed7d0295e5017d029ff1f40000';
         commit('SET_MALL_ID', '8a888aed7d0295e5017d029ff1f40000');
         }*/
        commit('SET_OPENID',openid || uni.getStorageSync('openid'));
        if ( isLogin ) {
          commit('SET_ACCESS_TOKEN',accessToken);
          commit('SET_KIP_USER_ID',kipUserId);
          commit('SET_MOBILE',mobile);
          dispatch('getUserDetail');
          const memberRes = await getVIPIntegral()
          // const memberRes = await crmQueryMemberInfo({
          //   groupId,
          //   kipUserId,
          //   mallId,
          // });
          // 请求 projectId
          window.toWXSendMsg({
            type: 'getProjectId',
            options: {},
          });
          const marketListRes = await kipAllCities();
          if ( memberRes) {
            dispatch('getUserDetail');
            commit('SET_MEMBER',memberRes);
          }
          // console.log(929292, marketListRes);
        }
        callback && callback();
      } catch ( e ) {
        console.log(e);
        callback && callback();
      }
    },
    async getUserDetail( {commit} ) {
      const res = await kipGetUserDetail();
      commit('SET_USER_INFO',res.data);
      // console.log('user_info', res);
    },
    clearUnlicensed( {state,commit} ) {
      commit('SET_UNLICENSED_INFO','');
      commit('SET_ENDLESS_LOOP','');
    }
  },
  modules: {
    cachedViews,
    order,
    invoice
  },
});

export default store;
