<template>
    <el-container :class="getRole">
        <el-aside>
            <div class="logo">
                <p v-if="userLoginDTO&&userLoginDTO.type=='0'"><b>医院知识库后台管理系统</b></p>
            </div>
            <lt-menu v-if="menuWrappers&&menuWrappers.length" v-bind:role="getRole" v-bind:data="menuWrappers"></lt-menu>
        </el-aside>
        <el-container>
            <el-header class="clearfix">
                <div class="title fl">
                    <h2>{{organization&&organization.name}}</h2>
                </div>
                <div class="userInfo fr">
                    <span class="username" @click="goCenter">
                      <i>{{userLoginDTO&&userLoginDTO.linkman}}</i>
                      <img class="actionDo" src="../../images/arrow_down.png" />
                    </span>
                    <ul class="action">
                      <li @click="changeWords">修改密码</li>
                      <li @click="logout">退出系统</li>
                    </ul>
                </div>
            </el-header>
            <el-main>
              <router-view v-if="ok" v-on:status-change="changeStatus"></router-view>
            </el-main>
        </el-container>
        <el-dialog
          title="修改密码"
          class="changewords"
          :visible.sync="changePassWord"
          width="600"
          top="20vh"
          center>
          <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="100px" class="demo-ruleForm">
            <el-form-item label="旧密码：" prop="oldpass">
              <el-input type="password" placeholder="请输入旧密码" @keyup.enter.native="submitForm('ruleForm2')" v-model.trim="ruleForm2.oldpass" auto-complete="off"></el-input>
            </el-form-item>            
            <el-form-item label="新密码：" prop="pass">
              <el-input type="password" placeholder="6-20位,可输入字符、数字或符号" @keyup.enter.native="submitForm('ruleForm2')" v-model.trim="ruleForm2.pass" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="再次输入新密码：" prop="checkPass">
              <el-input type="password" placeholder="6-20位,可输入字符、数字或符号" @keyup.enter.native="submitForm('ruleForm2')" v-model.trim="ruleForm2.checkPass" auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm('ruleForm2')">确 定</el-button>
          </span>
        </el-dialog>
    </el-container>
</template>

<script>
  import LtMenu from '../common/Menu.vue';
  import api from '@api/index.js';
  import newIcon from '../../images/new.png';
  import md5 from 'js-md5'
  export default {
    name: 'homepage',
    components: {
      'lt-menu': LtMenu,
    },
    data() {
      var validatePass1 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入旧密码'));
        } else {
          callback();
        }
      };
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        menuWrappers: null,
        organization: null,
        userLoginDTO: null,
        authStatus: null,
        authStatusName:'',
        ok:false,           //是否已获取到菜单
        versionName:'',
        versionVisible:false,
        versionInfo:'',
        isNewV:false,
        version:null,       //版本信息接口返回的数据
        changePassWord: false,

        ruleForm2: {
          pass: '',
          checkPass: '',
          oldpass: ''
        },
        rules2: {
          oldpass: [
            { validator: validatePass1, trigger: 'change',required:true }
          ],
          pass: [
            { min: 6, max: 20, message: '密码要求6-20位，可输入字母、数字或符号', trigger: 'blur' },
            { validator: validatePass, trigger: 'blur',required:true }
          ],
          checkPass: [
            { min: 6, max: 20, message: '密码要求6-20位，可输入字母、数字或符号', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur',required:true }
          ]
        }
      }
    },
    computed: {
      getRole: function () {
        return 'admin'
      }
    },
    created () {
      //获取菜单
      this.getMenuList();
    },
    watch:{
      '$route': function(to,from){
            if(from.name=='login'){
              this.getMenuList();
            }
            if(to.path=='/'){       // 退出时清空菜单
              this.menuWrappers=[];
              this.isNewV = false;
            }
        }
    },
    methods: {
      CalcuMD5(password){
        password = md5(password);
        return password;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.midifyPassword({
              'password':this.CalcuMD5(this.ruleForm2.oldpass),
              'modifyPassword':this.CalcuMD5(this.ruleForm2.pass)
            }).then((res) => {
              if (res.data.code == '0') {
                const data = res.data.data;
                this.$refs['ruleForm2'].resetFields();
                this.changePassWord = false
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 1000,
                  onClose:()=>{
                    // this.logout()
                  }
                })
              } else if(res.data.code === '00020005'){
                console.log('原密码错误');
                  this.$refs['ruleForm2'].clearValidate()
                  // 手动操作校验、展示登录错误信息
                  this.rules2.oldpass.push({ // js新增一个自定义校验
                    validator: (rule, value, callback) => {
                      callback('旧密码输入错误')
                    },
                    trigger: 'change'
                  })
                  this.$refs['ruleForm2'].validateField('oldpass') // 手动校验
                  this.rules2.oldpass = this.rules2.oldpass.slice(0, 1) // 删除校验
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error',
                  duration: 1000,
                })
              }
            }).catch((error) => {
              console.log(error);
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      changeWords(){
        this.changePassWord = true
        this.$refs['ruleForm2'] && this.$refs['ruleForm2'].resetFields();
      },
      getMenuList(){
        api.getAccessdMenu().then((res) => {
          if (res.data.code == '0') {
            const data = res.data.data;
            this.ok = true;
            const hasConcole=data.menuWrappers.find((it)=>{
              return it.code.indexOf('-KZT')>-1;
            });
            this.menuWrappers = data.menuWrappers;
            this.organization = data.organization;
            this.userLoginDTO = data.userLoginDTO;
            localStorage.setItem('userLoginDTO', JSON.stringify(data.userLoginDTO));
            if(hasConcole){
              const url = '/admin/LT-KZT';
              this.$router.push({path:url});
            }
          }
        }).catch((error) => {
          console.log(error);
        });
      },
      isNewVersion(){           //判断是否为新版

      },
      changeStatus(text){       //账号信息中提交认证后修改状态
        this.authStatus = 2;
        this.authStatusName = text;
      },
      goCenter(){
        
      },
      logout(){//退出
        localStorage.removeItem('token');
        this.$router.push({path:'/'});
      }
    }
  }
</script>

<style lang="less">

    @import '../../less/common.less';

    .user .el-menu-item.is-active {
        color: @userBase;
    }

    .admin .el-menu-item.is-active {
        color: @adminBase;
    }
    .admin .username{
        cursor: pointer;
    }
    .version-info h3{
        font-size: 14px;
        margin-bottom: 20px;
        span{
            float: right;
            font-weight: normal;
        }
    }
</style>
<style lang="less" scoped>
    @import '../../less/common.less';
    .el-menu-vertical-demo.el-menu{
        height: calc(100% - 120px);
        overflow-y: auto;
    }
    .userInfo {
      position: relative;
      padding-left: 20px;
      cursor: pointer;
      .username {
        font-size: 14px;
        color: #545455;
        img {
          width: 10px;
          margin-left: 8px;
          position: relative;
          bottom: 2px;
        }
      }
      &:hover .action {
          display: block;
      }
      .action {
        width: 94px;
        height: 70px;
        box-shadow: 1px 2px 8px 1px #ccc;
        border-radius: 3px;
        position: absolute;
        top: 50px;
        right: -5px;
        z-index: 999;
        background-color: #fff;
        color: #333;
        font-size: 14px;
        display: none;
        li {
          height: 35px;
          line-height: 35px;
          text-align: center;
          cursor: pointer;
          &:hover {
            background-color: #F2F2F2;
          }
        }
      }  
    }
    .version{
        position: fixed;
        bottom: 0;
        width: @aside-width;
        min-width: 270px;
        font-size: 12px;
        /*text-indent: 50px;*/
        text-align: center;
        height:54px;
        line-height: 54px;
        background: #fff;
        i{
            display: inline-block;
            width: 20px;
            height: 16px;
            img{
                vertical-align: text-top;
            }
        }
    }
    .user .version a{
        color: @userBase;
    }
    .admin .version a{
        color: @adminBase;
    }
    .user .logo {
        background: @userBase;

    p {
        font-size: 16px;
        line-height: normal
    }

    }
    .admin .logo {
        background: @adminBase;

    p {
        font-size: 18px;
        line-height: 40px;
    }

    }
    .title {

    h2 {
        display: inline-block;
        line-height: 60px;
        font-size: 18px;
    }

    }
    .block {
        height: 40px;
        width: 100%;
        background: #fff;
        box-shadow: 0px 1px 2px #c9c9c9;
    }
		.el-main{
			padding: 0;
		}
    .el-button{
      margin-left: 15px;
    }
    .changewords{
      // /deep/ .el-icon-circle-close{
      //   display: none;
      // }
      .dialog-footer{
        .el-button{
          // float: right;
          position: relative;
          left: 200px;
        }
      }
    }
</style>