<template>
   <div class="content-box">
     
  <div class="container">
    <!-- <nav>
      <router-link :to="a.url" :key="index" v-for="(a,index) in Data">{{a.title}}</router-link>
       <el-button type="primary" @click="dialogFormVisible = true">断面组件</el-button>
    </nav> -->
    <el-tabs type="border-card">
  <el-tab-pane label="xx路口">
     <div style="width:60%;height:100%;display:inline-block;border:1px soild #eee;padding:15px">
    <img :src='imgUrl' width="100%" height="100%"/>
  </div> 
  <div style="width:20%;height:100%;display:inline-block;border:1px soild #eee;padding:15px">
    <el-button type="primary" @click="dialogFormVisible = true">断面组件</el-button>
    <el-button type="primary" @click="areaComponent = true">区域组件</el-button>
    <el-button type="primary" @click="speed = true">速度组件</el-button>
    <el-button type="primary" @click="indexModule = true">流量组件</el-button>
    <el-button type="primary" @click="indexModule = true">车头时距</el-button>
    <el-button type="primary" @click="indexModule = true">排队数</el-button>
    <el-button type="primary" @click="indexModule = true">检测数</el-button>
    <el-button type="primary" @click="indexModule = true">延误</el-button>
    <el-button type="primary" @click="indexModule = true">拥堵</el-button>
  </div> 
  <div style="width:20%;height:100%;display:inline-block;border:1px soild #eee;padding:15px">
  </div> 
  </el-tab-pane>
  <el-tab-pane label="数据看板">数据看板</el-tab-pane>
  <el-tab-pane label="分析配置">
     <analysisConfiguration ></analysisConfiguration> 
  </el-tab-pane>
  <el-tab-pane label="分析状态">
   <editModal ></editModal> 
  </el-tab-pane>
   <el-tab-pane label="存储">存储</el-tab-pane>
    </el-tabs>
    <!-- <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl' width="100%" height="100%"/>
  </div>  
  <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl1' width="100%" height="100%"/>
  </div> 
  <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl2' width="100%" height="100%"/>
  </div> 
  <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl3' width="100%" height="100%"/>
  </div> 
  <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl4' width="100%" height="100%"/>
  </div> 
  <div style="width:30%;height:300px;display:inline-block">
    <img :src='imgUrl5' width="100%" height="100%"/>
  </div>  -->
 
  </div>
  <div id="dialog" class="margin-top: 0px !important;">
      <el-dialog
    title="断面组件配置"
    width="40%"
    :visible.sync="dialogFormVisible"
  >
  <el-form ref="form" :model="form" label-width="80px">
     <!-- <el-form-item label="实时性">
    <el-radio-group v-model="form.resource">
      <el-radio label="实时（触发）"></el-radio>
      <el-radio label="间隔"></el-radio>
    </el-radio-group>
  </el-form-item> -->
  <el-form-item label="断面名称">
    <el-input v-model="form.name"></el-input>
  </el-form-item>
 <el-form-item label="断面方向">
    <el-select v-model="form.region" placeholder="请选择类型">
      <el-option label="正向" value="car"></el-option>
      <el-option label="方向" value="bus"></el-option>
       <el-option label="双向" value="kache"></el-option>
    </el-select>
  </el-form-item>
 
  <el-form-item>
    <el-button type="primary" @click="onSubmit">确认</el-button>
    <el-button @click="dialogFormVisible = false">取消</el-button>
  </el-form-item>
</el-form>
  </el-dialog>
  <el-dialog
    title="区域组件配置"
    width="40%"
    :visible.sync="areaComponent"
  >
  <el-form ref="form" :model="areaComponentform" label-width="80px">    
  <el-form-item label="区域名称">
    <el-input v-model="areaComponentform.name"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmit">确认</el-button>
    <el-button @click="dialogFormVisible = false">取消</el-button>
  </el-form-item>
</el-form>
  </el-dialog>
  <el-dialog
    title="速度组件配置"
    width="40%"
    :visible.sync="speed"
  >
  <el-form ref="form" :model="speedForm" label-width="80px">    
  <el-form-item label="速度组件名称">
    <el-input v-model="speedForm.name"></el-input>
  </el-form-item>
   <el-form-item label="数值筛选">
    <el-input v-model="speedForm.name"></el-input>
  </el-form-item>
   <el-form-item label="时间模式">
   <el-select v-model="speedForm.region" placeholder="请选择时间模式">
      <el-option label="触发" value="car"></el-option>
      <el-option label="周期时刻" value="bus"></el-option>
       <el-option label="周期统计" value="kache"></el-option>
    </el-select>
  </el-form-item>
   <el-form-item label="展现形式">
     <el-checkbox-group v-model="speedForm.region">
      <el-checkbox label="数值" name="type"></el-checkbox>
      <el-checkbox label="表格" name="type"></el-checkbox>
      <el-checkbox label="时间曲线图" name="type"></el-checkbox>
       <el-checkbox label="均值图" name="type"></el-checkbox>
    </el-checkbox-group>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="onSubmit">确认</el-button>
    <el-button @click="dialogFormVisible = false">取消</el-button>
  </el-form-item>
</el-form>
  </el-dialog>
  </div>
</div>
</template>

<script>

import mqtt from "mqtt"; // mqtt协议
import editModal from "@/views/bounced/maintenanceRemind";
import analysisConfiguration from "@/views/bounced/analysisConfiguration";

import axios from 'axios'
export default {
  data() {
    return {
      hideBoxShow:true, //隐藏箱子按钮显示隐藏
      closeStatus: null,
      modelOthers: false,
      componentShow: "",
      isShowBtn: true, //菜单按钮隐藏
      isShowBtn1: false, //菜单按钮显示
      inputVal: "",
      dialogFormVisible: false,
      areaComponent:false,
      indexModule:false,
      speed:false,
      form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '实时（触发）',
          desc: ''
        },
        areaComponentform: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '实时（触发）',
          desc: ''
        },
        speedForm:{
            name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '实时（触发）',
          desc: ''
        },
    //   dateTime: this.$moment(new Date()).format("LL"),
      nowTime: "",
    //   weekday: this.$moment().format("dddd"),
      ins: 0,
      imgUrl:'',
      imgUrl1:'',
      imgUrl2:'',
      imgUrl3:'',
      imgUrl4:'',
      imgUrl5:'',
      btnPic: [],
      Data:[
        {
         title:'xx路口',
        url:''  
        },
        {
         title:'数据看板',
        url:''  
        },
        {
         title:'分析配置',
        url:''  
        },
        {
         title:'分析配置',
        url:''  
        }
      ],
      statusInfo: [
        {
          count: 15,
          name: "穿梭车在线数量",
        //   icon: require("../assets/images/运行设备图标.png"),
          color: "#01A8FC",
        },
        {
          count: 26,
          name: "任务数量",
        //   icon: require("../assets/images/故障设备图标.png"),
          color: "#FDA401",
        },
      ],
      messageInfo: [],
      orderList: [],
      enterList: [],
      stockInfo: [],
      perCent: 0,
      perCent1: 0,
      perCent2: 0,
      facToal: "",
      wbContent:'',
    //   wxContent:'',
      inContent:'',
      outContent:'',
      containerDetails:"",
      locdesc:'',
      weatherItem:{},
      loadingShow1:true,
      carInfo:[], //小车信息
      carName:'',
      palletizerInfo:[], //码垛机信息
      palletizerName:'',
      destackerInfo:[], //拆垛机信息
      destackerName:'',
      hoistInfo:[], //提升机信息’
      hoistName:'', 
      battaryStationInfo:[],//快换电池装置
      battaryStationName:"",
      conveyorInfo:[], //输送机信息
      conveyorName:"", 
    };
  },
  mounted() {

    // this.getMessage();
    // 消息提醒

    // getfacKeepRecord({ type: 0 }).then((res) => {
    //   this.messageInfo = this.messageInfo.concat(res.data);
    //   console.log(this.messageInfo, ",,qweqw");
    //   // this.messageInfo.push(res.data[1]) 
    // });
    // this.getDataByMqtt()
    // this.getstatus();
    // this.getInhouse();
    // this.getOuthouse();
    // this.handleWather();
    // this.getDeviceStatusData()
  },
   created() {
    this.testMqtt()
    
  },
  methods: {
     // 测试：mqtt测试
    testMqtt() {
         this.getDataByMqtt()
      // 小车订阅
    //   for (let key in this.carId) {
    //     this.getDataByMqtt(
    //       // "ws:ht.mqtt.umayle.com:2022/mqtt",
    //       "ws:220.163.114.157:8083/mqtt",
    //       "Car" + key,
    //       this.carId[key]
    //     );
    //   }
    //   //输送机入库订阅
    //   for (let i = 0; i < this.convoyorCIdGroup.length; i++) {
    //     this.getDataByMqtt(
    //       "ws:220.163.114.157:8083/mqtt",
    //       "InConvoyor" + this.convoyorCIdGroup[i],
    //       this.convoyorCIdGroup[i]
    //     );
    //   }

    //   //输送机出库订阅
    //   for (let i = 0; i < this.outConvoyorCIdGroup.length; i++) {
    //     this.getDataByMqtt(
    //       "ws:220.163.114.157:8083/mqtt",
    //       "OUTConvoyor" + this.outConvoyorCIdGroup[i],
    //       this.outConvoyorCIdGroup[i]
    //     );
    //   }

    //   for (let key in this.BattaryArr) {
    //     this.getDataByMqtt(
    //       "ws:220.163.114.157:8083/mqtt",
    //       "Battary_Sation" + key,
    //       this.BattaryArr[key]
    //     );
    //   }
    //   // 升降机订阅elvArr
    //   for (let key in this.elvArr) {
    //     this.getDataByMqtt(
    //       "ws:220.163.114.157:8083/mqtt",
    //       "ELV" + key,
    //       this.elvArr[key]
    //     );
    //   }
    //   // 拆码跺机订阅
    //   for (let key in this.stampArr) {
    //     this.getDataByMqtt(
    //       "ws:220.163.114.157:8083/mqtt",
    //       "INCMD" + key,
    //       this.stampArr[key]
    //     );
    //   }
    },
    onSubmit(){},
    //模型加载等待
    loadingShow(data){
      this.loadingShow1 = data
    },
     // mqtt订阅（独立）
    getDataByMqtt(url, topic, cIdNum) {
      const clientId = "test_id_" + String(new Date().getTime()); // 用户名
    //   const host = 'ws://49.234.27.18:10087/'; // 一个测试用url，改成给的，ws://broker.emqx.io:8083/mqtt
       const host = 'ws://172.16.1.168:10087/'; 
     
      const options = {
        // 配置
        // 测试：订阅本机IP
        // host: host,
        // port: port,
        // host:"172.16.1.168:10086",
        keepalive: 60, // 心跳时间，默认60s，设置为0禁用
        username: 'admin',  // 用户名（可选）
        password: '123456',  // 密码（可选）
        clientId: clientId, // 客户端ID，默认随机生成
        protocolId: "MQTT",
        protocolVersion: 4,
        clean: true, // false在离线时接收QoS1和2的消息
        reconnectPeriod: 2000, // 重连间隔，默认1000毫秒
        connectTimeout: 30 * 1000, // 收到CONNACK之前的等待时间
        will: {
          // 遗嘱消息（客户端严重断开连接时Broker将自动发送的消息）
          topic: "img1", // 要发布的主题
          payload: "[MQTT-TEST] 遗嘱消息：连接异常断开！", // 要发布的消息
          qos: 0, // QoS(Quality of Service)，QoS0：只负责发，QoS1：保证消息至少送达1次，QoS2：保证消息到且仅到1次
          retain: false, // 保留标志
        },
      };
      if (this.mqttClient == undefined) {
        this.mqttClient = mqtt.connect(host, options); // 连接
        // const client = mqtt.connect(host, options); // 连接
        // const client = mqtt.connect(host)  // 连接
        // 错误回调
        console.log("this.mqttClient",this.mqttClient)
        this.mqttClient.on("error", (err) => {
          console.log("[MQTT-TEST] 连接错误：",err);
          this.mqttClient.end();
        });
        // 重连回调
        this.mqttClient.on("reconnect", (reconnect) => {
          console.log("[MQTT-TEST] 重连中……",reconnect);
        });
        // 连接回调
        this.mqttClient.on("connect", (connect) => {
          console.log("[MQTT-TEST] 已连接的客户端ID: ",connect);
            // 订阅
           this.mqttClient.subscribe('img0', { qos: 0 });
           this.mqttClient.subscribe('img1', { qos: 0 });
           this.mqttClient.subscribe('img2', { qos: 0 });
           this.mqttClient.subscribe('img3', { qos: 0 });
           this.mqttClient.subscribe('img4', { qos: 0 });
            this.mqttClient.subscribe('img5', { qos: 0 });
            this.mqttClient.subscribe('stream0', { qos: 0 });
             this.mqttClient.subscribe('stream1', { qos: 0 });
              this.mqttClient.subscribe('stream2', { qos: 0 });
               this.mqttClient.subscribe('stream3', { qos: 0 });
                this.mqttClient.subscribe('stream4', { qos: 0 });
                 this.mqttClient.subscribe('stream5', { qos: 0 });

        });
        // 接收回调
        this.mqttClient.on("message", (topic, message, packet) => {
          console.log("[MQTT-TEST] 已连接的客户端ID: ",message);
    
          console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          // 解析后端数据
        //   let dataReceived = JSON.parse(message.toString());
        //     console.log("[MQTT-TEST] 已连接的客户端ID: ",dataReceived);
        //      try{
        //         const utf8decoder = new TextDecoder()
        //         const u8arr = new Uint8Array(message)
        //         const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
        //         const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
        //         console.log("msg",msg)   //msg为转换后的JSON数据
        //         this.imgUrl='data:image/png;base64,' + msg.pic;
        //         console.log("imageUrl",imageUrl)
        //     }catch{
        //         let imageType = 'arraybuffer';
        //         const blob = new Blob([message], { type: imageType })
        //         const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
        //         console.log("imageUrl",imageUrl)
        //     }
          if (topic.indexOf("img0") != -1) {
             try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          } else if (topic.indexOf("img1") != -1) {
             try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl1='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          } else if (topic.indexOf("img2") != -1) {
            try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl2='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          } else if (topic.indexOf("img3") != -1) {
            try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl3='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          } else if (topic.indexOf("img4") != -1) {
            try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl4='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          } else if (topic.indexOf("img5") != -1) {
           try{
                const utf8decoder = new TextDecoder()
                const u8arr = new Uint8Array(message)
                const temp = utf8decoder.decode(u8arr)	// 将二进制数据转为字符串
                const msg = JSON.parse(temp)		//这一步报错则返回的是二进制流图片，不报错则返回的是JSON的错误提示数据
                console.log("msg",msg)   //msg为转换后的JSON数据
                this.imgUrl5='data:image/png;base64,' + msg.pic;
                console.log("imageUrl",imageUrl)
            }catch{
                let imageType = 'arraybuffer';
                const blob = new Blob([message], { type: imageType })
                const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
                console.log("imageUrl",imageUrl)
            }
          }else if (topic.indexOf("stream0") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream0") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream1") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream2") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream3") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream4") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }else if (topic.indexOf("stream5") != -1) {
            console.log(
            `[MQTT-TEST] 从主题 "${topic}" 收到的内容: ${message.toString()}`,
            new Date(),
            new Date().getMilliseconds()
          );
          }
         
        });
      }
    
     
    },

    handleSearch(){
      this.modelOthers = true;
      this.$refs.htModels.finbBox(this.inputVal);
      console.log(this.$refs.htModels,'asdasdasd');
       this.inputVal = ''
    },
   handleRow(val){
      this.modelOthers = true;
      this.$refs.htModels.finbBox(val);
    },
    // 天气
    handleWather(){
      axios({url:'https://restapi.amap.com/v3/weather/weatherInfo?key=bc2b906032fdd8a63cbd0790d656b1d7&city=620100',methods:''}).then(res=>{
        this.weatherItem = res.data.lives[0]
        console.log(this.weatherItem,'asdsads');
      })
    },
    Onweather(name){
    //   switch (name) {
	// 				case "多云":
	// 					return require('../assets/weather/Cloudy .png');
	// 				case "阴":
	// 					return require('../assets/weather/Cloudy .png')
	// 				case "暴雨":
	// 					return require('../assets/weather/rainstorm.png')
	// 				case "冰雹":
	// 					return require('../assets/weather/hail.png')
	// 				case "大风":
	// 					return require('../assets/weather/gale.png')
	// 				case "大雪":
	// 					return require('../assets/weather/bigsnow.png')
	// 				case "大雨":
	// 					return require('../assets/weather/bigrain.png')
	// 				case "雷电":
	// 					return require('../assets/weather/thunder.png')
	// 				case "雷阵雨":
	// 					return require('../assets/weather/shower.png')
	// 				case "沙尘暴":
	// 					return require('../assets/weather/sand.png')
	// 				case "晴":
	// 					return require('../assets/weather/sun.png')
	// 				case "雾霾":
	// 					return require('../assets/weather/smog.png')
	// 				case "小雪":
	// 					return require('../assets/weather/snow.png')
	// 				case "小雨":
	// 					return require('../assets/weather/rain.png')
	// 				case "雪":
	// 					return require('../assets/weather/rainlitter.png')
	// 				case "多云":
	// 					return require('../assets/weather/night.png')
	// 				case "雨夹雪":
	// 					return require('../assets/weather/rainsnow.png')
	// 				case "月亮":
	// 					return require('../assets/weather/moon.png')
	// 				case "中雪":
	// 					return require('../assets/weather/mieddlesnow.png')
	// 				case "中雨":
	// 					return require('../assets/weather/middlerain.png')
	// 			}
    },
    //隐藏箱子
    hideBox(){
        this.$refs.htModels.handleFirstBox();
    }
  },
  components: {
   editModal,
   analysisConfiguration
  },
};
</script>
<style>

</style>
