import request from 'src/utils/request'
import sysRequest from 'src/utils/sysRequest'
import { subSysToken } from "src/api/system/registerConfig";
import { Notify, Dialog } from 'vant';
const state = {
  cloudServerAddress: localStorage.getItem('cloudServerAddress'),
  authCode: localStorage.getItem('authCode'),
  accessToken: localStorage.getItem('accessToken'),
  runMode: localStorage.getItem('runMode'),
  deviceSN: localStorage.getItem('deviceSN'),
  unitModel: localStorage.getItem('unitModel'),
  ipAddress: localStorage.getItem('ipAddress'),
  sysCode: localStorage.getItem('sysCode'),
  // 盒条件产线信息
  // qrCodeProductLine: JSON.parse(localStorage.getItem('qrCodeProductLine')),
  // qrOrder: localStorage.getItem('qrOrder'),
  isRefreshToken: false,
}

const mutations = {
  SET_CLOUD_SERVER_ADDRESS: (state, _cloudServerAddress) => {
    state.cloudServerAddress = _cloudServerAddress;
    localStorage.setItem('cloudServerAddress', _cloudServerAddress);
    // request工具类
    request.defaults.baseURL = _cloudServerAddress + '/sub-api';
    sysRequest.defaults.baseURL = _cloudServerAddress + '/sub-api';
  },
  SET_RUN_MODE: (state, _runMode) => {
    state.runMode = _runMode
    localStorage.setItem('runMode', state.runMode);
  },
  SET_AUTH_CODE: (state, _authCode) => {
    state.authCode = _authCode
    localStorage.setItem('authCode', state.authCode);
  },

  SET_IP_ADDRESS: (state, _ipAddress) => {
    state.ipAddress = _ipAddress
    localStorage.setItem('ipAddress', state.ipAddress);
  },
  SET_SYSTEM_SYSCODE: (state, sysCode) => {
    localStorage.setItem('sysCode', sysCode);
  },
  SET_ACCESS_TOKEN: (state, _accessToken) => {
    state.accessToken = _accessToken
    localStorage.setItem('accessToken', state.accessToken);
  },
  SET_IS_REFRESH_TOKEN: (state, _isRefreshToken) => {
    state.isRefreshToken = _isRefreshToken
    localStorage.setItem('isRefreshToken', state.isRefreshToken);
  },
  // 保存条零/盒条件产线信息
  SET_PRODUCT_LINE: (state, productLine) => {
    state.qrCodeProductLine = productLine
    localStorage.setItem('qrCodeProductLine', JSON.stringify(state.qrCodeProductLine));
  },
  SET_DEVICE_SN: (state, deviceSN) => {
    state.deviceSN = deviceSN
    localStorage.setItem('deviceSN', state.deviceSN);
  },
  SET_DEVICE_MODEL: (state, unitModel) => {
    state.unitModel = unitModel
    localStorage.setItem('unitModel', state.unitModel);
  },
}

const actions = {
  setProductLine({ commit }, productLine) {
    commit('SET_PRODUCT_LINE', productLine)
  },
  // 保存设备SN码
  setDeviceSN({commit},deviceSN){
    commit('SET_DEVICE_SN', deviceSN)
  },
  // 保存设备电子设备编码码
  setDeviceModel({commit},unitModel){
    commit('SET_DEVICE_MODEL', unitModel)
  },
  // 厂级编码
  setSystemSysCode({commit},configValue){
    commit('SET_SYSTEM_SYSCODE', configValue)
  },
  SetCloudServerAddress({ commit }, cloudServerAddress) {
    // return new Promise((resolve, reject) => {
      // 正则效验
      // const pattern = /^(https:\/\/)((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)*/;
      // if (pattern.test(cloudServerAddress)) {
        commit('SET_CLOUD_SERVER_ADDRESS', cloudServerAddress)
        // resolve()
     // }
      //  else {
      //   reject("厂级地址格式错误")
      // }
    // })
  },
  SetAuthCode({ commit, dispatch }, authCode) {
    return new Promise((resolve, reject) => {
      // 设置子系统鉴权码
      commit('SET_AUTH_CODE', authCode)
      dispatch('RefreshToken').then(res => {
        resolve(true)
      }).catch(err => {
        reject(err)
      });
    })
  },
  SetIpAddress({ commit, dispatch }, ipAddress) {
    return new Promise((resolve, reject) => {
      const pattern= /^(?=.*\d)(?=.*\.).+$/
      if (pattern.test(ipAddress)){
        commit('SET_IP_ADDRESS', ipAddress)
        dispatch('RefreshToken').then(res => {
          resolve(true)
        }).catch(err => {
          reject(err);
        });
      }else {
        reject("ip地址格式不正确")
      }

    })
  },
  // 刷新子系统token
  RefreshToken({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 用授权码去厂级获取access_token
      subSysToken({ authCode: state.authCode }).then(res => {
        // token不为空
        if (res.code == 200 && res.data.access_token) {
          // console.log(res.data.access_token)
          commit('SET_ACCESS_TOKEN', res.data.access_token)
          resolve(true);
        } else {
          commit('SET_ACCESS_TOKEN', null);
          dispatch('ReConfig');
          reject(res);
        }
      }).catch(err => {
        // console.error(err)
        commit('SET_ACCESS_TOKEN', null);
        dispatch('ReConfig');
        reject(err);
      })
    })
  },
  InitSysConf({ commit, state, dispatch }) {
    // alert(state.authCode)
    if (state.authCode && !state.isRefreshToken) {
      commit('SET_IS_REFRESH_TOKEN', true)
      // 初始化时默认刷新一次
      dispatch('RefreshToken')
      // 定时刷新 1小时刷新1次
      setInterval(function () {
        dispatch('RefreshToken')
      }, 1000 * 60 * 60)
    }

    if (!state.authCode) {
      dispatch('ReConfig');
    }
  },
  // 重新配置子系统信息
  ReConfig({ commit, state }) {
    // 当前不是注册界面
    if (location.href.indexOf('system-init') == -1) {
      Dialog.confirm({
        title: '系统提示',
        message: '当前子系统无法与边侧系统建立通讯，是否重新配置注册信息',


      }).then(() => {
        // console.log("正在前往注册界面")
        location.href = '#/system-init';
      }).catch(() => {
      });
    }

  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
