<template>
  <div class="L_userBox">
    <!-- <div class="lf mh">
      <a href="http://lswz:88/web/portal/#/dashboard">返回门户</a>
    </div>-->
    <div class="rg">
      <div class="logo-on">
        <!-- <span class="welText">欢迎</span> -->
        <el-dropdown trigger="click">
          <!-- <img v-if="photoId" :src="imgSrc+'?id='+photoId" class="userUploadImg">
          <img v-else src="../../../assets/index_images/userImg.png" class="userUploadImg">-->
          <span :title="currentName" class="el-dropdown-link">
            {{currentName}}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <a @click="handleUpdate">
              <el-dropdown-item>基本资料</el-dropdown-item>
            </a>
            <a @click="modifyPwd">
              <el-dropdown-item>修改密码</el-dropdown-item>
            </a>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <a
          v-if="managerMark !== -1"
          href="http://lswz:88/web/systemcenter"
          title="系统管理"
          target="_blank"
          class="systemIcon"
        >
          <i class="el-icon-setting"></i>
        </a> -->
        <a @click="znxFun" class="systemIcon">
          <el-badge :is-dot="dotStatus" class="dotStyle">
            <i class="iconfont iconxinfeng" title="站内信"></i>
          </el-badge>
        </a>
        <a @click="dbClick" class="systemIcon">
          <el-badge :is-dot="dbWaitCount" class="dotStyle_1">
            <i class="iconfont icondaiban" title="待办事项"></i>
          </el-badge>
        </a>
        <a @click="logout" class="systemIcon">
          <!-- <el-badge> -->
          <i class="iconfont icontuichu" title="注销"></i>
          <!-- </el-badge> -->
        </a>
        <!-- <span class="outText iconfont icon-tuichu" @click="logout" title="注销"></span> -->
      </div>
    </div>

    <!--站内信-->
    <el-dialog
      title="站内信息"
      :visible.sync="znxDialogVisible"
      width="80%"
      :close-on-click-modal="false"
      class="znxTitle"
      @open="openDialog"
    >
      <i class="iconfont iconyingyong"></i>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-menu
            :default-active="znxSf"
            class="el-menu-vertical-demo"
            @select="handleSelect"
            @open="handleOpen"
            @close="handleClose"
            style="height:440px;"
          >
            <el-menu-item index="1">
              <i class="el-icon-message"></i>
              <span slot="title">收信</span>
            </el-menu-item>
            <el-menu-item index="2">
              <i class="el-icon-message"></i>
              <span slot="title">发信</span>
            </el-menu-item>
          </el-menu>
        </el-col>
        <el-col :span="20">
          <div v-if="znxSf === '1'">
            <receiveLetters ref="recieveComp"></receiveLetters>
          </div>
          <div v-if="znxSf === '2'">
            <sendALetter></sendALetter>
          </div>
        </el-col>
      </el-row>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="znxDialogVisible = false" class="outCancelButton">取 消</el-button>
      </span>-->
    </el-dialog>

    <!--基本资料弹窗-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      class="basicData"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="form" status-icon :rules="rules" ref="form" label-width="120px">
        <el-form-item label="账号" prop="userAccount" style="width: 90%;">
          <el-input v-model="form.userAccount" placeholder="请输入账号" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName" style="width: 90%;">
          <el-input v-model="form.userName" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" style="width: 90%;" class="roleSelect">
          <el-select class="filter-item" multiple value-key="id" disabled v-model="form.roleNames"></el-select>
        </el-form-item>
        <el-form-item label="职位名称" style="width: 90%;">
          <el-input type="text" v-model="form.jobTitle" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" style="width: 90%;">
          <el-input type="text" v-model="form.deptName" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          placeholder="请输入邮箱"
          prop="email"
          style="width: 90%;"
          :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']}]"
        >
          <el-input type="email" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" placeholder="请输入手机号" prop="userMobile" style="width: 90%;">
          <el-input type="text" v-model="form.userMobile"></el-input>
        </el-form-item>
        <!-- <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            style="text-align: left;"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="onError"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.userPhoto" :src="imgSrc+'?id='+form.userPhoto" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="update('form')" class="outCancelButton">保 存</el-button>
        <el-button type="primary" @click="cancel('form')" class="outCancelButton">取 消</el-button>
      </div>
    </el-dialog>

    <!--修改密码弹窗-->
    <el-dialog
      title="修改密码"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
      :close-on-click-modal="false"
    >
      <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" label-width="68px" status-icon>
        <el-form-item label="旧的密码" prop="oldPassword">
          <el-input type="password" v-model="ruleForm2.oldPassword" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="新的密码" prop="newPassword">
          <el-input type="password" v-model="ruleForm2.newPassword" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm2')" class="outCancelButton">保存</el-button>
        <el-button type="primary" @click="resetForm('ruleForm2')" class="outCancelButton">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { file, fileDownload } from "@/api/index";
import sendALetter from "./zhanneixing/sendALetter";
import receiveLetters from "./zhanneixing/receiveLetters";

import {
  getById,
  updataPassword,
  putObj,
  unreadMessage,
  reqWaitCount
} from "@/api/headerUser";
export default {
  name: "HeaderBox",
  components: {
    receiveLetters,
    sendALetter
  },
  data() {
    let Base64 = require('js-base64').Base64;
    var checkOldPwd = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请输入旧密码"));
      } else {
        let oldPasswd= Base64.decode(JSON.parse(sessionStorage.getItem("LoginCode")).password) 
        if (value!=oldPasswd) {
          return callback(new Error("旧密码输入错误"));
        } else {
            callback();
        }
      }
    };
    var validatePass = (rule, value, callback) => {
      let reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,20}$/;
      
      if (!value && value != 0) {
        callback(new Error("请输入新密码"));
      } else if (!reg.test(value)) {
        callback(new Error("密码由字母,数字,特殊字符组成,长度在8~20位"));
      } else {
        // if (this.ruleForm2.checkPass !== "") {
        //   this.$refs.ruleForm2.validateField("checkPass");
        // }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请输入确认密码"));
      }else if (value !== this.ruleForm2.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      znxSf: "1",
      dbWaitCount: false,
      znxDialogVisible: false,
      infoType: "edit",
      photoId: "",
      imgSrc: `${fileDownload}`,
      managerMark: "",
      currentName: "",
      GetUserId: null,
      dialogFormVisible: false,
      form: {
        userAccount: "", //用户账号
        userName: "", //姓名
        roleNames: [], // 角色名称
        deptName: "", // 部门名称
        jobTitle: "", // 职位名称
        // sex: '',
        email: "",
        userMobile: "",
        id: "",
        userPhoto: "" //图片id
      },
      rules: {
        jobTitle: [
          {
            required: true,
            trigger: "blur"
          }
        ],
        deptName: [
          {
            required: true,
            trigger: "blur"
          }
        ],
        userAccount: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur"
          }
        ],
        userName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur"
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur"
          }
        ],
        userMobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            min: 11,
            max: 11,
            message: "长度在 11 个字符",
            trigger: "blur"
          }
        ]
      },
      centerDialogVisible: false,
      ruleForm2: {
        userId: null,
        oldPassword: null,
        newPassword: null,
        checkPass: null
      },
      rules2: {
        newPassword: [
          {
            validator: validatePass,
            trigger: "blur"
          }
        ],
        checkPass: [
          {
            validator: validatePass2,
            trigger: "blur"
          }
        ],
        oldPassword: [
          {
            validator: checkOldPwd,
            trigger: "blur"
          }
        ]
      },
      dotStatus: false, //信封红点状态
      textMap: {
        update: "基本资料",
        create: "创建"
      },
      dialogStatus: "",
      uploadUrl: `${file}`
    };
  },
  methods: {
    openDialog() {
      this.znxSf = "1";
      if (this.$refs["recieveComp"]) {
        this.$refs["recieveComp"].fGoBack();
      }
    },
    dbClick() {
      sessionStorage.setItem("dbFlag", "true");
      window.location.href = "/web/portal/#/dashboard";
      // http://lswz:88
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath);
    },
    handleSelect(key, keyPath) {
      this.znxSf = key;
      console.log(key, keyPath);
    },
    znxFun() {
      // this.znxDialogVisible = true;
      sessionStorage.setItem("znxFlag", "true");
      window.location.href = "/web/portal/#/dashboard";
      // http://lswz:88
    },
    welcome() {
      getById(this.GetUserId).then(response => {
        console.log("我是", response);
        if (response.infoCode == 200) {
          if (this.dialogFormVisible) {
            this.form = response.data;
          } else {
            localStorage.setItem("userName", response.data.userName);
            this.currentName = response.data.userName; // 用户真实姓名
            this.managerMark = response.data.admType; //判断是不是系统管理员(-1为非管理员)
            this.photoId = response.data.userPhoto;
          }
        } else {
          this.$message({
            type: "error",
            message: response.msg
          });
        }
        // console.log('判断是不是管理员',this.managerMark,Boolean(this.managerMark === -1))
      });
    },
    // 点击基本资料
    handleUpdate() {
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
      this.welcome();
    },
    // 基本资料弹框中==确定修改
    update(formName) {
      const set = this.$refs;
      set[formName].validate(valid => {
        this.isPoneAvailable(this.form.userMobile); // 验证有效手机号
        // console.log(this.poneAvailable);
        // console.log(this.form.roleNames);
        if (valid && this.poneAvailable) {
          putObj(this.form, this.infoType).then(res => {
            this.dialogFormVisible = false;
            this.$message({
              title: "成功",
              message: res.msg,
              type: "success",
              duration: 2000
            });
            this.welcome();
          });
        } else {
          return false;
        }
      });
    },
    // 验证有效手机号
    isPoneAvailable(phoneNum) {
      const myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!myreg.test(phoneNum)) {
        this.$notify({
          title: "警告",
          message: "无效手机号",
          type: "warning",
          duration: 2000
        });
        this.poneAvailable = false;
      } else {
        this.poneAvailable = true;
      }
    },
    modifyPwd() {
      this.centerDialogVisible = true;
      this.ruleForm2 = {
        oldPassword: null,
        newPassword: null,
        checkPass: null
      };
    },
    unreadNum() {
      //未读消息数量
      unreadMessage().then(res => {
        if (res.infoCode == 200) {
          if (!res.data) {
            this.dotStatus = false;
          } else {
            this.dotStatus = true;
          }
          console.log(this.dotStatus);
        } else {
          this.$message({
            type: "error",
            message: res.msg
          });
        }
      });
      reqWaitCount().then(res => {
        console.log(res);
        if (res.infoCode == 200) {
          if (res.data == 0) {
            this.dbWaitCount = false;
          } else {
            this.dbWaitCount = true;
          }
        }
      });
    },
    logout() {
      this.$store.dispatch("LogOut").then(() => {
        // location.reload(); // 为了重新实例化vue-router对象 避免bug
        window.location.href = "/web/portal/#/login";
        // http://lswz:88
      });
    },
    handleAvatarSuccess(res, file) {
      //上传成功时
      if (res.infoCode == 200) {
        this.$message({
          message: "上传成功",
          type: "success"
        });
        this.form.userPhoto = res.data.id;
        console.log("sdfsf", this.form.userPhoto);
        //this.imageUrl = URL.createObjectURL(file.raw);
      } else {
        this.$message({
          message: `${res.msg}`,
          type: "error"
        });
      }
    },
    onError(err, file, fileList) {
      //上传失败
      this.$message({
        message: "上传失败",
        type: "error"
      });
    },
    beforeAvatarUpload(file) {
      // 限制用户上传的图片格式和大小。
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、JPEG或者PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 修改密码
    submitForm(formName) {
      const data = {
        id: this.GetUserId,
        oldPasswd: this.ruleForm2.oldPassword,
        newPasswd1: this.ruleForm2.newPassword,
        newPasswd2: this.ruleForm2.checkPass
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          updataPassword(1, data)
            .then(response => {
              if (response.infoCode == 200) {
                this.$message({
                  type: "success",
                  message: response.msg
                });
                this.centerDialogVisible = false;
              } else {
                this.$message({
                  type: "error",
                  message: response.msg
                });
              }
              console.log(response);
            })
            .catch(err => {
              // alert(err)
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 清空form表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.centerDialogVisible = false;
    }
  },
  created() {
    this.GetUserId = localStorage.getItem("idportal");
    this.welcome();
    this.unreadNum();
  }
};
</script>
<style lang="scss">
.L_userBox .lf {
  float: left;
}
.L_userBox .rg {
  float: right;
  height: 100%;
}
.L_userBox {
  height: 100%;
  width: 100%;
  line-height: 38px;
  font-size: 13px;
  .mh {
    font-weight: bold;
    color: white;
  }
  .userUploadImg {
    // margin-top: -35px;
    vertical-align: middle;
    cursor: pointer;
    height: 25px;
    width: 25px;
    border-radius: 50%;
  }
  .userUploadImg_1 {
    margin-top: -35px;
    vertical-align: middle;
    cursor: pointer;
    height: 25px;
    width: 25px;
    border-radius: 50%;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .greet {
    display: inline-block;
    max-width: 70px;
    margin-right: 5px;
    font-weight: 400;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: default;
  }
  .systemIcon {
    vertical-align: top;
    display: inline-block;
  }
  .el-badge {
    position: relative;
    vertical-align: middle;
    display: inline-block;
  }
  .dotStyle .el-badge__content.is-dot {
    height: 6px;
    width: 6px;
  }
  .dotStyle_1 .el-badge__content.is-dot {
    height: 6px;
    width: 6px;
  }
  .dotStyle .el-badge__content.is-fixed.is-dot {
    right: 7px;
    top: 15px;
  }
  .dotStyle_1 .el-badge__content.is-fixed.is-dot {
    right: 5px;
    top: 14px;
  }

  .icon-xinfeng {
    font-size: 20px;
  }
  .roleSelect .el-select {
    width: 100%;
  }
  .znxTitle .el-dialog__title {
    left: 35px;
  }
  .icon-yingyong {
    position: absolute;
    top: 9px;
    left: 10px;
    color: #fff;
  }
  .dialog-footer {
    text-align: center;
  }
  .logo-on {
    width: auto;
    height: 100%;
    color: #f3f3f3;
    font-size: 14px;
    border-radius: 15px;
    padding-left: 5px;
    padding-right: 10px;
    line-height: 42px;
    .el-dropdown-link {
      cursor: pointer;
    }
    .el-icon-arrow-down {
      font-size: 10px;
    }
    .el-icon--right {
      margin-left: 1px;
    }
    .el-dropdown {
      height: 100%;
      color: #f3f3f3;
    }
    .welText,
    .systemIcon,
    .outText {
      vertical-align: top;
      display: inline-block;
    }
    .welText {
      margin-right: 5px;
      cursor: default;
    }
    .systemIcon:last-child {
      margin-right: 5px;
    }
    .outText {
      cursor: pointer;
    }
  }
  .logo-on span:nth-child(1) {
    margin-right: 5px;
  }
  //保存、取消等按钮
  .outCancelButton {
    padding: 7.2px 20px;
    background: #3fa9b5;
    border-color: #3fa9b5;
    margin-bottom: 10px;
  }
  .outCancelButton.el-button--primary:focus,
  .outCancelButton.el-button--primary:hover {
    background-color: #038794;
    border-color: #038794;
  }
  .outCancelButton.el-button--primary.is-disabled,
  .outCancelButton.el-button--primary.is-disabled:active,
  .outCancelButton.el-button--primary.is-disabled:focus,
  .outCancelButton.el-button--primary.is-disabled:hover {
    background-color: #aed6da;
    border-color: #aed6da;
  }
  // 站内信弹窗框的侧边栏样式-开始
  .el-menu-item {
    color: #303133 !important;
  }
  .el-menu-item i {
    color: #909399 !important;
  }
  .el-menu-item.is-active {
    color: #409eff !important;
  }
  .el-menu-item.is-active i {
    color: inherit !important;
  }
  .el-menu-item:focus,
  .el-menu-item:hover {
    outline: 0 !important;
    background-color: #ecf5ff !important;
  }
  .el-menu-item.is-active {
    outline: 0 !important;
    background-color: #ecf5ff !important;
  }
  // 站内信弹窗框的侧边栏样式-结束
}
</style>

