<template>
  <div class="header-bar">
<!--    <sider-trigger :collapsed="collapsed" icon="md-menu" @on-change="handleCollpasedChange"></sider-trigger>-->
<!--    <custom-bread-crumb show-icon style="margin-left: 30px;" :list="breadCrumbList"></custom-bread-crumb>-->
    <div class="content">
      <div class="left">
        <div class="logo-title">
          <img src="../../../../assets/images/log-new-login.png" alt="">
          <span class="text">智能仓储系统</span>
        </div>
        <div class="item">
          <span class="title">Hi，{{ userInfo.real_name }}</span>
          <span class="sub-title">欢迎登录！</span>
        </div>
      </div>
      <div class="center" ref="text-wrap">
        <span ref="text" class="nav-title">实现订单的需求与面料/配件供应的动态匹配</span>
      </div>
      <div class="right">
<!--        <div class="item search">-->
<!--          <Input prefix="ios-search" placeholder="search" clearable />-->
<!--        </div>-->
        <div class="item info">
          <Poptip v-model="tipVisible" placement="bottom">
            <img :src="avatarPic" alt="">
            <span class="sub-title">{{ userInfo.real_name }}</span>
            <Icon type="md-arrow-dropdown" color="#0077ff" />
            <div class="tip-content" slot="content">
              <div class="tip-top">
                <div class="tip-top-left">
                  <img :src="avatarPic" alt="">
                </div>
                <div class="tip-top-right">
                  <div class="sub-title">{{ userInfo.real_name }}</div>
                  <div class="tip-top-text">{{ userInfo.user_name }}</div>
                  <!-- <div class="tip-top-text">工号：{{ userInfo.user_name }}</div> -->
                </div>
              </div>
<!--              <div class="tip-center">-->
<!--                <div class="tip-center-wrap">-->
<!--                  <div class="row">-->
<!--                    <span>本次登陆时长</span>-->
<!--                    <span>总在线时长</span>-->
<!--                  </div>-->
<!--                  <div class="row">-->
<!--                    <span>00.00.00</span>-->
<!--                    <span>00.00.00</span>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </div>-->
              <!-- <div @click="changePwd" class="tip-bottom border">
                <span style="color: rgb(8, 123, 225);">修改密码</span>
                <my-modal-form v-model="changePwdShow" title="修改密码" :config="formConfig" :rule-validate="ruleValidate" @confirm="changePwdCfm"></my-modal-form>
              </div> -->
              <div @click="logout" class="tip-bottom">
                <span>退出</span>
              </div>
            </div>
          </Poptip>
        </div>
        <div class="item" @click="toHandle" v-if="$store.state.user.access !== 'supplier'">
          <span style="color: #0077ff;cursor: pointer">待审批</span>
        </div>
        <div class="item" @click="toMsg">
          <div class="msg-icon">
            <Icon type="md-notifications-outline" size="20" />
            <div class="idot" v-if="msgLength">{{ msgLength }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="custom-content-con">
      <slot></slot>
    </div>
  </div>
</template>
<script>
import * as signalR from '@microsoft/signalr'
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack'
import config from '@/config'
import MyModalForm from '_c/my-modal-form/my-modal-form'
import logoTitlePic from '@/assets/images/login-icon.png'
import avatarPic from '@/assets/images/avatar.png'
import { GetMessageRemindPage, ReadMessageRemind } from '@/api/storageHome'
import { ChangePassword } from '@/api/user'
import { mapActions } from 'vuex'
import siderTrigger from './sider-trigger'
import customBreadCrumb from './custom-bread-crumb'
import './header-bar.less'
export default {
  name: 'HeaderBar',
  components: {
    siderTrigger,
    customBreadCrumb,
    MyModalForm
  },
  props: {
    collapsed: Boolean
  },
  data () {
    return {
      baseUrl: process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro,
      avatarPic,
      logoTitlePic,
      tipVisible: false,
      changePwdShow: false,
      timer: null,
      titleTimer: null,
      title: '',
      msgList: [],
      msgLength: 0,
      name: this.$store.state.user.name,
      accessName: this.$store.state.user.accessName,
      jobNo: this.$store.state.user.jobNo,
      formConfig: [
        {
          type: 'input',
          comType: 'password',
          label: '新密码',
          key: 'newPassword',
          placeholder: '请输入新密码'
        },
        {
          type: 'input',
          comType: 'password',
          label: '确认密码',
          key: 'cfmPassword',
          placeholder: '请输入确认密码'
        }
      ],
      ruleValidate: {
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        cfmPassword: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' }
        ]
      },
      userInfo: JSON.parse(window.localStorage.getItem('token')),
    }
  },
  computed: {
    msgChange () {
      return this.$store.state.app.msgChange
    },
    breadCrumbList () {
      return this.$store.state.app.breadCrumbList
    }
  },
  watch: {
    msgChange () {
      this.readMessageRemind()
    }
  },
  methods: {
    ...mapActions([
      'handleLogOut'
    ]),
    handleCollpasedChange (state) {
      this.$emit('on-coll-change', state)
    },
    changePwd () {
      this.tipVisible = false
      this.changePwdShow = true
    },
    changePwdCfm (type, data) {
      ChangePassword(data).then(res => {
        if (res.code === 0) {
          this.$Message.info('修改成功，请重新登录！')
          this.changePwdShow = false
          setTimeout(() => {
            this.handleLogOut().then(() => {
              this.$router.push({
                name: 'login'
              })
            })
          }, 1000)
        }
      })
    },
    logout () {
      this.$MyModal.show({
        type: 'exit',
        text: '确认退出吗？'
      }).$on('confirm', () => {
        this.handleLogOut().then(() => {
          this.$router.push({
            name: 'login'
          })
        })
      })
    },
    /* 弹出消息提示 */
    notice (msg) {
      this.$Notice.warning({
        title: '消息通知',
        name: msg.id,
        duration: 0,
        render: h => {
          let _this = this
          return h('div', [
            h('div', { style: { paddingBottom: '20px', lineHeight: '1.5' } }, msg.content),
            h('div', {
              style: { textAlign: 'right' }
            }, [
              h('span', {
                style: {
                  color: 'blue',
                  cursor: 'pointer',
                  textDecoration: 'underline',
                  marginRight: '10px'
                },
                on: {
                  click () {
                    _this.$Notice.destroy()
                    _this.toMsg()
                  }
                }
              }, '所有未读'),
              h('span', {
                style: {
                  color: 'blue',
                  cursor: 'pointer',
                  textDecoration: 'underline'
                },
                on: {
                  click () {
                    ReadMessageRemind({
                      id: msg.id
                    }).then(res => {
                      if (res.code === 0) {
                        _this.readMessageRemind()
                        _this.$Notice.close(msg.id)
                      }
                    })
                  }
                }
              }, '已阅')
            ])
          ])
        }
      })
    },
    /* 首次加载显示消息徽章 弹出消息提示 */
    alertMsg () {
      GetMessageRemindPage({
        pageIndex: 1,
        pageSize: 1,
        readState: 0
      }).then(res => {
        if (res.code === 0) {
          this.msgLength = res.result.totalCount < 100 ? res.result.totalCount : 99
          this.msgList = res.result.list[0]
          if (this.msgList) {
            this.notice(this.msgList)
            this.title = this.msgList.content
            this.blinkMsg()
          } else {
            clearInterval(this.timer)
          }
        }
      })
    },
    /* 修改当前消息条数 */
    readMessageRemind () {
      GetMessageRemindPage({
        pageIndex: 1,
        pageSize: 1,
        readState: 0
      }).then(res => {
        if (res.code === 0) {
          this.msgLength = res.result.totalCount < 100 ? res.result.totalCount : 99
          this.msgList = res.result.list[0]
          if (this.msgList) {
            this.title = this.msgList.content
            this.blinkMsg()
          } else {
            clearInterval(this.timer)
          }
        }
      })
    },
    /* 设置消息闪烁 */
    blinkMsg (content) {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        // 截取首字符串(第一个)
        var head = this.title.substring(0, 1)
        // 截取除首字符串外所有字符串(除第一个所有)
        var foot = this.title.substring(1)
        // 头尾拼接后赋给data => tit属性
        this.title = foot + head
        // 最后赋给最终显示的标题(标题)
        document.title = this.title
      }, 300)
    },
    /* 跳转消息列表 */
    toMsg () {
      this.$router.push({
        name: 'msg'
      })
    },
    /* 跳转待审批 */
    toHandle () {
      this.$router.push({
        name: 'schedule'
      })
    },
    /* 中间固定文字滚动 */
    textAnimate () {
      let textWrapEl = this.$refs['text-wrap']
      let textEl = this.$refs['text']
      let position = 0
      if (textWrapEl.offsetWidth < textEl.offsetWidth) {
        position = textWrapEl.offsetWidth - textEl.offsetWidth
        textEl.style.left = position + 'px'
      }
      this.titleTimer = setInterval(() => {
        if (position === (textWrapEl.offsetWidth - textEl.offsetWidth)) {
          position = 0
          textEl.style.left = position + 'px'
        } else if (textWrapEl.offsetWidth < textEl.offsetWidth) {
          position = textWrapEl.offsetWidth - textEl.offsetWidth
          textEl.style.left = position + 'px'
        }
      }, 3000)
    },
    SRConnection () {
      let _this = this
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl(`${this.baseUrl}/plcHub?groupName=pcGroup`)
        .withAutomaticReconnect()
        .withHubProtocol(new MessagePackHubProtocol())
        .build()
      // 获取扫描rfid
      this.connection.on('bindRfid', res => {
        console.log('获取rfid通知')
        console.log(res)
        this.connection.invoke('ReturnSureMes', res.MesId)
        this.$emit('sr-handle', 'rfid', res.Data)
      })
      this.connection.start().then(() => {
        console.log('连接成功--')
      }).catch(err => {
        console.log('err--')
        console.log(err)
        re_start()
      })
      // 监听网络断开
      this.connection.onclose(() => {
        this.connection = null
        console.log('网络已断开！')
        // this.$Message.error('网络连接断开')
        // this.$router.go(0)
      })
      // 异常重启
      async function re_start () {
        try {
          await _this.connection.start()
        } catch (err) {
          setTimeout(() => re_start(), 5000)
        }
      }
    }
  },
  mounted () {
    // this.SRConnection()
    //this.alertMsg()
    this.$nextTick(() => {
      this.textAnimate()
    })
  },
  destroyed () {
    clearInterval(this.timer)
    clearInterval(this.titleTimer)
  }
}
</script>

<style lang="less" scoped>
.content {
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  min-width: 1000px;

  .left, .right {
    display: flex;
    align-items: center;
    height: 100%;
    .info {
      margin-right: 83px !important;
      .sub-title {
        font-size: 14px;
      }
    }
    .item {
      margin-right: 30px;
      &:last-child {
        margin-right: 0;
      }
      .sub-title {
        padding: 0 15px;
        color: #0077ff;
      }
    }
  }
  .center {
    position: relative;
    margin: 0 10px;
    flex: 1;
    overflow: hidden;
    color: #FFFF80;
    .nav-title {
      position: relative;
      white-space: nowrap;
      transition: all 3s;
      left: 0;
    }
  }
  .left {
    .logo-title {
      margin-right: 54px;
      height: 100%;
      display: flex;
      align-items: center;
      img {
        width: 113px
      }
      .text {
        margin-left: 13px;
        font-size: 28px;
        font-style: italic;
        letter-spacing: 2px;
      }
    }
  }
  .right {
    .item {
      display: flex;
      align-items: center;
      margin-right: 20px;
      cursor: pointer;
      .idot {
        position: absolute;
        right: 0;
        top: 0;
        display: inline-block;
        background-color: red;
        width: 16px;
        height: 16px;
        line-height: 16px;
        border-radius: 50%;
        text-align: center;
        font-size: 12px;
      }
      .msg-icon {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #3a4045;
      }
    }
  }
}
/deep/ .search {
  margin-right: 52px !important;
  .ivu-input {
    border: none;
    background: #21262b;
    border-radius: 16px;
    color: #d7d7d7;
  }
}
/deep/ .ivu-poptip-rel {
  display: flex;
  align-items: center;
}
/deep/ .ivu-poptip-popper{
  padding: 0 !important;
  top: 79px !important;
  .ivu-poptip-arrow {
    display: none;
  }

  .ivu-poptip-body {
    padding: 0;
    .ivu-poptip-body-content {
      overflow: hidden;
    }
    .tip-content {
      width: 252px;
      box-sizing: border-box;
      background-color: #3a4045;
      border-radius: 0px 0px 4px 4px;
      border: solid 1px #565c61;
      .tip-top {
        height: 93px;
        box-sizing: border-box;
        display: flex;
        .tip-top-left {
          padding: 20px 15px;
          img {
            width: 40px;
            height: 40px;
          }
        }
        .tip-top-right {
          .sub-title {
            padding: 20px 0 10px 0;
          }
          .tip-top-text {
            padding-bottom: 10px;
            line-height: 1;
            font-size: 12px;
          }
        }
      }
      .tip-center {
        height: 61px;
        box-sizing: border-box;
        border-top: solid 1px #565c61;
        border-bottom: solid 1px #565c61;
        display: flex;
        align-items: center;
        .tip-center-wrap {
          flex: 1;
        }
        .row {
          display: flex;
          justify-content: space-around;
          span {
            font-size: 12px;
          }
        }
      }
      .tip-bottom {
        height: 41px;
        line-height: 41px;
        text-align: center;
        box-sizing: border-box;
        span {
          font-size: 12px;
        }
        &.border {
          border-top: solid 1px #565c61;
          border-bottom: solid 1px #565c61;
        }
      }
    }
  }
}
</style>
