import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getMobileRouters } from "@/api/common/system";
import {ws_server_url} from '@/utils/config.js'
import {checkUserFirstLogin} from '@/api/login.js'
import Vue from 'vue'

let socketTask;
let pingTimer;
const user = {
  state: {
    token: getToken(),
    name: storage.get(constant.name),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
	isModel: storage.get(constant.isModel),//演示模式  -false当前账号  true是演示账号
	cacheToken: storage.get(constant.cacheToken),
	showSts:  0, //是否显示试用按钮 0不显示，1显示
	dynList: [],
    wsMsg:null,
    wsMsgNum:0,
	nickName: storage.get(constant.nickName),
	avatar: storage.get(constant.avatar),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
	SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName
      storage.set(constant.nickName, nickName)
    },
	SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },

    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
	SET_MODEL: (state, data) => {
	    state.isModel = data
		storage.set(constant.isModel, data)
	},
	SET_SHOW_STS: (state, data) => {
	    state.showSts = data
	},
    SET_WSMSG: (state, data) => {
        // if(state.wsMsgNum===Number.MAX_SAFE_INTEGER)state.wsMsgNum=0
        state.wsMsgNum++
        state.wsMsg = data
    }
  },

  actions: {
	  setIsModel({ commit,state,dispatch },data){
		  let that = this
	  	  return new Promise((resolve, reject) => {
			  
			  commit('SET_MODEL', data)
			  
			  if (data) {
				  let ajaxData = {
				  		username: "qilin",
				  		password: "Tq123456",
				  		client: "TQ-HW-MOBILE",		  
				  }
				  login(ajaxData).then(res => {
					  state.cacheToken = state.token
					  storage.set(constant.cacheToken, state.token)
					  
				    setToken(res.token)
				    commit('SET_TOKEN', res.token)
				    resolve()
					
					dispatch('GetInfo').then((res) => {
						uni.reLaunch({
							url: '/pages/index/index'
						})
						setTimeout(() => {
							getApp().checkTabPer()
						},500)
					})
					
				  }).catch(error => {
				    reject(error)
					state.setIsModel = !state.setIsModel
				  })
				  
			  } else {
				  setToken(state.cacheToken)
				  commit('SET_TOKEN', state.cacheToken)
				   resolve()
				   
				   dispatch('GetInfo').then((res) => {
				   	uni.reLaunch({
				   		url: '/pages/index/index'
				   	})
					setTimeout(() => {
						getApp().checkTabPer()
					},500)
				   })
			  }
			 
			  
	  		  
	  		 
	  	   })
	    },
		
	  //设置token
	setTokenData({ commit },{token}){
		  return new Promise((resolve, reject) => {
			  setToken(token)
			  commit('SET_TOKEN', token)
			  resolve()
		   })
	  },
	  
    // 登录
    Login({ commit }, userInfo) {
      
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state,dispatch }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          const user = res.user
		  const {showSts} = res.userConfig
          
          const username = (user == null || user.userName == "" || user.userName == null) ? "" : user.userName
          if (res.roles && res.roles.length > 0) {
            commit('SET_ROLES', res.roles)
            // commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_PERMISSIONS', res.permissions)
          commit('SET_SHOW_STS', showSts)
          commit('SET_NAME', username)
          commit('SET_NICK_NAME', user.nickName)
          commit('SET_AVATAR', user.avatar)
		  
		  dispatch('GetMobileRouters').then((res) => {
		  	
		  })
          dispatch('GetWebSockeMsg',user.userId)//
		  
		  /* 仅第三方钉钉应用有*/
		  if(Vue.prototype.hasHostPlat(["dingH5"]) && Vue.prototype.hasPlat(["enterprises"])) {
			  if(showSts == 1) {
			  			  checkUserFirstLogin().then((res) => {
			  			  	let {code,data} = res
			  			  	
			  			  	if(code == 0 && data) {
			  			  		uni.showModal({
			  			  			title: '提示',
			  			  			content: `点击上方绿色“开始演示”按钮后，系统会生成对应的模拟数据`,
			  			  			showCancel:false,
			  			  			confirmText: '确定',
			  			  			success: function(res) {
			  			  				if (res.confirm) {
			  			  					
			  			  				}
			  			  			}
			  			  		})
			  			  	}
			  			  	
			  			  })
			  }
		  }
		 
		 
		  
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
	
	GetMobileRouters({ commit, state }) {
		return new Promise((resolve, reject) => {
			
		  getMobileRouters({}).then(({code,data}) => {
			  
			  if(code == 0) {
			  	state.dynList = data
			  }
			  
		  }).catch(error => {
		    reject(error)
		  })
		})
	},
      GetWebSockeMsg({ commit, state }, userId) {

          const connectSocket = () => {
              if (socketTask) {
                  socketTask.close();
                  socketTask = null;
              }
             
              socketTask = uni.connectSocket({
                  url: `${ws_server_url}/websocket/${userId}`, //仅为示例，并非真实接口地址。
                  complete: () => { },
                  fail: (e) => {
                      console.log('ws调用失败', e)
                  },
              });

              try {
                  socketTask.onMessage((e) => {
                      let { code } = JSON.parse(e.data)
                      if (pingTimer) clearTimeout(pingTimer);
                      pingTimer = setTimeout(() => {
                          socketTask.send({
                              data: 'ping'
                          })
                      }, 30000);
                      if (code != 'pong') {
                          commit('SET_WSMSG', code)
                      }
                  })
                  socketTask.onOpen((e) => {
                      console.log('onOpen', e)
                  })
                  socketTask.onError((e) => {
                      console.log('onError', e);
                      reconnection();
                  });

                  socketTask.onClose((e) => {
                      console.log('onClose', e);
                      reconnection();
                  });
              } catch (error) {
                  console.log('wx错误', error)
              }



              let reconnectionTimeoutId = null
              const reconnection = () => {
                  if (reconnectionTimeoutId) clearTimeout(reconnectionTimeoutId)
                  reconnectionTimeoutId = setTimeout(() => {
                      connectSocket();
                  }, 3000);
              }

          }
          connectSocket();
      }

  }
}

export default user
