<template>
 <el-dialog
    :title="'应用监控'"
    :visible.sync="visible"
    width="80%"
    @close="cancel"
  >
    <div>
      
    
    
    <el-row :gutter="100">
      <el-col :span="11" :offset="1">
        <h4>CPU使用量</h4>
      </el-col>
    </el-row>
 <el-row type="flex" :gutter="90">
      <el-col :span="22" :offset="1">
        <el-card shadow="hover" body-style="padding:1px">
         <scheduler-attempts :charData="schedulerLatency" :id="'applicationCPU'"></scheduler-attempts>
        </el-card>
      </el-col>
     </el-row>

 <el-row :gutter="100">
      <el-col :span="11" :offset="1">
        <h4>内存使用量</h4>
      </el-col>
    </el-row>

 <el-row type="flex" :gutter="90">
      <el-col :span="22" :offset="1">
        <el-card shadow="hover" body-style="padding:1px">
       <schedu-rate-view  :charData="scheduAttempts" :id="'applicationMermory'" ></schedu-rate-view>
        </el-card>
      </el-col>
     </el-row>

      


<!-- 
<el-row :gutter="100">
      <el-col :span="11" :offset="1">
        <h4>调度延迟</h4>
      </el-col>
    </el-row> -->

     <!-- <el-row type="flex" :gutter="90">
      <el-col :span="22" :offset="1">
        <el-card shadow="hover" body-style="padding:1px">
          <scheduler :charData="schedulerLatency" :id="'serer3'"></scheduler>
        </el-card>
      </el-col>
     </el-row> -->
    </div>
 </el-dialog>
</template>

<script >
import scheduler from '../schedulerLatencyView.vue';
import  schedulerAttempts from'../schedulerScheduleLattempts.vue';
import   scheduRateView  from '../scheduRateView.vue';


export default{
  data(){
return{
  visible: true,
  applicationName:"",//用于保存应用名称,
  applicationNameVisible: false

}
  },
    components:{
      scheduler,
      schedulerAttempts,
      scheduRateView
    },
    computed:{

     //这里处理的为CPU使用量，忽略函数名称
    schedulerLatency(){
     var cpuUtil = [];
      const physical = this.$store.state.monitor.applicationMonitor;
         cpuUtil.splice(0, cpuUtil.length); //清零
       if(physical.pod_cpu_usage){

           physical.pod_cpu_usage.forEach((test) => {
        var time1 = this.formatTime(test[0]);
        var socre =this.formPointNumber(test[1]);
        cpuUtil.push({ name: time1, value: socre });
      });
       }
      return cpuUtil;
    },
//这里为内存使用量，pod_memory_usage_wo_cache


   scheduAttempts(){

     var cpuUtil = [];
      const physical = this.$store.state.monitor.applicationMonitor;

         cpuUtil.splice(0, cpuUtil.length); //清零
       if(physical.pod_memory_usage_wo_cache){
           physical.pod_memory_usage_wo_cache.forEach((test) => {
        var time1 = this.formatTime(test[0]);
        var socre =this.formPointNumber(test[1]);
        cpuUtil.push({ name: time1, value: socre });
      });

       }
      return cpuUtil;
    },
    //scheduler_schedule_attempt_rate  调度速率
    scheduRate(){
      var cpuUtil = [];
      const physical = this.$store.state.monitor.schedulerMonitor;

         cpuUtil.splice(0, cpuUtil.length); //清零
       if(physical.scheduler_schedule_attempt_rate){
   
           physical.scheduler_schedule_attempt_rate.forEach((test) => {
        var time1 = this.formatTime(test[0]);
        var socre =this.formPointNumber(test[1]);
        cpuUtil.push({ name: time1, value: socre });
      });

       }
      return cpuUtil;
    },


    },
    created(){
      
    },
     methods: {
   
    init(applicationName) {
      
      this.visible=true;
     this.applicationName=applicationName;
      console.log("输出init中的应用名称");
      console.log(applicationName); 
      this.getApiServerMonitor();  
    },
     cancel() {
      this.visible = false;
    },
    //形成百分数
    formatNumber(num) {
      return num * 100;
    },

    //处理小数点后留两位
    formPointNumber(num) {
      return Math.floor(num * 100) / 100;
    },
    formatNumberBinary() {},
    //设置时间格式
    formatTime(time) {
      var newDate = new Date();
      Date.prototype.toLocaleString = function () {
        return (
          this.getHours() + ":" + this.getMinutes() + ":" + this.getSeconds()
        );
      };
      newDate.setTime(time * 1000);
      return newDate.toLocaleString();
    },
      
    //获取数据
    getApiServerMonitor() {
      var deployParamsName;//部署名称
      var serviceParamsName;//服务名称
      var podParamsName;//容器名称
      const physical = {};
      var nowtime = Math.round(new Date().getTime() / 1000).toString();
      this.applicationName=this.applicationName+"application";
      console.log("应用名称为："+this.applicationName);
    // 先从url中获取到参数值，然后再用该参数去放到下一个Url中获取数据
       // 获取部署名称
        this.$http({
          url: "/kubesphereApi/apis/apps/v1/namespaces/mkcloud/deployments",
          method: "get",
// 
          params: {
            labelSelector:
              `app.kubernetes.io/name=${this.applicationName},app.kubernetes.io/version=v1`,
          },
        }).then(({ data }) => {
      
        console.log("测试获取部署的data");
        console.log(data);
        
        this.deployParamsName=data.items[0].metadata.labels.app;//将部署名称传入到参数中
        this.serviceParamsName=data.items[0].metadata.name;//将服务名称传入到参数中
        console.log(this.deployParamsName);
        console.log(this.serviceParamsName);
        
        //获取容器名称部分
            this.$http({
          url: `/kubesphereApi/api/v1/namespaces/mkcloud/endpoints/${this.deployParamsName}`,
          method: "get",
            }).then(({ data }) => {
        
        console.log("容器名称的data");
         console.log(data);
        if(data.subsets[0].hasOwnProperty('notReadyAddresses')){
          this.podParamsName=data.subsets[0].notReadyAddresses[0].targetRef.name;
        }else{
          this.podParamsName=data.subsets[0].addresses[0].targetRef.name;
        }
        
        console.log(this.podParamsName);
        //等测试以上能获取容器名称后再利用新参数传到下一个,上面成功！
   this.$http({
        url: `/kubesphereApi/kapis/monitoring.kubesphere.io/v1alpha3/namespaces/mkcloud/workloads/deployment/${this.serviceParamsName}/pods`,
        method: "get",
        headers: {
        },
        params: this.$http.adornParams({
          cluster:"default",
          start: nowtime - 900,
          end: nowtime,
          step: "30s",
          times: 60,
          resources_filter:this.podParamsName,
          metrics_filter: 
            "pod_cpu_usage|pod_memory_usage_wo_cache|pod_net_bytes_transmitted|pod_net_bytes_received"
        }),
      }).then(({ data }) => {
        console.log("data");
        console.log(data);
        data.results.forEach((element) => {
           console.log("results");
           console.log(element);
          element.data.result.forEach((test)=>{
          //   console.log("app监控数据result");
           // console.log(test)
            var key;
            if(!test.metric.verb){
              key = element.metric_name;
            }else{
                key = element.metric_name+"_"+test.metric.verb;
            }

          const value = test.values;
               value.forEach((test1) => {
            physical[key] = value;
                });
          });
        });
        //用于测试时打开，现在关闭，需要打开
           
            console.log("physical的数据");
            console.log(physical);
            
        this.$store.dispatch("monitor/setApplicationMonitor", physical);
        //this.physical=physical
           });

      });
      });
    

   
    },

  },

}
</script>

