<template>
  <div class="header">
    <div style="line-height: 60px">
      <img v-if="Setting.isSq" class="logo" style="max-height: 100%" src="/images/1.png" alt="">
      <img v-else class="logo" :src="logoUrl" />
      <span class="title">{{ title }}</span>
    </div>
    <div class="action">
      <el-popover placement="top" :disabled="!notices.length">
        <p v-for="(item, i) in notices" :key="i" class="p-v-5 cursor-pointer" @click="toComment(item)">{{
          item.commentUsername }} 回复了你的评论</p>
        <el-badge class="msg" :is-dot="!!notices.length" slot="reference">消息</el-badge>
      </el-popover>
      <el-dropdown class="user-wrap" @command="userCommand">
        <div class="user">
          <el-avatar :size="40" :src="avatar"></el-avatar>
          <span class="m-l-10">{{ customerName || userName }}</span>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-if="!customerName" command="person">个人中心</el-dropdown-item>
          <el-dropdown-item v-else command="resetPw">修改密码</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-divider direction="vertical"></el-divider>
      <el-button type="text" class="ml20" @click="logout">退出</el-button>
    </div>
    <el-dialog title="修改密码" :visible.sync="passwordVisible" :close-on-click-modal="false" :append-to-body="true"
      @close="resetPassword" width="30%">
      <el-form ref="passwordForm" label-width="82px">
        <el-form-item label="原密码">
          <el-input type="password" v-model="passwordForm.password" placeholder="请输入原密码"></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input type="password" v-model="passwordForm.reNewPassword" placeholder="请确认新密码"
            @keyup.enter.native="submitPassword"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations, mapActions } from "vuex";
import util from "@/libs/util";
import Setting from "@/setting";
import Bus from '@/libs/bus'
export default {
  data () {
    return {
      Setting,
      passwordVisible: false,
      passwordForm: {
        password: "",
        newPassword: "",
        reNewPassword: ""
      },
      notices: [],
      noticeTimer: null,
      ip: localStorage.getItem('localIp') ? +localStorage.getItem('localIp') : 0,
    };
  },
  computed: {
    ...mapState("user", [
      "avatar", "userName", "title", "logoUrl", "customer", "customerName", 'fromClient'
    ])
  },
  mounted () {
    this.getSystemDetail();
    this.getUserDetail();
    this.getNotice()
    Setting.isPro && this.heartbeatDetection()
  },
  methods: {
    ...mapMutations("user", [
      'SET_SCHOOLID', 'setUserId'
    ]),
    ...mapActions("user", [
      "setTitle", "setLogoUrl", "setAvatar", "setUserName", 'logout'
    ]),
    getSystemDetail () { // 获取系统logo
      this.$get(this.api.logoDetail).then(res => {
        const { data } = res
        if (data) {
          this.setTitle(data.title)
          this.setLogoUrl(data.logoUrl)
          this.SET_SCHOOLID(data.schoolId)
        } else {
          // 获取schoolId
          this.$post(this.api.getSchoolIdByToken).then(res => {
            this.SET_SCHOOLID(res.schoolId)
          }).catch(res => { })
        }
      }).catch(res => { })
    },


    // socket连接成功
    open () {
      console.log("socket连接成功");
    },
    // socket连接失败
    error () {
      console.log("连接错误");
    },
    // 接收消息
    getMessage (msg) {
      console.log("==websocket接收数据==");
      console.log(JSON.parse(msg.data));

      const { content } = JSON.parse(msg.data)
      // 1赛事、2创业、3考核、4模型。-号拼接携带id
      if (content == 1) {
        Bus.$emit('matchSocket')
      } else if (content == 2) {
        Bus.$emit('activitySocket')
      } else if (content == 4) {
        Bus.$emit('modelSocket')
      } else {
        this.getNotice()
      }
    },
    // 关闭socket
    close () {
      console.log("socket已经关闭");
    },
    initSocket ({ id, account }) {
      // 实例化socket
      this.socket = new WebSocket(`${Setting.isTest ? 'ws' : 'wss'}://${Setting.isDev ? '192.168.31.51:9100' : location.host}/nakadai/websocket/${id}/${account}`)
      // this.socket = new WebSocket(`ws://118.31.167.228:9100/nakadai/websocket/${id}/${account}`)
      // 监听socket连接
      this.socket.onopen = this.open;
      // 监听socket错误信息
      this.socket.onerror = this.error;
      // 监听socket消息
      this.socket.onmessage = this.getMessage;
    },
    // 心跳检测
    heartbeatDetection () {
      setInterval(async () => {
        await this.$get(this.api.heartbeatDetection)
      }, 58 * 1000)
    },

    // 获取消息
    getNotice () {
      this.$get(this.api.messageNotificationList, {
        type: 2
      }).then(res => {
        this.notices = res.notificationList
      }).catch(res => { });
    },
    // 前往评论列表
    async toComment (item) {
      await this.$post(`${this.api.noticeRead}?isRead=1&notifyId=${item.notifyId}`) // 该通知置为已读
      this.getNotice()
      this.$router.push(`/station/preview?courseId=${item.cid}&commentId=${item.commentId}&notifyId=${item.notifyId}`)
    },
    getUserDetail () { // 获取用户详情
      this.$get(this.api.queryUserInfoDetails).then(res => {
        this.initSocket(res.result.userAccount)
        let { hrUserInfo } = res.result
        if (hrUserInfo) {
          const { userAvatars, userName, userId } = hrUserInfo
          this.setUserId(userId)
          userAvatars && this.setAvatar(userAvatars)
          this.setUserName(userName)
        }
      }).catch(res => { })
    },
    userCommand (command) { // 切换下拉菜单
      if (command == "person") {
        this.$router.push("/setting/person");
      } else {
        this.passwordVisible = true;
      }
    },
    resetPassword () { // 关闭修改密码
      this.passwordForm = {
        password: "",
        newPassword: "",
        reNewPassword: ""
      };
    },
    submitPassword () { // 提交修改密码
      if (!this.passwordForm.password) return util.warningMsg("请输入原密码");
      if (!this.passwordForm.newPassword) return util.warningMsg("请输入新密码");
      if (!this.passwordForm.reNewPassword) return util.warningMsg("请确认新密码");
      if (this.passwordForm.newPassword.length < 6 || this.passwordForm.reNewPassword.length < 6) return util.warningMsg("请输入6位数以上的密码");
      if (this.passwordForm.newPassword !== this.passwordForm.reNewPassword) return util.warningMsg("输入的新密码不一致，请重新确认");
      if (this.passwordForm.password === this.passwordForm.newPassword) return util.warningMsg("原密码跟新密码不能一致");
      this.$post(this.api.examinePassword, this.passwordForm).then(res => {
        util.successMsg("修改成功");
        this.passwordVisible = false;
      }).catch(err => {
      });
    },

    ipChange (val) {
      localStorage.setItem('localIp', val)
      location.reload()
    },
  }
};
</script>
<style lang="scss" scoped>
.header {
  position: relative;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #333;
  background-color: #fff;

  .logo {
    max-height: 50px;
    margin: 0 20px 0 40px;
  }

  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .action {
    display: flex;
    padding-right: 50px;
    align-items: center;

    .user {
      display: inline-flex;
      align-items: center;
      cursor: pointer;

      span {
        font-size: 12px;
      }
    }

    .el-button--text {
      margin-left: 20px;
      color: #333;
    }

    .el-divider {
      width: 2px;
      height: 15px;
      margin-left: 20px;
      background-color: #333;
    }
  }

  .msg {
    margin-right: 30px;
    font-size: 12px;
    cursor: pointer;
  }
}
</style>