<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" />

    <div class="right-menu">
      <div class="right-menu-item hover-effect">
        <span style="font-weight: bold">部门：{{ pd.DEPARTMENT_NAME }}</span>
      </div>
      <div class="right-menu-item hover-effect">
        <span style="font-weight: bold">姓名：{{ pd.NAME }}</span>
      </div>
      <div class="right-menu-item hover-effect" @click="gotoMap()">
        <svg-icon icon-class="dashboard" />
        <span>地图</span>
      </div>
      <div class="right-menu-item hover-effect" @click="gotoBI()">
        <svg-icon icon-class="dashboard" />
        <span>驾驶舱</span>
      </div>
      <div class="right-menu-item hover-effect" @click="setShowModel('other')">
        <svg-icon icon-class="dashboard" />
        <span>安全监管</span>
      </div>
      <div class="right-menu-item hover-effect" @click="setShowModel('relatedParties')">
        <svg-icon icon-class="dashboard" />
        <span>相关方</span>
      </div>
      <div class="right-menu-item hover-effect" @click="setShowModel('detection')">
        <svg-icon icon-class="dashboard" />
        <span>在线监测</span>
      </div>
      <div class="right-menu-item hover-effect" @click="setShowModel('system')">
        <svg-icon icon-class="example" />
        <span>系统管理</span>
      </div>
      <!-- <template v-if="device!=='mobile'">
        <screenfull id="screenfull" class="right-menu-item hover-effect" />

        <el-tooltip content="Global Size" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip>
      </template> -->

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img src="../../assets/avatar.png" class="user-avatar">
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="Message">基本资料</el-dropdown-item>
          <el-dropdown-item @click.native="changePassword">修改密码</el-dropdown-item>
          <el-dropdown-item divided @click.native="goOut">
            <span style="display:block;">注销</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-dialog :visible.sync="dialogMessage" :append-to-body="true" title="基本资料" width="600px">
      <div style="padding:0 40px">
        <el-form ref="userForm" :model="pd" :rules="resetFormRules" status-icon label-width="100px">
          <el-form-item label="用户名" >
            <el-input v-model="pd.USERNAME" disabled placeholder="默认用户手机号码..." />
          </el-form-item>
          <el-form-item label="姓名" prop="NAME">
            <el-input v-model="pd.NAME" placeholder="这里输入姓名..." />
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogFormEdit" :append-to-body="true" title="修改密码" width="700px">
      <div style="padding:0 40px">
        <el-form ref="resetForm" :model="resetForm" :rules="resetFormRules" status-icon label-width="100px">
          <el-form-item label="旧密码：" prop="password">
            <el-input v-model="resetForm.password" type="password" auto-complete="off"/>
          </el-form-item>
          <el-form-item label="新密码：" prop="newpwd">
            <el-input v-model="resetForm.newpwd" type="password" maxlength="16" placeholder="请输入长度8-16位密码，必须由大写字母，小写字母，数字，特殊符号(!#@*&.)组成" auto-complete="off"/>
          </el-form-item>
          <el-form-item label="确认密码：" prop="newpassword1">
            <el-input v-model="resetForm.newpassword1" type="password" auto-complete="off"/>
          </el-form-item>

        </el-form>
        <div style="text-align: center;margin-top:30px">
          <el-button type="primary" @click.native.prevent="confirm">确认修改</el-button>

        </div>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { Message, MessageBox } from 'element-ui'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import SizeSelect from '@/components/SizeSelect'
import { requestFN } from '@/utils/request'
export default {
  components: {
    Breadcrumb,
    Hamburger,
    Screenfull,
    SizeSelect
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'))
      } else if (value.toString().length < 8 || value.toString().length > 16) {
        callback(new Error('密码长度为8-16位'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetForm.newpwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogMessage: false,
      config: config,
      fwebsocket: {},
      dialogFormEdit: false,
      pd: {
        NAME: '',
        USERNAME: ''
      },
      resetForm: {
        newpwd: '',
        newpassword1: '',
        password: '',
        username: ''
      },
      resetFormRules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newpwd: [
          { required: true, validator: validatePass, trigger: 'blur' },
          {
            pattern: /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)(?=.*?[!#@*&.])[a-zA-Z\d!#@*&.]*.{8,16}$/,
            message: '请输入长度8-16位密码，必须由大写字母，小写字母，数字，特殊符号(!#@*&.)组成'
          }
        ],
        newpassword1: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'device'
    ])
  },
  created() {
    this.getInfo()
    this.editUserOwn()
  },
  methods: {
    // 从修改个人资料
    editUserOwn: function() {
      requestFN(
        '/user/goEditMyInfo',
        {}
      ).then((data) => {
        this.USER_ID = data.pd.USER_ID				// 主职角色ID
        this.USERNAME = data.pd.USERNAME
        this.NAME = data.pd.NAME
        // this.ROLE_IDS = data.pd.ROLE_IDS				// 副职角色ID
        // this.DEPARTMENT_ID = data.pd.DEPARTMENT_ID
        this.pd = Object.assign({}, data.pd) // copy obj
      }).catch((e) => {
      })
    },
    gotoMap() {
      this.$router.push('/map')
    },
    gotoBI() {
      this.$router.push('/BI')
      // window.open(this.config.weburl + 'static/bi-first/index.html', '_blank')
    },
    setShowModel(model) {
      this.$store.dispatch('permission/setShowModel', model)
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    getInfo() {
      var _this = this
      requestFN(
        '/head/getInfo',
        {}
      ).then((data) => {
        // 加入在线列表
        sessionStorage.setItem('onlineAdress', data.onlineAdress)
        if (window.WebSocket) {
          this.fwebsocket = new WebSocket(encodeURI('ws://' + data.onlineAdress)) // oladress在main.jsp页面定义
          this.fwebsocket.onopen = () => {
            this.fwebsocket.send('[join]' + data.USERNAME) // 连接成功
          }
          this.fwebsocket.onerror = function() {
            // 连接失败
          }
          this.fwebsocket.onclose = function() {
            // 连接断开
          }
          // 消息接收
          this.fwebsocket.onmessage = function(message) {
            var messageMsg = JSON.parse(message.data)
            if (messageMsg.type == 'goOut') {
              _this.goOut('1')
            } else if (messageMsg.type == 'thegoout') {
              _this.goOut('2')
            }
          }
        }
      })
        .catch((e) => {
          MessageBox.alert('登录失效,请重新登录', {
            confirmButtonText: '确定',
            callback: action => {
              sessionStorage.clear()
              location.reload()
            }
          })
        })
    },
    // 下线
    goOut: function(msg) {
      requestFN(
        '/main/logout',
        { }
      ).then((data) => {
        this.fwebsocket.close()
        sessionStorage.clear()
        location.reload()
      })
        .catch((e) => {
          this.fwebsocket.close()
          sessionStorage.clear()
          location.reload()
        })
    },
    Message() {
      this.editUserOwn()

      this.dialogMessage = true
    },
    changePassword() {
      this.dialogFormEdit = true
    },
    confirm() {
      this.$refs.resetForm.validate(valid => {
        if (valid) {
          requestFN(
            '/user/editUserPwd',
            this.resetForm
          ).then((data) => {
            Message({
              message: '密码修改成功',
              type: 'success',
              duration: 5 * 1000
            })
            this.dialogFormEdit = false
          }).catch((e) => {
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color:transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 54px;

    &:focus {
      outline: none;
    }

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

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

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
