import {
  login,
  logout,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash,
  getUnreadCount
} from '@/api/system/user/login'
import {setToken, getToken, setTagNavListInLocalstorage, localRead} from '@/libs/base/util'
import maxLogo from '@/assets/images/dongke_logo.png'
import mainService from '@/api/main'
import store from '@/store'
import config from '@/config'
import Router from 'vue-router'
import router, {resetRouter} from '@/router'
import {getRouteTree2, filterAsyncRouter} from '@/libs/base/router-util'
import {convertToChildrenMain, handleMenu} from '@/libs/tools/user-tools'
import {request} from "@/api/base";

let Base64 = require('js-base64').Base64

export default {
  state: {
    imagePath: '',
    imagePathType: '',
    userName: '',
    id: '',
    avatorImgPath: '',
    token: getToken(),
    access: [],
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    userCode: '',
    loginType: 1,
    cpId: 0,
    // dealerCode:'',
    userPwd: '',
    // 是否是初始化密码
    flgInitPwd: null,
    // 密码过期日期
    pwdDate: null,
    //业务部门id
    orgId: null,
    //业务部门名称
    orgName: null,
    //渠道名称
    salesChannelName: null,
    //渠道Id
    salesChannel: null,
    //所在城市
    cityName: null,
    //用户表格设置
    userTableSetting: null,
    roleName: null,
    // 系统参数
    setting: {},
    // 服务代码
    svcCode: '',
    // 加入的公司
    joinedCpList:[]
  },
  mutations: {
    setUserPwd(state, userPwd) {
      state.userPwd = userPwd
    },
    setAvator(state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setId(state, id) {
      state.id = id
    },
    setUserName(state, name) {
      state.userName = name
    },
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setMessageCount(state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList(state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList(state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList(state, list) {
      state.messageTrashList = list
    },
    setUserCode(state, userCode) {
      state.userCode = userCode
    },
    setLoginType(state, loginType) {
      state.loginType = loginType
    },
    setAppCode(state, appCode) {
      state.appCode = appCode
    },
    setCpId(state, cpId) {
      state.cpId = cpId
    },
    setCpCode(state, cpCode) {
      state.cpCode = cpCode
    },
    setCpName(state, cpName) {
      state.cpName = cpName
    },
    setAccess(state, access) {
      state.access = access || []
    },
    setRoleName(state, roleName) {
      state.roleName = roleName
    },
    updateMessageContentStore(state, {msg_id, content}) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg(state, {from, to, msg_id}) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    },
    setFlgInitPwd(state, flgInitPwd) {
      state.flgInitPwd = flgInitPwd
    },
    setOrgId(state, orgId) {
      state.orgId = orgId
    },
    setOrgName(state, orgName) {
      state.orgName = orgName
    },
    setCityName(state, cityName) {
      state.cityName = cityName
    },
    setStaffId(state, staffId) {
      state.staffId = staffId
    },
    setRoleIds(state, roleIds) {
      state.roleIds = roleIds
    },
    setStaffName(state, staffName) {
      state.staffName = staffName
    },
    setSetting(state, setting) {
      state.setting = setting
    },
    setUserTableSetting(state, setting) {
      state.userTableSetting = setting
    },
    setPwdDate(state,pwdDate){
      state.pwdDate = pwdDate
    },
    setSvcCode(state, svcCode){
      state.svcCode = svcCode
    },
    setBaseUrl(state, baseUrl){
      state.baseUrl = baseUrl
    },
    setJoinedCpList(state, joinedCpList){
      state.joinedCpList = joinedCpList
    },
    setDefaultWhId(state, defaultWhId){
      state.defaultWhId = defaultWhId
    },
    setDefaultWhName(state, defaultWhName){
      state.defaultWhName = defaultWhName
    },
    setDataKindList(state, dataKindList){
      state.dataKindList = dataKindList
    },
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    getRouters({commit}) {
      return new Promise((resolve, reject) => {
        try {
          getRouterReq().then(res => {
            let routers = backendMenusToRouters(res.data)
            commit('setRouters', routers)
            commit('setHasGetRouter', true)
            resolve(routers)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    /**
     * @desc   : 登录
     * @author : 周兴
     * @date   : 2024/3/4 15:44
     */
    handleLogin({commit}, {userCode, userPwd}) {
      userCode = userCode.trim()
      return new Promise((resolve, reject) => {
        login({
          userCode,
          userPwd,
        }).then(res => {
          const data = res.data
          if (data) {
          } else (commit('setToken', ''))
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    /**
     * @desc   : 切换公司
     * @author : 周兴
     * @date   : 2024/3/19 15:39
     */
    changeCp(data,joinedCps){
      let params = {}
      params.appCode = config.appCode.WEB
      params.userId = data.state.id
      params.userName = data.state.userName
      params.cpId = data.state.cpId
      params.currentCp = data.state.cpId
      params.joinedCps  = joinedCps;
      params.cpCode = data.state.cpCode
      return request('oauth-server/oauth/change_cp', params)
    },
    /**
     * @desc   : 登录之后获取基础数据
     * @author : 周兴
     * @date   : 2024/3/4 15:43
     */
    getInfoAfterLogin(data){
      let params = {}
      params.appCode = config.appCode.WEB
      params.userId = data.state.id
      params.cpId = data.state.cpId
      params.cpCode = data.state.cpCode
      params.lang = localRead('local_lan');
      return request('mdm-server/mst/staff/get_info_after_login', params)
    },
    /**
     * @desc   : 处理登录后的数据
     * @author : 周兴
     * @date   : 2024/3/4 17:25
     */
    handleAfterLoginInfo({commit}, data){
      // menu菜单
      let menu = data.menuList;
      let menuCopy = menu.copy();
      menuCopy = menuCopy.filter(it =>  it.objectCode !== 'home')
      sessionStorage.setItem('menu', JSON.stringify(menuCopy))
      // 功能权限
      if (data.function) {
        sessionStorage.setItem('function', JSON.stringify(data.function))
      }
      // 处理数据
      menu = handleMenu(menu);
      let arr = convertToChildrenMain(menu,'parentId','id','objectPath');
      console.log('menu', menu, arr,arr.copy())
      commit('setMenuList', arr.copy())
      // 记录员工信息
      commit('setStaffId', data.staff.staffId)
      commit('setStaffName', data.staff.staffName)
      // 记录部门信息
      commit('setOrgId', data.staff.orgId)
      commit('setOrgName', data.staff.orgName)
      // 默认仓库
      commit('setDefaultWhId', data.staff.defaultWhId)
      commit('setDefaultWhName', data.staff.defaultWhName)
      // 记录系统字典
      commit('setDataKindList', data.dataKindList)
      // 角色
      commit('setRoleIds',data.staff.roleIds)
      if(data.settingValue && data.settingValue.setting){
        let setting = JSON.parse(data.settingValue.setting.value)
        // 参数
        commit('setSetting',setting)
      }

      sessionStorage.setItem('route', JSON.stringify(arr))
      // console.log('routes',routes)
      router.addRoutes(filterAsyncRouter(arr,menu))
    },
    /**
     * @desc   : 更新token
     * @author : 周兴
     * @date   : 2024/3/19 16:13
     */
    updateToken({commit}, data){
      sessionStorage.setItem('token', data.accessToken)
      commit('setToken', data)
    },
    /**
     * @desc   : 登录后处理
     * @author : 洪旭东
     * @date   : 2022-06-09 16:14
     */
    afterLogin({commit}, data) {
      // 保存系统参数
      commit('setSetting', data.setting)
      store.dispatch('saveSetting')

      sessionStorage.setItem('online', 'true')
      sessionStorage.setItem('login', 'login')
      sessionStorage.setItem('token', data.accessToken)
      commit('setId', data.userId)
      commit('setUserCode', data.userPhone)
      commit('setUserName', data.userName)
      commit('setToken', data.accessToken)
      let joinedCpList = []
      if (data.joinedCpList && data.joinedCpList.length > 0) {
        joinedCpList = data.joinedCpList;
      }
      // 加入体验公司
      joinedCpList = joinedCpList.union(config.expCp);
      commit('setJoinedCpList', joinedCpList)
      // commit('setLoginType', data.user.sysId)
      // todo 前台保存权限
      // commit('setAccess', data.user.funCodeList)

      commit('setAvator', maxLogo)
      // commit('setFlgInitPwd', data.user.flgInitPwd)
      // commit('setOrgId', data.user.orgId)
      // commit('setOrgName', data.user.orgName)
      if(data.company){
        commit('setCpId', data.company.cpId)
        commit('setCpCode', data.company.cpCode)
        commit('setCpName', data.company.cpName)
        commit('setSvcCode', data.company.svcCode)

        if(data.company.svcIp && data.company.svcPort){
          commit('setBaseUrl', data.company.svcIp + ':' + data.company.svcPort )
        }
      }

      // commit('setStaffId', data.user.staffId)
      // commit('setStaffName', data.user.staffName)
      // commit('setRoleIds', data.user.roleIds)
      // commit('setUserTableSetting', data.userTableSetting)
      //菜单类型 默认抽屉
      // commit('setMenuType', data.menuType || 'drawer')
      // commit('setPwdDate', data.user.pwdDate)
    },

    /**
     * @desc   : 登录后处理
     * @author : 洪旭东
     * @date   : 2022-06-09 16:14
     */
    updateCompany({commit}, company) {
      if(company){
        console.log('ttt',company)
        commit('setCpId', company.cpId)
        commit('setCpCode', company.cpCode)
        commit('setCpName', company.cpName)
        commit('setSvcCode', company.svcCode)
        if(company.svcIp && company.svcPort){
          commit('setBaseUrl', company.svcIp + ':' + company.svcPort )
        }
      }
    },

    /**
     * @desc   : 给用户表格缓存赋值
     * @author : 周兴
     * @date   : 2023/5/11 10:39
     */
    setUserTableSettingAfter({commit}, data) {
      commit('setUserTableSetting', data)
    },

    /**
     * @desc   : 设置菜单
     * @author : 周兴
     * @date   : 2023/5/11 10:48
     */
    setMenuListAfter({commit}, data){
      commit('setMenuList', data)
    },

    /**
     * @desc   : 读取系统参数
     * @author : 洪旭东
     * @date   : 2022-09-20 13:02
     */
    saveSetting({state}) {
      let data = state.setting
      // 保存系统参数
      // if (data.HGSCRM_OSS1) {
      //   if (!data.HGSCRM_OSS1.endsWith('/')) {
      //     data.HGSCRM_OSS1 += '/'
      //   }
      //   config.imgUrl = data.HGSCRM_OSS1
      // } else {
      //   config.imgUrl =process.env.VUE_APP_IMG_URL
      // }
      config.imgUrl = process.env.VUE_APP_IMG_URL
      // if (data.HGHAP_OSS2) {
      //   if (!data.HGHAP_OSS2.endsWith('/')) {
      //     data.HGHAP_OSS2 += '/'
      //   }
      //   config.hgImgUrl = data.HGHAP_OSS2
      // } else {
      //   config.hgImgUrl = process.env.VUE_APP_HG_IMG_URL
      // }
      config.hgImgUrl = process.env.VUE_APP_HG_IMG_URL
    },

    // 退出登录
    handleLogOut({state, commit}) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        commit('setTagNavList', [])
        commit('setMenuList', [])
        // mainService.closeByHand()
        //退出后清空tagList
        setTagNavListInLocalstorage([])
        sessionStorage.removeItem('route')
        sessionStorage.removeItem('token')
        resetRouter()
        resolve()
      })
    },

    // 根据当前点击的消息的id获取内容
    getContentByMsgId({state, commit}, {msg_id}) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', {msg_id, content})
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead({state, commit}, {msg_id}) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageUnreadList',
            to: 'messageReadedList',
            msg_id
          })
          commit('setMessageCount', state.unreadCount - 1)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded({commit}, {msg_id}) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageReadedList',
            to: 'messageTrashList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash({commit}, {msg_id}) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageTrashList',
            to: 'messageReadedList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    pushAccess({state, commit}, access) {
      return new Promise((resolve, reject) => {
        state.access.push({code: access})
        commit('setAccess', state.access)
        resolve()
      })
    },
    removeAccess({state, commit}, access) {
      return new Promise((resolve, reject) => {
        state.access.filter(it => it.code !== access)
        commit('setAccess', state.access)
        resolve()
      })
    },
    /**
     * @desc   : 刷新token
     * @author : 洪旭东
     * @date   : 2022-05-10 14:15
     */
    refreshToken({state, commit}, token) {
      commit('setToken', token)
    },

    /**
     * @desc   : 强制修改密码后 修改flgInitPwd
     * @author : 沈博
     * @date   : 2022/7/5 13:01
     */
    refreshFlgInitPwd({state, commit}, flag) {
      commit('setFlgInitPwd', flag)
    },
  }
}
