<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="3">
        <a :href="homePage" class="logo-link">
          <img class="container__left-logo" :src="logo" />
        </a>
      </el-col>
      <el-col :span="12" :offset="3">
        <myMenu v-if="$route.path!='/'" />
      </el-col>
      <el-col :span="6">
        <div class="flex container__right">
          <el-badge v-if="msgbadge > 0" :value="msgbadge" :max="100" title="内部消息">
            <i class="msg-link-icon icon-message" @click="linkToMessage()"></i>
          </el-badge>
          <div class="container__right-profile">
            <h3 :title="currentUser.username">你好！{{ currentUser.username }}</h3>
            <span v-if="curOrg.name" :title="curOrg.name">所在部门：{{curOrg.name}}</span>
          </div>
          <el-dropdown @command="handleCommand" trigger="click">
            <span class="container__photo-span">
              <img :src="userPhoto" class="container__photo-img" />
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="info">{{$t('navigator.userInfo')}}</el-dropdown-item>
              <el-dropdown-item command="langSelect">
                <lang-select class="right-menu-item hover-effect" />
              </el-dropdown-item>
              <el-dropdown-item command="switchingPost">
                <el-dropdown @command="switchPost" placement="left-start">
                  <span class="theme-color">切换当前岗位</span>
                  <el-dropdown-menu slot="dropdown" style="margin-right: 30px;">
                    <el-dropdown-item :command="post" :disabled="post.disabled" :key="post.postId"
                      v-for="post in postMap">{{post.postName}}({{post.orgName}})</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-dropdown-item>
              <el-dropdown-item command="modifyPwd">修改密码</el-dropdown-item>
              <el-dropdown-item command="electronicSealManage">签章管理</el-dropdown-item>
              <el-dropdown-item command="logout">退出系统</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
      <el-dialog title="查看个人信息" :visible.sync="infoDialogVisible" :close-on-click-modal="false" top="12vh"
        width="860px">
        <el-form v-if="curUser.user" :inline="true" ref="form" label-width="80px" size="mini">
          <el-form-item label="用户名称">
            <span class="content_span">{{curUser.user.fullname}}</span>
          </el-form-item>
          <el-form-item label="用户账号">
            <span class="content_span">{{curUser.user.account}}</span>
          </el-form-item>
          <el-form-item label="手机号码">
            <span class="content_span">{{curUser.user.mobile}}</span>
          </el-form-item>
          <el-form-item label="邮箱地址">
            <span class="content_span">{{curUser.user.email}}</span>
          </el-form-item>
          <el-form-item label="用户性别">
            <span class="content_span">{{curUser.user.sex}}</span>
          </el-form-item>
          <el-form-item label="用户状态">
            <span
              class="content_span">{{curUser.user.status == '1'?'正常':curUser.user.status == '0'?'禁用':curUser.user.status == '-1'?'未激活':'离职'}}</span>
          </el-form-item>

          <el-form-item label="家庭地址" style="width: 100%;">
            <span class="content_span" style="width: 650px;">{{curUser.user.address}}</span>
          </el-form-item>
          <el-form-item style="width: 100%;" label="所属角色">
            <template v-for="name in curUser.role">
              <el-tag type="warning" size="small" :key="name" v-if="name">{{name}}</el-tag>
            </template>
          </el-form-item>
          <el-form-item style="width: 100%;" label="所属岗位">
            <el-tooltip :content="post.pathName" placement="top" :key="post.postId" v-for="post in curUser.post">
              <el-tag type="success" size="small">{{post.postName}}</el-tag>
            </el-tooltip>
          </el-form-item>
          <el-form-item style="width: 100%;" label="所属组织">
            <el-tooltip :content="org.pathName" placement="top" :key="org.orgId" v-for="org in curUser.org">
              <el-tag size="small">{{org.orgName}}</el-tag>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-dialog title="签章管理" :visible.sync="electronicSealVisible" width="40%" :close-on-click-modal="false">
        <el-form data-vv-scope="electronicSealForm">
          <ht-form-item label="签章">
            <ht-viewer v-model="electronicSeal.fileId" v-if="htViewerDialog" />
          </ht-form-item>
          <ht-form-item label="登录密码">
            <ht-input v-model="electronicSeal.oldPassWord" validate="required" type="password" placeholder="请输入登录密码" />
          </ht-form-item>
          <ht-form-item label="请输入密码">
            <ht-input v-model="electronicSeal.password" type="password" placeholder="请输入密码" />
          </ht-form-item>
          <ht-form-item label="确认密码">
            <ht-input v-model="electronicSeal.confirmPwd" :validate="'confirmed:'+electronicSeal.password"
              type="password" placeholder="确认密码" />
          </ht-form-item>
        </el-form>
        <div class="dialog-footer electronic-style">
          <ht-submit-button :url="ElectronicSealSubmitUrl" :model="electronicSeal" :isSubmit="isSubmit" requestMethod="POST"
            scopeName="editForm" @before-save-data="beforeSaveData" @after-save-data="afterSaveData">{{ $t("eip.common.save") }}</ht-submit-button>
        </div>
      </el-dialog>
      <el-dialog title="修改密码" :visible.sync="modifyPwdDialogVisible" :close-on-click-modal="false" top="20vh"
        width="500px" id="modlfy-dialog" @open="open">
        <el-form :model="pwdForm" :rules="pwdRules" ref="pwdForm" label-width="120px" size="mini">
          <el-form-item label="旧密码" prop="old">
            <el-input type="password" v-model="pwdForm.old" placeholder="请输入旧密码"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="new">
            <el-input type="password" placeholder="请输入新密码" v-model="pwdForm.new"></el-input>
          </el-form-item>
          <el-form-item label="重复新密码" prop="newRepeat">
            <el-input type="password" placeholder="请再次输入新密码" v-model="pwdForm.newRepeat"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button size="small" type="primary" @click="submitForm">确认</el-button>
          <el-button size="small" @click="modifyPwdDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import { mapState } from "vuex";
import myMenu from "@/components/menu.vue";
import langSelect from "@/components/langSelect";
import req from "@/request.js";
import HtViewer from "@/components/common/HtViewer";
import messageReceiver from "@/store/messageReceiverList";
export default {
  name: "navigator",
  data() {
    var validateNew = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      }
      let config = this.pwdStrategy;
      if (config.enable == 1) {
        let pwdRule = config.pwdRule;
        let pwdLength = config.pwdLength;
        if (pwdRule) {
          if (value.length < pwdLength) {
            callback(new Error("新密码长度至少为" + pwdLength));
          } else if (pwdRule == 2) {
            var re = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z])");
            if (!re.test(value)) {
              callback(new Error("新密码必须包含数字、字母"));
            } else {
              callback();
            }
          } else if (pwdRule == 3) {
            var re = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])");
            if (!re.test(value)) {
              callback(new Error("新密码必须包含数字、字母、特殊字符"));
            } else {
              callback();
            }
          } else if (pwdRule == 4) {
            var re = new RegExp(
              "(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9])"
            );
            if (!re.test(value)) {
              callback(new Error("新密码必须包含数字、大小字母、特殊字符"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        }
      } else {
        if (value.length < 6) {
          callback(new Error("新密码长度至少为6"));
        } else {
          callback();
        }
      }
    };
    var validateold = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入旧密码"));
      } else {
        callback();
      }
    };
    var validateNewReapeat = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入新密码"));
      } else if (value !== this.pwdForm.new) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      logo: "",
      showLogo: true,
      infoDialogVisible: false,
      modifyPwdDialogVisible: false,
      electronicSealVisible: false,
      userPhoto: require("@/assets/img/defaultPhoto.jpg"),
      pwdForm: {
        old: "",
        new: "",
        newRepeat: ""
      },
      pwdRules: {
        old: [{ validator: validateold, trigger: "blur" }],
        new: [{ validator: validateNew, trigger: "blur" }],
        newRepeat: [{ validator: validateNewReapeat, trigger: "blur" }]
      },
      count: 0,
      homePage: window.context.front + "/home",
      electronicSeal: {
        fileId: '',
        password: '',
        oldPassWord: '',
        picUrl: ''
      },
      electronicSealFileUrl: "",
      htViewerDialog: false,
      isSubmit: false,
    };
  },
  computed: mapState({
    postMap: state => state.user.postMap || {},
    currentUser: state => {
      return state.login.currentUser ? state.login.currentUser : {};
    },
    curUser: state => state.user.currentUserDetail || {},
    curOrg: state => state.user.currentOrgDetail || {},
    pwdStrategy: state => state.user.pwdStrategy || {},
    ElectronicSealSubmitUrl: function () {
      return window.context.uc + "/uc/electronicSeal/v1/userSave";
    },
    msgbadge: state => state.messageReceiver.msgbadge || 0,
  }),
  mounted() {
    const _this = this;
    const currentUser = this.$store.state.login.currentUser;
    if (currentUser) {
      let userAttrs = this.$store.state.login.currentUser.userAttrs;
      if (userAttrs) {
        let tenantId = userAttrs.tenantId;
        //租户
        if (tenantId && tenantId != "null") {
          let url = window.context.uc + "/uc/tenantManage/v1/getJson?id=" + tenantId;
          this.$http.get(url).then(resp => {
            if (resp.data) {
              let tenantManage = resp.data;
              if (tenantManage.frontLogo) {
                let frontLogo = JSON.parse(tenantManage.frontLogo);
                if (frontLogo && frontLogo.length > 0) {
                  _this.showLogo = true;
                  req.get(window.context.portal + "/file/onlinePreviewController/v1/getFileById_" + frontLogo[0].id, 'arraybuffer').then(response => {
                    let type = response.headers['content-type'];
                    if (type) {
                      _this.logo = window.URL.createObjectURL(new Blob([response.data], { type: type }));
                    } else {
                      _this.logo = window.URL.createObjectURL(new Blob([response.data]));
                    }
                  });
                  // _this.logo = window.context.portal + "/system/file/v1/downloadFile?fileId=" + frontLogo[0].id;
                }
              } else {
                _this.showLogo = false;
                this.logo = require("@/assets/img/logo.svg");
              }
            }
          }, error => {
            _this.showLogo = false;
            this.logo = require("@/assets/img/logo.svg");
            reject(error);
          })
        } else {
          //不是租户
          this.logo = require("@/assets/img/logo.svg");
          _this.sysSetting();
        }
      } else {
        //不是租户
        this.logo = require("@/assets/img/logo.svg");
        _this.sysSetting();
      }
    } else {
      //不是租户
      this.logo = require("@/assets/img/logo.svg");
      _this.sysSetting();
    }
    setTimeout(() => {
      this.$route.path !== "/" &&
        this.$store.dispatch("user/loadCurrentUserDetail").then(data => {
          if (data) {
            var promise = this.$store.dispatch("user/getCurrent");
            promise.then(data => {
              if (data.photo && data.photo.indexOf("img/defaultPhoto") < 0) {
                this.$store
                  .dispatch("menu/downloadImg", data.photo)
                  .then(res => {
                    if (res != "") {
                      this.userPhoto = res;
                    }
                  });
              }
            });
          }
        });
    }, 1200);

    this.$store.dispatch("messageReceiver/setMsgbadge");
  },
  watch: {
    //第一次加载著部门，当前切换岗位部门时当前部门发生改变
    "$store.state.user.postCharge": function () {
      const postCharge = this.$store.state.user.postCharge;
      this.count += 1;
      if (postCharge.org && this.count > 1) {
        this.$store.dispatch("user/setcurrentOrg", postCharge.org);
      }
    }
  },
  methods: {
    //获取系统默认配置 系统Logo、名称
    sysSetting() {
      const _this = this;
      let url = window.context.portal + "/sys/sysProperties/v1/getDecryptBySysSetting";
      _this.$http.get(url).then(response => {
        if (response && response.data && response.data.value) {
          let sysSettingData = JSON.parse(response.data.value);
          if (sysSettingData.frontLogo.length > 0) {
            let frontLogo = sysSettingData.frontLogo;
            _this.showLogo = true;
            req.get(window.context.portal + "/file/onlinePreviewController/v1/getFileById_" + frontLogo[0].id, 'arraybuffer').then(response => {
              let type = response.headers['content-type'];
              if (type) {
                _this.logo = window.URL.createObjectURL(new Blob([response.data], { type: type }));
              } else {
                _this.logo = window.URL.createObjectURL(new Blob([response.data]));
              }
            });
          } else {
            this.logo = require("@/assets/img/logo.svg");
          }
        } else {
          this.logo = require("@/assets/img/logo.svg");
        }
      });
    },
    open() {
      this.$store.dispatch("user/getDefPwdStrategy");
    },
    handleCommand(command) {
      switch (command) {
        case "logout":
          //退出登陆时把vuex 里面的一些值清空
          this.$store.dispatch("menu/setCopyMenus", []);//菜单
          let loginRouthPath =
            localStorage.getItem(
              this.$store.state.login.currentUser.account + "loginRoutePath"
            ) || "/login";
          this.$store.dispatch("login/logoutAndCleanUp").then(() => {
            switch (window.ssoConfig.mode) {
              case "cas":
              case "oauth":
                window.sessionStorage.removeItem("currentUser");
                window.location.href =
                  window.ssoConfig.logout +
                  "?service=" +
                  window.location.href.split("?")[0];
                break;
              default:
                this.$router.push({
                  path: loginRouthPath
                });
                break;
            }
          });
          break;
        case "info":
          this.infoDialogVisible = true;
          break;
        case "electronicSealManage":
          // 签章管理
          // 获取当前登录用户的签章图片
          req.get(window.context.uc + '/uc/electronicSeal/v1/getSealByCurrentUserId').then(response => {
            if (response.data) {
              this.electronicSeal = response.data;
              this.$store
                .dispatch("menu/downloadImg", this.electronicSeal.fileId)
                .then(res => {
                  if (res != "") {
                    this.electronicSealFileUrl = res;
                  }
                });
            }
          }).then(() => {
            this.htViewerDialog = false;
            this.$nextTick(() => {
              this.htViewerDialog = true;
              this.electronicSealVisible = true;
            })
          });
          break;
        case "modifyPwd":
          this.modifyPwdDialogVisible = true;
          if (this.$refs["pwdForm"]) {
            this.$refs["pwdForm"].resetFields();
          }
          break;
      }
    },
    submitForm() {
      let this_ = this;
      this.$refs["pwdForm"].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("user/modifyPwd", {
              oldPwd: this.pwdForm.old,
              newPwd: this.pwdForm.new
            })
            .then(data => {
              if (data.state) {
                this.modifyPwdDialogVisible = false;
                this.$alert('修改密码成功, 请使用新密码重新登录。', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    //退出登录
                    this_.handleCommand('logout');
                  }
                });
              } else {
                this.$message.error(data.message || "保存失败");
              }
            });
        }
      });
    },
    switchPost(item) {
      for (let obj in this.postMap) {
        this.postMap[obj].disabled = false;
      }
      item.disabled = true;
      //设置表单中当前岗位
      this.$store.dispatch("user/setpostMap", {
        postMap: this.postMap,
        postCharge: item
      });
      this.$message.success("切换当前岗位成功");
      this.infoDialogVisible = true;
      this.infoDialogVisible = false;
    },
    beforeSaveData(){
      this.isSubmit = true;
      if(!this.electronicSeal.oldPassWord){
        this.$message.warning("请输入登录密码！");
        this.isSubmit = false;
        return ;
      }
      if(!this.electronicSeal.password){
        this.$message.warning("请输入密码！");
        this.isSubmit = false;
        return ;
      }
      if(!this.electronicSeal.confirmPwd){
         this.$message.warning("请输入确认密码！");
         this.isSubmit = false;
         return ;
      }
      if(this.electronicSeal.password != this.electronicSeal.confirmPwd){
         this.$message.warning("密码与确认密码不一致！");
         this.isSubmit = false;
         return ;
      }
    },
    afterSaveData() {
      // 签章添加完成后的操作
      this.electronicSealVisible = false;
    },
    linkToMessage() {
      this.$router.push({ path: '/v-personal/v-messageReceiver' });
    }
  },
  components: {
    HtViewer,
    myMenu,
    langSelect
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables.scss";

.container {
  margin: 0 auto;
  height: 100%;
  overflow: hidden;

  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
    }
  }

  .container__left-logo {
    height: calc(100% - 5px);
    margin-left: 30px;
  }

  .container__right {
    justify-content: space-around;
    align-items: center;
    float: right;
    height: 100%;
    width: 280px;

    .el-badge {
      margin-right: 30px;
    }

    .el-dropdown {
      height: 100%;
    }

    .container__photo-span {
      padding-right: 20px;
    }

    .container__photo-img {
      width: 35px;
      height: 35px;
      border-radius: 50%;
    }

    .container__photo-img + i {
      position: absolute;
      top: 20px;
      right: 0px;
    }
  }

  .msg-link-icon {
    font-size: 20px;
    cursor: pointer;
    color: white;
  }

  .container__right-profile {
    min-width: 90px;
    max-width: 150px;

    h3 {
      margin: 5px 0;
      color: $--color-white;
      white-space: nowrap;
      display: inline-block;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    span {
      color: $--color-white;
      white-space: nowrap;
      display: inline-block;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.theme-color {
  color: $--color-text-regular;
}

.el-row {
  margin: 0 -20px;
}

img {
  margin-top: 5px;
}

div.el-dropdown,
div.el-dropdown + span {
  color: #fff;
  line-height: 48px;
  font-size: 13px;
}

.logo-link {
  color: #fff;
  text-decoration: none;
  font-size: 24px;
  font-weight: 400;
  line-height: 48px;
}

.el-form /deep/ .el-form-item__content > .el-tag {
  margin-right: 10px;
}

.content_span {
  color: #212121;
  border-bottom: 1px solid #ededed;
  width: 260px;
  display: inline-block;
  margin: 0 30px 0 10px;
}

#modlfy-dialog /deep/ .el-input__inner {
  width: 200px;
}
.electronic-style {
  margin-left: 100px;
}
.msg-link-icon {
  font-size: 18px;
  font-weight: bold;
  cursor:pointer;
  color:white;
}
.msg-link-badge {
  margin: 15px 25px;
}
.msg-link-badge /deep/ .el-badge__content{
  height: 14px;
  line-height: 14px;
}
</style>


