import Cache from '@/utils/cache';
import { getConfig } from "@/api/config.js";






const state = {
  eyeType: Cache.get('eyeType') || true, // 小眼睛
  request: Cache.get('request') || true, // 网络请求
  config: JSON.parse(Cache.get('config')||'{}'),
  updateFlag: true
};

const mutations = {
  SET_EYE_TYPE(state){
    state.eyeType=!state.eyeType;
    Cache.set('eyeType', state.eyeType);
  },
  SET_REQUEST(state, data=true){
    state.request = data;
    Cache.set('request', state.request);
  },
  SET_CONFIG(state, data){
    state.config = {...data};
    Cache.set('config', JSON.stringify(state.config));
  },
  SET_UPDATEFLAG(state, data){
    state.updateFlag = data;
  },
};

const actions = {
  async initConfig({ state, commit }, data = false) {
    let res = await getConfig();
    commit('SET_CONFIG', res.data);
    // console.log(compareVersions(res.data.version, '1.0.0')==1&&compareVersions(res.data.version, Cache.get('wgt_version'))==1);
    if(uni.getStorageSync('uniMP')||!state.updateFlag) return ;//是小程序环境时不进行更新
    let os = uni.getSystemInfoSync();
    // uni.showModal({
    //   title: `当前:${os.appVersion},WGT:${Cache.get('wgt_version')},返回:${res.data.version}`
    // })
    // #ifdef APP-PLUS
    if(data) uni.showLoading({
      title: '检查更新中'
    })
    const wgt_v = uni.getStorageSync('wgt_version')||'1.0.0';
    commit('SET_UPDATEFLAG', false);
    // 版本更新
    if(compareVersions(res.data.version, os.appWgtVersion||wgt_v)==1&&compareVersions(res.data.version, wgt_v)==1){
      try{
        let info = res.data.version_info||{};
        let version = {
          title: info.title||'发现新版本',
          content: info.content||'修复了部分BUG',
          versionName: info.version||'1.0.1',
          downUrl: info.dow_url||'',
          force: info.force==1?true:false, // 是否强制更新
          quiet: info.quiet==1?true:false // 是否静默更新
        }
        Updater.update(version);;
      }catch(e){
        console.log(e);
      }
      if(data) uni.hideLoading();
    }else if(data){
      uni.hideLoading();
      uni.showToast({
        title: '已经是最新版本了',
        icon: 'none'
      })
    }
    // #endif
  }
};


export default {
  state,
  mutations,
  actions
};
