<template>
  <div class="right-menu">
    <div class="menu-item">
          <span style="width: 210px;font-size: 14px;font-weight: 500;color:#05fd3c">当前时间：{{nowtime}}</span>
          <!-- <el-button type="primary" round @click="ddd" size="mini" >关闭告警</el-button>
          <el-badge :value="200" :max="99" class="item" >
            <i class="el-icon-message-solid" style="font-size: 20px;" @click="message"/>
         </el-badge> -->
        </div>
    <el-dropdown trigger="click" size="medium">
      <div id="right-menu-set" class="menu-item">
        <i class="el-icon-s-custom" /><span style="margin-left: 5px" v-if="flag"
          >{{ userInfo.name
          }}<i style="margin-left: 5px" class="el-icon-caret-bottom"
        /></span>
      </div>
      <!-- <el-dropdown-menu slot="dropdown" id="dropdown" class="user-dropdown" :style="device==1?'zoom:1':'zoom:1.06'"> -->
      <el-dropdown-menu slot="dropdown" id="dropdown" class="user-dropdown">
        <!-- <el-dropdown-menu slot="dropdown" id="dropdown" class="user-dropdown"> -->
        <el-dropdown-item>
          <span style="display: block" @click="userclickd()">用户信息</span>
        </el-dropdown-item>
        <el-dropdown-item @click.native="handleResetPassword()">
          <span style="display: block">修改密码</span>
        </el-dropdown-item>
        <el-dropdown-item>
          <span style="dispblock" @click="goto">帮助文档</span>
        </el-dropdown-item>
        <!-- divided  closelostar-->
        <el-dropdown-item @click.native="logout(1)">
          <span style="display: block">清理缓存</span>
        </el-dropdown-item>
        <el-dropdown-item @click.native="logout(0)">
          <span style="display: block">退出登录</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <el-dialog
      :close-on-click-modal="false"
      title="修改密码"
      :visible.sync="dialogVisible1"
      append-to-body
      width="30%"
      :before-close="closepw"
    >
      <el-form ref="passwordform" :model="passwordform" :rules="rules"   label-width="100px">
        <el-form-item label="旧密码:" prop="password">
          <el-input v-model="passwordform.password"  type="password"   placeholder="请输入旧密码"/>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPwd"  class="top" >
          <el-input v-model="passwordform.newPwd"  type="password"  placeholder="请输入新密码"/>
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPwd"  class="top">
          <el-input v-model="passwordform.confirmPwd"  type="password"   placeholder="请输入确认密码"/>
        </el-form-item>
         
        
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button
            text-align="center"
            
            @click="resetForm('passwordform')"
            >取 消</el-button
          >
          <el-button text-align="center" type="primary" @click="submint"
            >确认</el-button
          >
        </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="用户信息"
       append-to-body
      :visible.sync="dialogVisible2"
      width="30%"
    >
      <el-form ref="form" :model="form"  label-width="100px">
        <el-form-item label="用户名称:">
          <el-input v-model="form.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="登录名称:" class="top" >
          <el-input v-model="form.loginName"  :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="归属部门名称:" class="top" >
          <el-input v-model="form.deptName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="拥有的角色:" class="top" >
          <el-input v-model="form.roles" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="电话号码:" class="top" >
          <el-input v-model="form.iphone" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱:" class="top" >
          <el-input v-model="form.emirl" :disabled="true"></el-input>
        </el-form-item>
      
        
        <!-- <el-form-item label="系统类型:">
          <el-input v-model="form.systype" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态:">
          <el-input v-model="form.status" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="登录时间:">
          <el-input v-model="form.lofintime" :disabled="true"></el-input>
        </el-form-item> -->
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import {
  add,
  list,
  getById,
  deleteById,
  dept,
  edit,
  detptree,
  rolelist,
  selecRoleDetail,
  passwordConfirm,
  deluser,
  updatePassword,
  activateUser,
  exportUser,
  exportUserExcel,
} from "@/api/admin/user";
import { gongkey, userfunction } from "@/api/user";
import axios from "axios";
import { sm3Digest } from "@/assets/commjs/sm3";
import { sm2, encrypt } from "@/assets/commjs/sm2.js";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.passwordform.confirmPwd !== "") {
          this.$refs.passwordform.validateField("confirmPwd");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordform.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      flag: true,
      dialogVisible2: false,
      dialogVisible1: false,
      passwordform: {
        password: "",
        newPwd:'',
        confirmPwd:''
      },
      nowtime:'',
      LocationProvince:"正在定位所在省",    //给渲染层定义一个初始值
      LocationCity:"正在定位所在市" ,    //给渲染层定义一个初始值
      form: {
        name: "",
        deptName: "",
        iphone: "",
        emirl: "",
        roles: '',
        loginName: "",
        systype: "",
        status: "",
        lofintime: "",
      },
      password3: "",
      id: "",
      device: 1,
      pd: "",

      rules: {
        password: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: validatePass, trigger: "blur" },
        ],
        newPwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: validatePass, trigger: "blur" },
        ],
        confirmPwd: [
          { required: true, message: "请确认密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
          { validator: validatePass2, trigger: "blur", required: true },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    this.device = window.devicePixelRatio;
 
  
  },
  mounted() {
   // this.city()    //触发获取城市方法
   setInterval(()=>{
      this.getnowtime()
    },500)
  },
  methods: {
    ...mapActions({
      changeSetting: "settings/changeSetting",
    }),

    async logout(t) {
      this.flag = false;
      await this.$store.dispatch("user/logout");
      if(t==1){
        this.$message({
            type: "success",
            message: "缓存清理成功!",
          });
      }else{
         return
      }
    },
    toggleSettings() {
      const showSettings = this.$store.state.app.showSettings;
      this.$store.state.app.showSettings = !showSettings;
    },

    goto(t) {
      //this.$router.push({path:'/algorithm/algorithm1',query:{name:'wtzhpg',path:'/algorithm/algorithm1'}})
      this.$router.push({ path: "/algorithm/algorithm1" });
     
      
    },
    message() {
      // alert(9)
      this.$router.push("/BusinessAdministrator/alarManagement/AlarmInformation");
    },
    ddd() {
      this.$notify.closeAll();
    },
    closelostar() {
      this.$confirm("此操作将清理所有信息缓存, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          window.localStorage.removeItem("loglevel:webpack-dev-server");
          window.localStorage.removeItem("CUSTOM_SETTINGS");
          //window.localStorage.clear()
          //window.sessionStorage.clear()
          this.$store.dispatch("user/logout");
          this.$message({
            type: "success",
            message: "缓存清理成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消缓存清理",
          });
        });
    },
    userclickd() {
      this.dialogVisible2 = true;
      var info = window.sessionStorage.getItem("Info");
      info = eval("(" + info + ")");
      // var gNamelist=[]
      // for (var i = 0; i < info.role.length; i++) {
      //   gNamelist.push(row.role[i]);
      // }
      //  gNamelist.join();
      this.form.name = info.name;
      this.form.deptName = info.deptName;
      if (info.type == 1) {
        this.form.systype = "省级系统";
      } else {
        this.form.systype = "数据中心";
      }
      this.form.emirl = info.emirl;
      let str = info.loginTime
      let str1=str.split('T')
      //console.log(str1)
      this.form.lofintime = str1[0]+" "+str1[1];
      // let r = ''
      // info.role.forEach((m,index) => {
      //   r+=m+',  '
      // });
      this.form.roles = info.role.join() 
      //this.form.roles =JSON.stringify(info.role);


      if (info.state == 1) {
        this.form.status = "正常";
      }
      this.form.loginName = info.loginName;
    },
    resetForm(formName){
      this.$refs[formName].resetFields();
    },
    closepw(){
      this.$refs.passwordform.resetFields();
      this.dialogVisible1 = false;
    },
    handleResetPassword() {
      this.passwordform.password = "";
      this.passwordform.newPwd = "";
      this.passwordform.confirmPwd = "";
     
      this.pd = "pw";
      this.dialogVisible1 = true;
      var info = window.sessionStorage.getItem("Info");
      info = eval("(" + info + ")");
      this.id = info.id;
     
      this.gongKey();
    },
    submint() {
      this.gonxxKey();
    },
    gonxxKey() {
      gongkey({ loginName: window.sessionStorage.cnloginname }).then((response) => {
          if (response.code === "A0000") {
            var publicKey = response.data;
           // console.log("获取公钥后赋值" + publicKey);
            var sm3Pwd = sm3Digest(this.passwordform.password); //SM3加密
            var jiamipassword = "";
            jiamipassword = sm2(
              sm3Pwd + "|" + this.passwordform.password,
              publicKey,
              0
            ); //SM2公钥加密
            this.password3 = jiamipassword;
          //  console.log("密码加密后hhhhh:" + jiamipassword);
          //  console.log("测试" + this.password3);
            if (this.pd == "del") {
              var password = this.password3;
              this.dialogVisible1 = false;
              passwordConfirm(password).then((response) => {
                if (response.code === "A0000") {
                  this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
                    confirmButtonText: "删除",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(() => {
                      let data = {
                        id: this.id,
                      };
                      deluser(data).then((response) => {
                        this.$message({ type: "success", message: "删除成功" });
                      });
                      this.handleQuery();
                    })
                    .catch(() => {
                      this.$message({
                        type: "info",
                        message: "已取消删除",
                      });
                    });
                }
              });
            }
            if (this.pd === "pw") {
              var password = this.password3;
              this.dialogVisible1 = false;
              passwordConfirm(password).then((response) => {
                if (response.code === "A0000") {
                  // this.$prompt("请输入新密码", "提示", {
                  //   confirmButtonText: "确定",
                  //   cancelButtonText: "取消",
                  // })
                    // .then(({ value }) => {
                      gongkey({loginName: window.sessionStorage.cnloginname}).then((response) => {
                        if (response.code === "A0000") {
                          var publicKey = response.data;
                         // console.log("获取公钥后赋值" + publicKey);
                          var sm3Pwd = sm3Digest(this.passwordform.newPwd); //SM3加密
                          var jiamipassword = "";
                          jiamipassword = sm2( sm3Pwd + "|" + this.passwordform.newPwd, publicKey, 0); //SM2公钥加密
                          let id = window.sessionStorage.getItem("Info").id;
                          let data = {
                            id: this.id,
                            newPassword: jiamipassword,
                          };
                          updatePassword(data).then((response) => {
                            if (response.code === "A0000") {
                              this.$message({
                                type: "success",
                                message: "修改成功",
                              });
                            }
                          });
                        }
                      });
                    // })
                    // .catch(() => {
                    //   this.$message({
                    //     type: "info",
                    //     message: "取消输入",
                    //   });
                    // });
                }
              });
            }
          }
        }
      );
    },
    getnowtime(){
      const now = new Date();
      const year = now.getFullYear();
      const month = ('0' + (now.getMonth() + 1)).slice(-2);
      const day = ('0' + now.getDate()).slice(-2);
      const hours = ('0' + now.getHours()).slice(-2);
      const minutes = ('0' + now.getMinutes()).slice(-2);
      const seconds = ('0' + now.getSeconds()).slice(-2);

      this.nowtime = year +"-"+ month +"-"+ day +":"+ hours +":"+ minutes +":"+ seconds;
    },
    city(){    //定义获取城市方法

      const geolocation = new BMap.Geolocation();

      var _this = this

      geolocation.getCurrentPosition(function getinfo(position){

          let city = position.address.city;             //获取城市信息

          let province = position.address.province;     //获取省份信息

          _this.LocationProvince = province

          _this.LocationCity = city

      }, function(e) {

          _this.LocationCity = "定位失败"

      }, {provider: 'baidu'});

      }


    //   delAllCookie() {
    //   //清空全部cookie
    //   var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    //   if (keys) {
    //     for (var i = keys.length; i--; ) {
    //       document.cookie =
    //         keys[i] + "=0;path=/;expires=" + new Date(0).toUTCString(); //清除当前域名下
    //       document.cookie =
    //         keys[i] +"=0;path=/;domain=" +document.domain +";expires=" +
    //         new Date(0).toUTCString();
    //       document.cookie =
    //         keys[i] +"=0;path=示例：/index.vue（不同域的path,也就是你清除不了的cookie）;domain=示例：10.10.10.208（不同域的domain,也就是你清除不了的cookie）;expires=" +
    //         new Date(0).toUTCString();
    //                           //  **document.cookie可加多条！！！！**
    //     }
    //   }
    // },
  },
};
</script>
<style lang="less" scoped>
@import url("../../styles/comStyle.less");
</style>
<style lang="scss" scoped>
.item {
  margin-top: 0px;
  margin-right: 20px;
}
.right-menu {
  display: flex;
  border-left: 1px solid #d4d4d400 !important;
  //background: red;
  height: 100%;
  &:focus {
    outline: none;
  }

  .right-menu-item {
    display: inline-block;
    height: 100%;
    padding: 0 8px;
    font-size: 18px;
    color: #5a5e66;
    vertical-align: text-bottom;

    &.hover-effect {
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: rgba(0, 0, 0, 0.025);
      }
    }
  }

  .menu-item {
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 10px;
    color: #fff;
    cursor: pointer;
    &:hover {
      background: rgba(0, 0, 0, 0.1);
    }

    .user-avatar {
      width: 30px;
      height: 30px;
      margin-right: 8px;
      border-radius: 10px;
    }

    .el-icon-caret-bottom {
      font-size: 12px;
    }
  }
}
.user-dropdown {
  min-width: 100px;
  // display: flex;
  position: absolute;
  z-index: 9999999999999 !important;
  left: 99%;
}
</style>
<style>
.theme-picker-dropdown .el-color-dropdown__link-btn {
  display: none;
}
.v-modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  /* background: #7a6464; */
}
</style>
