<template>
	<div v-if="$route.name!='loginPage'">
		<v-header :userName="userName" :portrait="portrait" :idType="idType"></v-header>
    <v-slidebar :authList="authList" :tokenValue="token" :storageIdType="storageIdType" :notCompleteCount="redNum" :masterFlag="masterFlag"></v-slidebar>
		<el-container>
			<div class="content" id="body-content">
				<transition name="router-fade" mode="out-in">
					<keep-alive>
						<router-view v-if="$route.meta.keepAlive"></router-view>
					</keep-alive>
				</transition>
				<transition name="router-fade" mode="out-in">
					<router-view v-if="!$route.meta.keepAlive"></router-view>
				</transition>
				<v-footer></v-footer>
			</div>
		</el-container>
  </div>
  <div class="login-div" v-else>
    <transition name="router-fade" mode="out-in">
      <router-view v-if="!$route.meta.keepAlive"></router-view>
    </transition>
  </div>
</template>

<script>
import VHeader from './views/layout/header.vue'
import VSlidebar from './views/layout/slidebar.vue'
import VFooter from './views/layout/footer.vue'
import { base64decode, isNotEmptyUtils, getUrlParamsMap } from "./utils/utils.js"
import { mapActions, mapGetters } from 'vuex'
import { getLoginUrl } from './utils/index.js'
import { getRedNum, getCircleRole } from './utils/patients/patientsapi'
let vm = null
export default {
	components:{
		VHeader,
		VSlidebar,
		VFooter
	},
	data() {
		return {
			idType: 0,
      storageIdType: 0,
			token: '',
			userName: '',
			portrait: '',
			authList: {},
			redNum: 0,
			masterFlag: false,
		}
	},
	computed:{
		...mapGetters([
			'_token'
		])
	},
	created() {
		vm = this
    if(vm.$route.name!='loginPage') {
     vm.getToken()
    }
	},
	mounted() {
	  vm.getRedData()
    function checkIE(){
      return '-ms-scroll-limit' in document.documentElement.style && '-ms-ime-align' in document.documentElement.style
    }
    if (checkIE()) {
      window.addEventListener('hashchange', () => {
        let currentPath = window.location.hash.slice(1);
        if (this.$route.path !== currentPath) {
          this.$router.push(currentPath)
        }
      }, false)
    }
	},
	methods: {
    ...mapActions('reservationManage',['getUserName']),
		// 解密token
		getToken() {
			let href = window.location.href
			let offset = href.indexOf("?")
			if(offset !== -1) {
				let paramStr = href.substring(offset + 1, href.length)
				let pars = base64decode(paramStr)
				let paramMap = getUrlParamsMap(pars, "&")
				if (isNotEmptyUtils(paramMap["token"])) {
					vm.token = paramMap["token"]
					localStorage.setItem('storageToken', vm.token)
          vm.$router.push({ path: 'home' })
          // if(href.indexOf("mypatients-manage/patients-list") > -1) {
          //   // vm.$router.push({ path: 'patients-manage/mypatients-manage/patients-list' })
          //   vm.$router.push({ path: 'patients-list' })
          // }else {
          //   vm.$router.push({ path: 'home' })
          // }
				} else {
					if(!localStorage.getItem('storageToken')) {
					  console.log('域名',window.location.host)
            if(window.location.host.indexOf("work.yunqueyi") != -1&&window.location.host.indexOf("test2-work.yunqueyi") == -1) {
              window.location.href = getLoginUrl('?from=work&type=logout')  // 没有token返回登录页面
              return;
            } else {
              this.$router.push('/login')
              return;
            }

					}
				}
			}else {
				if(!localStorage.getItem('storageToken')) {
          if(window.location.host.indexOf("work.yunqueyi") != -1&&window.location.host.indexOf("test2-work.yunqueyi") == -1) {

            window.location.href = getLoginUrl('?from=work&type=logout')  // 没有token返回登录页面
            return;
          } else {
            this.$router.push('/login');
            return;
          }
				}
			}
			vm.changeToken(vm.token)
			vm.getUserAuth(vm.token)
		},
		// 修改token
		...mapActions([
			'changeToken',
			'changeIdType',
			'changeMaster'
		]),
		// 获取用户权限
		getUserAuth(token) {
      vm.getCircleRoleData();
			let req = null
			req = {
				token: token
			}
			vm.GET('portal/common/v1/role',req).then((res) => {
				if(res.code == '000000') {
					vm.changeIdType(res.data.idType)
					vm.changeMaster(res.data.masterAdministratorFlag)
					localStorage.setItem('storageIdType', res.data.idType)
					localStorage.setItem('isRoleOfOuter', res.data.isRoleOfOuter)
					localStorage.setItem('storageMaster', res.data.masterAdministratorFlag)
					vm.idType = res.data.idType
					vm.storageIdType = res.data.idType
					vm.masterFlag = res.data.masterAdministratorFlag
					vm.userName = res.data.name
					vm.portrait = res.data.imageUrl
					vm.authList = res.data.auth
          vm.getUserName(vm.userName);
				} else {
					vm.$message.info(res.message)
				}
			})
		},
    setStoreData(value) {
      if (value){
        return 1;
      }else {
        return 0;
      }
    },
    getCircleRoleData() {
      localStorage.removeItem('highMainManager');
      localStorage.removeItem('mainManager');
      localStorage.removeItem('manager');
      localStorage.removeItem('ordinary');
      getCircleRole({}).then((res) => {
        if(res.code == '000000') {
          //mainManager主管理员，manager管理员，ordinary普通人
          const { highMainManager, mainManager, manager, ordinary} = res.data;
          localStorage.setItem('highMainManager', vm.setStoreData(highMainManager))
          localStorage.setItem('mainManager', vm.setStoreData(mainManager))
          localStorage.setItem('manager', vm.setStoreData(manager))
          localStorage.setItem('ordinary', vm.setStoreData(ordinary))
        } else {
          vm.$message.info(res.message)
        }
      })
    },
    getRedData() {
      getRedNum({
        openTime: (new Date()).getTime()
      }).then((data) => {
        if(data.code == '000000') {
          vm.redNum = data.data
        }
      }).catch(error => {
        vm.$message.error(error)
      })
    }
	},
  watch: {
    _token(val) {
      if(val!=undefined&&val!=null) {
        vm.getUserAuth(val)
      }
    },
    $route:{
      deep:true,
      handler:function(newVal){
        if(vm.$route.path == '/patients-manage/not-complete/uncompleted-list'){ //避免重复请求
          vm.redNum = 0
        }
      }
    }
  }
}
</script>

<style lang="scss">
  	// @import './style/common';
  	@import './style/global';
  	@import './style/mixin.scss';
	.router-fade-enter-active, .router-fade-leave-active {
	  	transition: opacity .1s;
	}
	.router-fade-enter, .router-fade-leave-active {
	  	opacity: 0;
	}
	.el-container {
		margin-left: 255px;
		overflow: hidden;
		.content {
			background: #F0F2F5;
			position: absolute;
			left: 255px;
			right: 0;
			top: 64px;
			bottom: 0;
			width: auto;
			box-sizing: border-box;
			overflow-y: scroll;
		}
	}
  .login-div {
    height: 100%;
  }
  .check-auth{
    width: 480px!important;
    height: 240px;
    padding: 20px 50px;
    .el-message-box__content{
      padding:20px 0;
      margin-bottom: 10px;
    }
  }
</style>
