<template>
  <div class="header">
    <div class="bgb-color">
      <el-row>
        <el-col :xs="6" :sm="8" :md="8" :lg="8" class="oneHeader">
          <span>
            <router-link to="/home"><img src="../../../../assets/img/白色logo.png" alt /></router-link>
          </span>
          <span
            :class="['iconfont', collapse?'iconcaidan_zhankai':'iconcaidan_shousuo']"
            @click="CollapseBtn"
          ></span>
        </el-col>
        <el-col :xs="18" :sm="16" :md="16" :lg="16">
          <ul class="headerRight">
            <li>
              <div @click="retreat">
                  <i class="iconfont icontuichu"></i>
                  <span>退出</span>
              </div>
            </li>
            <li>
              <div @click="isnews=!isnews">
                  <i class="el-icon-message-solid"></i>
                  <span>消息列表</span>
              </div>
              <!-- <el-dropdown class="NewListDrop" size="medium" trigger="click" @command="handleCommand" >
                  <span class="el-dropdown-link">
                    <i class="el-icon-message-solid"></i>
                    消息列表 -->
                    <!-- <i class="el-icon-arrow-down el-icon--right"></i> -->
                  <!-- </span>
                  <el-dropdown-menu slot="dropdown" style="width: 300px;
    height: 500px;
    overflow-y: scroll;">
                    <el-dropdown-item
                      v-for="item in NewList"
                      :key="item.id"
                      :command="item"
                    >{{item.content}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->


               
            </li>
            <!-- <li>
              <div><i class="el-icon-setting"></i>系统设置</div>
            </li> -->
            <li>
              <el-dropdown trigger="click" @command="handleCommand">
                  <span class="el-dropdown-link">
                    <i class="el-icon-sort"></i>
                    切换团队
                    <!-- <i class="el-icon-arrow-down el-icon--right"></i> -->
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="item in CompanyList"
                      :key="item.id"
                      :command="item"
                    >{{item.name}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              
            </li>
            <li>
              <div>{{CompanyClick}}</div> 
            </li>
            <li>
              <div @click="toUserAccount">
                <img :src="userAvatar" alt />
                <div style="margin-left:5px">{{userName}}</div>
                <div style="margin-left:5px">({{userRole}})</div>
              </div>
            </li>
          </ul>
          <!-- <div style="text-align: right;">
            <div class="twoHeader">
              <div style="width:160px">
                <a href="">
                  <img :src="userAvatar" alt />
                  <div style="margin-left:5px">{{userName}}</div>
                  <div style="margin-left:5px">({{userRole}})</div>
                </a>
              </div>
              <div style="width:180px">
                <div>{{CompanyClick}}</div>
              </div>
              <div style="width:120px">
                <el-dropdown trigger="click" @command="handleCommand">
                  <span class="el-dropdown-link">
                    切换团队
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="item in CompanyList"
                      :key="item.id"
                      :command="item"
                    >{{item.name}}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              <div style="width:80px">
                <div @click="retreat">
                  <span>退出登录</span>
                  <span class="iconfont icontuichu1"></span>
                </div>
              </div>
            </div>
          </div> -->
        </el-col>
      </el-row>
    </div>
    <div class="NewListDio" v-if="isnews">
     <el-scrollbar style="height:500px">
          <p v-for="item in NewList" :style="{color:item.viewFlag==1?'#409eff':'#606266'}"
            :key="item.id" :title="item.content" @click="showNewsOne(item)">
          {{item.content}}</p>
      </el-scrollbar>
    </div>
    <div class="showNews">
      <el-dialog title="查看消息"
        width="50%"
         :visible.sync="dialogshowNews">
        <p>{{NewsContent}}</p>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import bus from "./bus";
import store from '../../store/index';
let socket;
export default {
  
  data() {
    return {
      isnews:false,
      dialogshowNews:false,
      NewsContent:'',
      collapse: false,
      CoputStatus: false,
      CompanyList: [],
      CompanyClick:"",
      userAvatar:"",
      userName:"",
      userRole:"",
      NewList:[
      
      ],
      // 连接标志位
      lockReconnect: false,
      wsCfg: {
          // websocket地址
          url: "wss://ws.edtyun.com/myMessageHandler"
      }
    };
  },
  
  created() {
    this.CompanyList = JSON.parse(JSON.parse(sessionStorage.getItem('companyList')))?JSON.parse(JSON.parse(sessionStorage.getItem('companyList'))):[]
    // this.CompanyClick = this.CompanyList?this.CompanyList[0].name:''
    this.CompanyClick = JSON.parse(sessionStorage.getItem('companyID')).name?JSON.parse(sessionStorage.getItem('companyID')).name:''
    // console.log(this.CompanyList)
    this.userAvatar =JSON.parse(JSON.parse(sessionStorage.getItem('userAvatar')))?JSON.parse(JSON.parse(sessionStorage.getItem('userAvatar'))):''
    this.userName =JSON.parse(JSON.parse(sessionStorage.getItem('userName')))?JSON.parse(JSON.parse(sessionStorage.getItem('userName'))):''
    this.userRole =JSON.parse(sessionStorage.getItem('userRole'))?JSON.parse(JSON.parse(sessionStorage.getItem('userRole'))):''
    // this.showNewList()
  },
  mounted(){
    this.createWebSocket();
    // this.test()
  },
 

  methods: {
    CollapseBtn() {
      this.collapse = !this.collapse;
      this.CompanyList = [
        {
          companyAddress: "测试地址0",
          companyId: 1,
          companyName: "测试公司0"
        }
      ]
      bus.$emit("funCol", this.collapse);
    },
    confirmDelete() {
      this.$store.commit("SET_TOKEN", "");
      this.$store.commit("SET_companyList", "");
      this.$store.commit("SET_USER", "");
      this.$router.push("/login");
    },
    // showNewList(){
    //   var url = "push/message/list";
    //   var param = {
    //     userId: sessionStorage.getItem('user'),
    //     type: 1
    //   };
    //   this.axios.post(url, param).then(res => {
    //     if (res.statusCode === "1") {
    //       var data = res
    //       this.NewList = data.data.records?data.data.records:[]
    //     } 
    //   });
    // },
    createWebSocket() {
        try {
            // 创建Web Socket 连接
            socket = new WebSocket(this.wsCfg.url+"?currentUserId="+JSON.parse(sessionStorage.getItem("user")));
            // 初始化事件
            this.initEventHandle(socket);
            this.test()
        } catch (e) {
            // 出错时重新连接
            this.reconnect(this.wsCfg.url+"?currentUserId="+JSON.parse(sessionStorage.getItem("user")));
        }
    },
    initEventHandle(socket) {
        // 连接关闭时触发
        socket.onclose = () => {
            console.log("连接关闭");
        };
        // 通信发生错误时触发
        socket.onerror = () => {
            // 重新创建长连接
            this.reconnect();
            console.log("通信错误")
        };
        // 连接建立时触发
        socket.onopen = () => {
            console.log("连接成功");
        };
        // 客户端接收服务端数据时触发
        socket.onmessage = msg => {
            // 业务逻辑处理
            console.log(JSON.parse(msg.data));
            if(JSON.parse(msg.data).msgList){
              this.NewList = JSON.parse(msg.data).msgList
            }else{
              this.NewList=[{
                id:0,
                content:'暂无消息'
              }]
            }
            
        };
    },
    showNewsOne(item){
      this.NewsContent = item.content
      this.dialogshowNews = true;
      this.isnews = !this.isnews
      if(item.viewFlag==0){
        var url = "push/message/read";
        var param = {
          ids: [item.id]
        };
        this.axios.post(url, param).then(result => {
          var data = result;
          if (data.statusCode === "1") {
            
          }else {
          }
        });
      }
    },
    reconnect() {
      if (this.lockReconnect) {
          return;
      }
      this.lockReconnect = true;

      //没连接上会一直重连，设置延迟避免请求过多
      setTimeout(() => {
          this.lockReconnect = false;
          this.createWebSocket(this.wsCfg.url+"?currentUserId="+JSON.parse(sessionStorage.getItem("user")));
      }, 60000);
    },
    test() {
      // 给服务器发送一个字符串:
      socket.send('111');
    },
    retreat() {
      var that = this;
      this.$confirm("您确定要退出登录吗?", "退出登录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          that.confirmDelete();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退出"
          });
        });
    },
    //团队点击
    handleCommand(command){
      this.$store.commit("SET_mtCompanyId",command.id);
      sessionStorage.setItem('companyID',JSON.stringify(command))
      this.CompanyClick = command.name;
      var url = "system/login/changeTeam";
      var param = {
        companyId:JSON.parse(sessionStorage.getItem('mtCompanyId')),
        userId:JSON.parse(sessionStorage.getItem("user"))
      };
      this.axios.post(url, param).then(result => {
        var data = result;
        if(data.statusCode==="1"){
          this.$store.commit("SET_TOKEN",result.data.token);  
          this.$store.commit("SET_menus",result.data.menus);
          this.$store.commit("SET_USERROLE",result.data.role?result.data.role.name:'');
          window.location.reload();
        }else{
          this.$message.error(result.message);
        }
      });
    },
    toUserAccount(){
      this.$router.push("/UserAccount");
    },
  }
};
</script>
<style lang="stylus">
$bColor = #40A9FF;
$fwColor = #fff;
$San-font = 'Open Sans,sans-serif';

body {
  margin: 0;
}

.header {
  width: 100%;
  font-famil: $San-font;
  font-size:16px

  .bgb-color {
    background-color: $bColor;
    padding: 1rem 1.5rem;

    .oneHeader {
      span {
        display: inline-block;
        width: 149px;
        vertical-align: middle;
        padding-left: 1rem;
        color: #fff;

        img {
          width: 100%;
        }
      }

      >span:last-child {
        width: 30px;
      }

      .iconcaidan_shousuo {
        color: #fff;
        cursor: pointer;
      }
    }
    .headerRight{
      li{
        float right
        display: inline-block;
        font-size: 16px;
        color: #fff;
        font-weight: bold; 
        cursor pointer
        margin 0 15px
        .el-dropdown {
          background-color: #40a9ff;
          color: #40a9ff;
          margin-left: 1rem;
          border-radius: 6px;
          line-height: 24px;
          padding: 0 0.5rem;
          cursor: pointer;
          margin-top: 5px;
          padding: 0 4px;

          span {
            color: #fff;
            font-size: 16px;
            i{
              border: 1px solid;
              padding: 3px;
              border-radius: 50%;
            }
          }
        }
      }
      li:nth-child(3),li:nth-child(2) {
        margin-left 0 
      }
      li:nth-child(5) {
        div{
          img{
            display inline-block
            width 35px;
            height 35px;
            border-radius: 50%;
          }
          div{
            display inline-block
            vertical-align: top
            line-height: 35px;
          }
        }
      }
      li:nth-child(4) {
        margin-right 0
        div{
          line-height: 35px;
          padding-right: 1rem;
          border-right: 1px solid #fff;
          i{
            border: 1px solid;
            padding: 3px;
            border-radius: 50%;
          }
        }
      }
     /* li:nth-child(2) {
        div{
          line-height: 35px;
          i{
            border: 1px solid;
            padding: 3px;
            border-radius: 50%;
          }
        }
      }*/
      li:nth-child(1),li:nth-child(2)   {
        div{
          line-height: 35px;
          i{
            border: 1px solid;
            padding: 3px;
            border-radius: 50%;
          }
          >.iconfont {
            font-size: 16px;
          }
        }
        
      }
      
    }
    /*.twoHeader {
      width 550px
      div:first-child {
        text-align: right;
        img{
          display inline-block
          width 35px;
          height 35px;
          border-radius: 50%;
        }
        div{
          display inline-block
          vertical-align: top
        }
      }
      div:nth-child(2) {
        text-align: right;

        div {
          padding-right: 1rem;
          border-right: 1px solid #fff;
        }
      }

      div {
        display: inline-block;
        font-size: 16px;
        color: #fff;
        font-weight: bold;
        line-height: 34px;
      }

      .el-dropdown {
        background-color: #fff;
        color: #40a9ff;
        margin-left: 1rem;
        border-radius: 6px;
        line-height: 24px;
        padding: 0 0.5rem;
        cursor: pointer;

        span {
          color: #40a9ff;
          font-size: 16px;
        }
      }

      >.el-col:last-child {
        text-align: left;

        span {
          font-weight: 300;
        }

        >.iconfont {
          font-size: 16px;
        }
      }

      >.el-col:last-child {
        >div {
          cursor: pointer;
        }
      }
    }*/
  }
}

.NewListDio{
  position: absolute;
  right: 100px;
  width: 300px;
  z-index: 10000000;
  border: 1px solid #EBEEF5;
  font-size: 14px;
  padding: 5px 10px;
  background: #fff;
  border-radius: 20px;
  .el-scrollbar__view p {
      padding: 10px 5px;
      white-space: nowrap;
      overflow-x: hidden;
      text-overflow: ellipsis;
      cursor: pointer;
  }
  .el-scrollbar__view p:hover {
      background-color: #ecf5ff;
      color: #409eff;
  }
}

</style>

  