import {baseLogin, logout} from '@main/api/login'
import {getInfo,getBzList,getSSOInfo,getSSOTicket} from '@main/api/user'
import { getToken, setToken, removeToken,setCookieUserid,removeCookieUserid } from '@main/utils/auth'
import {getUrlValue,getUrlSearch} from '@main/utils'
import md5 from 'js-md5'
if(window.Scp==null){
  window.Scp = {} 
}
if(window.Scp.User==null){
  window.Scp.User={}
}
const user = {
  namespaced: true,
  state: {
    token: getToken(),
    avatar: '',
    introduction: '',
    roles: [],
    //后面加的
    userInfo: {},
    bzList: null,
    id:Scp.User.id,
    name:Scp.User.name,
    deptId:Scp.User.deptId,
    deptName:Scp.User.deptName,
    positionId:Scp.User.positionId,
    postionName:Scp.User.postionName,  
  
    bzId:Scp.User.bzId,
    bzName:Scp.User.bzName,
  
    bzDeptId:Scp.User.bzDeptId,
    bzDeptName:Scp.User.bzDeptName,
  
    bzPositionId:Scp.User.bzPositionId,
    bzPositionName:Scp.User.bzPositionName,
  
    orgId:Scp.User.orgId ,
    defOrgId:Scp.User.defOrgId,
    showPwDialog:false,
    ssoInfo:null,
  },
  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_BZLIST: (state, bzList) => {
      state.bzList = bzList
    },
    SET_PWDIALOG: (state, isShow) => {
      state.showPwDialog = isShow
    },
  },
  actions: { 
    load({ commit, state }) {
      
    },
    // user login
    login({ commit }, userInfo) {
      let pushData={};
      if(userInfo){
        const { username, password } = userInfo
        pushData={ 
          username: username.trim(), 
          password: md5(password) 
        };
      }
      return new Promise((resolve, reject) => {
        if(window.HIVUI_SETTING.url!=location.origin){
          let searchParams=getUrlSearch(location.href);
          delete searchParams.ticket;
          let service=location.origin+location.pathname+"?";
          for(let k in searchParams){
            service+=k+"="+searchParams[k]+"&";
          }
          service=service.slice(0,-1);
          pushData={
            type:"casPre",
            ticket:getUrlValue('','ticket'),
            service:service
          };
        }
        baseLogin(pushData).then(response => {
          const data = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 多岗
    getBzList({ commit, state }) {
      return new Promise((resolve, reject) => {
        getBzList().then(response => {
          let _arr=response.dataPack
          if (_arr) {
            if (!_arr || _arr.length < 0) {
              reject('getInfo: data must be a non-null array!')
            }
            commit("SET_BZLIST",_arr);
            resolve(_arr)
          }else{
            reject('Verification failed, please Login again.');
          }
        }).catch(error => {
          reject(error)
        });
      })
    },
    // get user info
    getInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          if (!response.dataPack) {
            reject('Verification failed, please Login again.')
          }
          //const { info ,org} = response.data;
          const info = response.dataPack
          // if (!info) {
          //   reject('Verification failed, please Login again.')
          // }

          //const { roles, name, avatar, introduction } = data
          window.Scp.User=info;
          let roles = ['admim'], avatar = "", introduction = "", name = info.fuserid, userInfo = info;
          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }
          commit('SET_USERINFO', userInfo);
          commit('SET_ROLES', roles);
          commit('SET_NAME', name);
          commit('SET_AVATAR', avatar);
          commit('SET_INTRODUCTION', introduction);
          setCookieUserid(name);
          resolve(info);
        }).catch(error => {
          reject(error);
        })
      })
    },

    // user logout
    logout({ commit, state }) {
      return new Promise((resolve, reject) => {
        if(!getToken()){
          resolve();
        }else{
          logout().then(() => {
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            removeToken();
            removeCookieUserid();
            resolve();
          }).catch(error => {
            reject(error);
          });
        }        
      });
    },

    // remove token
    resetToken({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_ROLES', []);
        removeToken();
        removeCookieUserid();
        resolve();
      })
    },

    // dynamically modify permissions
    changeRoles({ commit, dispatch }, role) {
      return new Promise(async resolve => {
        const token = role + '-token'

        commit('SET_TOKEN', token)
        setToken(token)

        const { roles } = await dispatch('getInfo')

        //resetRouter()
        // generate accessible routes map based on roles
        const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

        // dynamically add accessible routes
        router.addRoutes(accessRoutes)

        // reset visited views and cached views
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      })
    },
    //修改密码弹窗
    showPwDialog({ commit, dispatch }, isShow){
      commit('SET_PWDIALOG', isShow);
    },
    //获取单点登录服务器信息
    getSSOInfo({state, dispatch}){
      return new Promise((resolve, reject) => {
        getSSOInfo().then((res)=>{
          state.ssoInfo=res.dataPack;
          resolve(res);
        }).catch(err=>{
          reject(err);
        });
      });
    },
    //单点跳转功能
    async openSSOFuncPage({state, dispatch},opt){
      await dispatch("getSSOInfo");
      if(state.ssoInfo){
        let res=await getSSOTicket(state.ssoInfo.serverUrl,{
            'clientId': state.ssoInfo.clientId,
            'token': state.token,
            'pn':state.ssoInfo.serverPn,
        });
        if (res.status == 200) {
          let __service = encodeURIComponent((opt.serviceUrl.startsWith("http")?"":location.origin+(opt.serviceUrl.startsWith("/")?"":"/"))+opt.serviceUrl);
          let returnUrl = state.ssoInfo.serverUrl + (state.ssoInfo.serverUrl.endsWith("/")?"":"/")+"sso/remote-login?service=" + __service + "&ticket=" + res.dataPack;
          return returnUrl;
          //window.open(returnUrl, "_black");
        }
      }
      return opt.serviceUrl;
    },
  }
}

export default user