<template>
<div>
 
  <div class="x-bar" v-show="container_show">
    <div id="container"></div>
  </div>
  <!-- 折线图 -->
  </div>

</template>
<script>
import Highcharts from "highcharts"; //必须引入
import { kgReplace, ugread } from "./Util.js";
import { options } from 'runjs';
import { request } from "@/utils/request";

export default {
  data() {
    return {
       container_show:false,
      chart: null,
      convergeDate: { title: "hcfd", VARIABLES: [], value: [] },
    numlist:[],
    s1:'',
    option:{
        title: {
          text: "HCFD",
        },
        type: 'point',
        credits:{
          enabled:false,
        },
        chart: {
          plotBackgroundColor: "rgba(255,255,255,0)",
          // borderWidth: 1,
          backgroundColor: "rgba(255,255,255,0)",
        },
        yAxis: {},
        xAxis: {},
        plotOptions: {
          series: {
            lineWidth: 2,
            label: {
              connectorAllowed: false,
            },
            marker: {
              radius: 5,
            },
            pointStart: 1,
          },
        },
        tooltip: {},
       
                
        legend: {
                  layout: "horizontal",
                  align: "center",
                  verticalAlign: "bottom",
                  itemStyle:{'color':"#b6b6b6" }
                },
        series: [
        ],
      }
    };
  },
  components:{
 
  },
    props:{
    name:String,
    projectId:String,
    lsolverState:String,
    numzhexian:String,
    nmlsteps:Number,
    state:String,
   

  },
  mounted: function () {
   // this.oldlog()
    Highcharts.setOptions({
      global: {
        useUTC: false,
      },
    });
    let _this = this;
   // this.getwebsocket();
  },
  methods: {
      newHighcharts(){
      let _this = this;
  _this.chart = Highcharts.chart("container",_this.option);
    },
      hiden(){
      this.container_show=false;
    },
    nhiden(){
      this.container_show=true;
    },

  // 时间换算
  timedata(d1, d2,s1){
    console.log(this.nmlsteps);
 var date1 = new Date(d1);   //开始时间  
            var date2 = new Date(d2);    //结束时间  
             var cydata=(date2.getTime() - new Date(date1).getTime())/s1*(Number(this.nmlsteps)-s1);
           //var Milliseconds = date2.getTime() - new Date(date1).getTime();   //时间差的毫秒数       
          
            var Milliseconds = cydata;
            //计算出相差天数  
            var days = Math.floor(Milliseconds / (24 * 3600 * 1000))
            //计算出小时数   
            var leave1 = Milliseconds % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数  
            var hours = Math.floor(leave1 / (3600 * 1000))
            //计算相差分钟数  
            var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数  
            var minutes = Math.floor(leave2 / (60 * 1000))
            //计算相差秒数  
            var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数  
        
            var seconds = Math.round(leave3 / 1000)
            var ResultJson = {
                days: {
                    days: days >= 0 ? days : days + 1,
                    hours: hours >= 0 ? hours: hours + 1,
                    minutes: minutes >= 0 ? minutes : minutes + 1,
                    seconds: seconds >= 0 ? seconds: seconds + 1
                },
                Milliseconds: Milliseconds
            }; 
          //console.log(ResultJson)
            let year=ResultJson.days.days+'天'+ this.p(ResultJson.days.hours)+':'+ this.p(ResultJson.days.minutes)+':'+ this.p(ResultJson.days.seconds)
           this.$emit('restimeyear',year);
            return year;

  },
   p(s) {
		return s < 10 ? '0' + s: s;
	},
    // 获取求解日志
  getlog(){
         let params = {
            transCode: "C00006",
            pid: this.projectId,
             lesseeId: this.$store.getters.lesseeId
         
          };
           request(params)
        .then((res) => {
          console.log(res);
            })
  },

  //获取历史数据每一条
  historydata(){
 let params = {
            transCode: "C00007",
            pid: this.projectId,
             lesseeId: this.$store.getters.lesseeId
         
          };
           request(params)
        .then((res) => {
          console.log(res)
            })
  },
    // websocket
    getwebsocket() {
     // 初始化weosocket
     this.numlist=[];
     this.option.series=[];
     this.convergeDate.value=[];
      const wsuri = "ws://192.168.0.43:8031/websocket?projectId="+this.projectId;
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen(e) {
          
      //连接建立之后执行send方法发送数据this.newlog();
      // if(this.lsolverState=='1'||this.numzhexian=='1'){
           this.getlog();
           this.historydata()
            // }
    },
    websocketonerror() {
      //连接建立失败重连
      this.websock.close();
    },
    websocketonmessage(e) {
      //数据接收
   try{
            const redata = JSON.parse(e.data);
            if(typeof redata==='object'&& redata){
            
              if(redata.type == "log"){
                 this.$emit('getthislog',redata.stats+redata.value);
              }
            if (redata.type == "iter") {
               this.convergeDateLoad(redata.value);
               //获取运行多少步了
                const lines = redata.value;
                 var patiter = /^ iter /;
                  if (patiter.exec(lines) !== null) {
              const onelines = kgReplace(lines.trim()).split(" ")
                .map((str) => str.trim());
              this.s1= onelines.slice(1,2).map((str) => Number(str));
            }
               this.timedata(redata.startTime,redata.time,this.s1[0]);
            }
              }
            }catch(error){
                return false;
            }
    },
    websocketsend(Data) {
      //数据发送
      this.websock.send(Data);
    },
    websocketclose(e) {
      //关闭
      Message({
        type: "error",
        message: "websock断开连接",
      });

      this.websock.close();
      
    },
    convergeDateLoad(data) {
      const lines = data;
      if(this.numlist.includes(lines)){
      }else{
        this.numlist.push(lines);
          var patIter = /^ Iter /;
      var patiter = /^ iter /;
     if (patIter.exec(lines) !== null) {
        const onelines = kgReplace(lines.trim())
          .split(" ")
          .map((str) => str.trim());
        let VARIABLES = onelines.slice(1);
        this.convergeDate.VARIABLES=VARIABLES;
        this.HighchartsData();
      }
      if (patiter.exec(lines) !== null) {
        const onelines = kgReplace(lines.trim()).split(" ")
          .map((str) => str.trim());
        let data = onelines.slice(2).map((str) => Number(str));
        let num= onelines.slice(1,2).map((str) => Number(str));
        this.convergeDate.value.push(
          onelines.slice(2).map((str) => Number(str))
        );
        
        for (var i in this.convergeDate.VARIABLES) {
            var series = this.chart.series[i];
            series.addPoint([Number(onelines[1]),data[i]]);
        }
      }
     
      } 
    },

    activeLastPointToolip(chart) {
      var points = chart.series[0].points;
      chart.tooltip.refresh(points[points.length - 1]);
    },
    HighchartsData() {
      let _this = this;
      // let option={
      //   title: {
      //     text: "HCFD",
      //   },
      //   credits:{
      //     enabled:false,
      //   },
      //   chart: {
      //     plotBackgroundColor: "rgba(255,255,255,0)",
      //     // borderWidth: 1,
      //     backgroundColor: "rgba(255,255,255,0)",
      //   },
      //   yAxis: {},
      //   xAxis: {},
      //   plotOptions: {
      //     series: {
      //       lineWidth: 2,
      //       label: {
      //         connectorAllowed: false,
      //       },
      //       marker: {
      //         radius: 5,
      //       },
      //       pointStart: 1,
      //     },
      //   },
      //   tooltip: {},
       
                
      //   legend: {
      //             layout: "horizontal",
      //             align: "center",
      //             verticalAlign: "bottom",
      //             itemStyle:{'color':"#b6b6b6" }
      //           },
      //   series: [
      //   ],
      // }
       for (var i in _this.convergeDate.VARIABLES) {
          var obj = {
            name: "",
            data: [0, 0],
            color: "",
            display: true,
          };
          obj.name = _this.convergeDate.VARIABLES[i];
        _this.option.series.push(obj);
      
        }

     _this.option.title.text=this.name;
      _this.chart = Highcharts.chart("container",_this.option);
    },
  
  },
  
};
</script>
<style lang="scss" scoped>
// .x-bar{
//   margin-top: 120px;
// }
</style>