<template>
  <div class="cy-person">
    <el-dropdown>
      <div class="menu-userinfo">
        <el-avatar shape="square" size="small" @error="errorHandler">
          <img :src="avatarDefault"/>
        </el-avatar>
        <span>{{ name }}</span>
      </div>
      <el-dropdown-menu slot="dropdown">
        <!--          <el-dropdown-item>详细信息</el-dropdown-item>-->
        <el-dropdown-item @click.native="reloadPage">首页</el-dropdown-item>
        <el-dropdown-item v-if="roleCodeList.indexOf(__self.clientRole) > -1" @click.native="getWarnInfo">报警信息</el-dropdown-item>
        <el-dropdown-item @click.native="updateUserPwd">修改密码</el-dropdown-item>
        <el-dropdown-item @click.native="checkApplicationUpdate">关于我们</el-dropdown-item>
        <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <!-- 用户密码修改 -->
    <el-dialog
        title="修改密码"
        width="500px"
        center
        v-dialog-drag
        v-if="dialogPwdVisible"
        :before-close="dialogClose"
        :visible.sync="dialogPwdVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <div>
        <el-form ref="userPwdForm" :model='userPwdForm' :rules="userPwdRules" label-width='100px'>
          <el-form-item label='原密码' prop="password">
            <el-input v-model.trim='userPwdForm.password'
                      type="password"
                      auto-complete="off"
                      placeholder="请输入原密码"></el-input>
          </el-form-item>
          <el-form-item label='新密码' prop="newPassword">
            <el-input v-model.trim='userPwdForm.newPassword'
                      type="password"
                      auto-complete="off"
                      placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label='确认密码' prop="confirmPassword">
            <el-input v-model.trim='userPwdForm.confirmPassword'
                      type="password"
                      auto-complete="off"
                      placeholder="请再次输入新密码"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center; margin-top: 40px;">
        <el-button type="primary" @click="updateUserPwdEvent">确定</el-button>
        <el-button @click="dialogClose">取消</el-button>
      </div>
    </el-dialog>

    <!-- 关于我们 -->
    <el-dialog
        title=""
        width="300px"
        center
        v-dialog-drag
        v-if="dialogAboutVisible"
        :before-close="dialogClose"
        :visible.sync="dialogAboutVisible"
        :close-on-click-modal="true"
        :append-to-body="true">
      <div style="text-align: center;">
        <div>
          <el-image :src="require('@/assets/images/logo.png')" fit="contain" class="c-logo"></el-image>
        </div>
        <div>
          <span style="font-size: 18px; font-weight: bold; font-family: '微软雅黑';">重庆川仪控制系统有限公司</span>
        </div>
        <div style="margin-top: 50px;">当前版本：{{ appVersion }}</div>
      </div>
    </el-dialog>

    <!-- 报警信息 -->
    <el-dialog
        title="报警信息"
        width="80vw"
        class="cy-warn-dialog"
        center
        v-dialog-drag
        v-if="dialogNoticeVisible"
        :before-close="dialogClose"
        :visible.sync="dialogNoticeVisible"
        :close-on-click-modal="true"
        :append-to-body="true">
      <el-table
          :data="tableNoticeData" border :stripe="true"
          @sort-change="sortChange"
          :header-cell-style="{background: '#E8E8E8'}"
          style="width: 100%; height: calc(100% - 50px); overflow: auto;">
        <el-table-column label="序号" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column align="center" sortable="custom" label="标题" prop="noticeTitle" width="350">
        </el-table-column>
        <el-table-column align="center" label="报警内容" prop="noticeContent">
        </el-table-column>
        <el-table-column align="center" sortable label="报警时间" prop="createTime" width="200">
        </el-table-column>
      </el-table>
      <el-pagination
          style="margin-top: 20px;"
          background
          layout="prev, pager, next, total"
          :current-page="tablePage"
          @size-change="sizeChangeEvent"
          @current-change="currentChangeEvent"
          :total="tableTotal">
      </el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import avatarDefault from '@/assets/images/default.png'
import {mapGetters} from 'vuex'
import {updatePwd} from '@/api/user'
import {getPubKey} from '@/utils/auth'
import {encrypt} from '@/utils/jsencrypt'
import {customCompare, showAlertWin, showLoading} from '@/utils/cqcy'
import {getAllMessageNotice} from "@/api/basic";

let pkg = require('../../../package.json')

export default {
  name: "HeaderPersonal",
  data() {
    let checkPwd = ((rule, value, callback) => {
      if (value.trim().length == 0) {
        callback(new Error("请输入确认密码"))
      } else if (value != this.userPwdForm.newPassword) {
        callback(new Error("两次密码不一致"))
      } else {
        callback()
      }
    })

    return {
      roleCodeList: [],
      avatarDefault: avatarDefault,
      dialogPwdVisible: false,
      dialogAboutVisible: false,
      dialogNoticeVisible: false,
      appVersion: '',
      tableNoticeData: [],
      tablePage: 1,
      tableLimit: 10,
      tableTotal: 0,
      userPwdForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      userPwdRules: {
        password: [
          {required: true, message: '原密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '原密码长度必须介于 6 和 20 之间', trigger: 'blur'}
        ],
        newPassword: [
          {required: true, message: '新密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '新密码长度必须介于 6 和 20 之间', trigger: 'blur'},
          {
            pattern: /(?!^\d+$)(?!^[A-Za-z]+$)(?!^[^A-Za-z0-9]+$)(?!^.*[\u4E00-\u9FA5].*$)^\S{6,20}$/,
            message: '密码必须由数字、字母或字符任意两种组合',
            trigger: 'blur'
          },
        ],
        confirmPassword: [
          {required: true, message: '确认密码不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '新密码长度必须介于 6 和 20 之间', trigger: 'blur'},
          {validator: checkPwd, required: true, trigger: 'blur'}
        ]
      }
    }
  },
  inject: ['__self'],
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'name',
      'uid',
      'device',
      'roles'
    ])
  },
  mounted() {
    this.roleCodeList = []
    this.roles.forEach((role) => {
      this.roleCodeList.push(role.roleCode)
    })
  },
  methods: {
    sortChange({ prop, order }) {
      this.tableNoticeData.sort(customCompare(prop, order))
    },
    errorHandler() {
      return true
    },
    /**
     * 修改密码
     */
    updateUserPwd() {
      if (this.$refs['userPwdForm'])
        this.$refs['userPwdForm'].resetFields()
      this.dialogPwdVisible = true
    },
    checkApplicationUpdate() {
      this.appVersion = 'V' + pkg.version
      this.dialogAboutVisible = true
    },
    reloadPage() {
      this.$router.push({path: '/', query: {}})
      // window.location.reload()
      this.$router.go(0)
    },
    updateUserPwdEvent() {
      this.$refs['userPwdForm'].validate(valid => {
        if (valid) {
          const loading = showLoading(this, '修改中，请稍候···')
          let pubKey = getPubKey()
          let data = {
            'password': encrypt(this.userPwdForm.password, pubKey),
            'newPassword': encrypt(this.userPwdForm.newPassword, pubKey),
            'userName': this.name,
            'userId': this.uid
          }
          if (this.userPwdForm.password == this.userPwdForm.newPassword) {
            loading.close()
            this.$message({
              message: '修改失败，新密码与原密码不能相同！',
              type: 'error'
            })
            return
          }
          updatePwd(data).then(res => {
            loading.close()
            if (res.code != 200) {
              this.$message({
                message: res.msg,
                type: 'error'
              })
              return
            }
            this.$message({
              message: '密码修改成功！',
              type: 'success'
            })
            this.$store.dispatch('user/Logout').then(() => {
              // location.href = '/index';
              this.$router.push({path: '/', query: {}})
              window.location.reload()
            }).catch(() => {
            })
            this.dialogClose()
          }).catch((e) => {
            loading.close()
            showAlertWin(this, e)
          })
        }
      })
    },
    /** 数据条数改变 */
    sizeChangeEvent(val) {
      this.tablePage = 1
      this.tableLimit = val
      this.getWarnInfo()
    },
    /** 页码改变 */
    currentChangeEvent(val) {
      this.tablePage = val
      this.getWarnInfo()
    },
    /** 获取报警信息 */
    getWarnInfo() {
      const loading = showLoading(this, '加载中，请稍候···')
      let params = {
        'page': this.tablePage,
        'limit': this.tableLimit,
      }
      getAllMessageNotice(params).then(res => {
        loading.close()
        if (!res || !res.data) {
          return
        }
        this.dialogNoticeVisible = true
        this.tableTotal = res.data.count
        this.tableNoticeData = res.data.messageNoticeList
      }).catch((e) => {
        loading.close()
        showAlertWin(this, e)
      })
    },
    /**
     * 退出登录
     */
    logout() {
      this.$confirm('您确定要退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'close_confirm',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('user/Logout').then(() => {
          // location.href = '/index';
          this.$router.push({path: '/', query: {}})
          window.location.reload()
        }).catch(() => {
        })
      }).catch(() => {
      });
    },
    /** 弹出层关闭事件 */
    dialogClose(done) {
      if (this.$refs['userPwdForm'])
        this.$refs['userPwdForm'].resetFields()
      if (typeof (done) === 'function') {
        done()
      } else {
        this.dialogPwdVisible = false
        this.dialogAboutVisible = false
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.cy-person {
  background-color: #2c3e50;
  height: 70px;
  width: 100%;
  padding-right: 20px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-end;
  align-items: center;
}

.menu-userinfo {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;

  i {
    color: white;
  }
}

.el-avatar {
  margin-right: 5px;
}

.cy-warn-dialog {
  .el-dialog {
    height: 70vh;

    .el-dialog__body {
      height: calc(100% - 60px);
    }
  }
}
</style>