<template>
  <div   v-loading="loading"
      element-loading-text="数据加载中">
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" :model="formData" class="demo-form-inline">
            <el-form-item style="display:none">
              <el-switch
                class="tableScopeSwitch"
                :active-value="2"
                :inactive-value="1"
                @change="handleStatusChange"
                :active-text="quyuname"
                inactive-text="超高压"
                inactive-color="#666666"
                v-model="formData.monitorFlag"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="类型:">
              <el-select
                v-model="formData.statisticalType"
                @change="changeclasss"
                placeholder="请选择统计类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in classificationData"
                  :key="item.id"
                  :label="item.name"
                  :value="{
                    label: item.name,
                    value: item.id,
                    name: item.name,
                    id: item.id,
                    code: item.code,
                    sort: item.sort,
                  }"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域:" >
              <el-select ref="select1"
                v-model="deptName"
                placeholder="请选择所属部门区域"
                style="width: 100%"
              >
                <el-option :value="deptIndex" style="height: auto">
                  <el-tree
                    ref="tree"
                    :data="treeData"
                    node-key="id"
                    accordion
                    :default-expanded-keys="idArr"
                    :props="defaultProps"
                    @node-click="handleNodeClick"
                  >
                    <span class="span-ellipsis" slot-scope="{ node, data }">
                      <span :title="data.name">{{ data.name }}</span>
                    </span>
                  </el-tree>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="电压:">
              <el-select
                v-model="formData.scale"
                multiple
                collapse-tags
                placeholder="请选择电压等级"
                style="width:100%"
              >
                <el-option
                  v-for="item in voltageleveloption"
                  :key="item.id"
                  :label="item.name"
                  :value="{
                    label: item.name,
                    value: item.id,
                    code: item.code,
                    name: item.name,
                    id: item.id,
                    sort: item.sort,
                  }"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="厂家:" >
              <el-select
                v-model="formData.manufacturer"
                multiple
                collapse-tags
                placeholder="请选择终端厂家"
                style="width: 100%"
              >
                <el-option
                  v-for="item in terminaloption"
                  :key="item.id"
                  :label="item.name"
                  :value="{
                    label: item.name,
                    value: item.id,
                    code: item.code,
                    name: item.name,
                    id: item.id,
                    sort: item.sort,
                  }"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="干扰源:" style="display: none;">
              <el-select
                v-model="formData.loadType"
                multiple
                collapse-tags
                placeholder="请选择干扰源类型"
                style="width:100%"
              >
                <el-option
                  v-for="item in interfereoption"
                  :key="item.id"
                  :label="item.name"
                  :value="{
                    label: item.name,
                    value: item.id,
                    code: item.code,
                    name: item.name,
                    id: item.id,
                    sort: item.sort,
                  }"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <timepicker
              ref="fdf"
            :id="id"
            @querfromdata="querfromdata"
            :interval="interval"
            :treenode="treenode"
            :tablename="tablename"
            :name="name"
            :path="path"
            :dataTree="dataTree"
          ></timepicker>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
          <el-tabs style="height:calc(100vh - 127px)"
            type="border-card"
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane :lazy="false" label="数据完整性列表" name="tab1">
              <dataintegrity
                :classvalue="classt"
                :tableData="tableData"
                :loading="loading"
              ></dataintegrity>
            </el-tab-pane>
            <el-tab-pane :lazy="false" label="数据完整性图表" name="tab2">
              <dataintegrityechart
                v-show="eacjartflag && activeName == 'tab2'"
                :classvalue="classt"
                :timeValue="time"
                :timehuanbiValue="ping"
                :xdata="xdata"
                :ydata="ydata"
               
                ref="child"
              ></dataintegrityechart>
            </el-tab-pane>
          </el-tabs>
  </div>
</template>
<script>
import { getappheight, getheight } from "@/assets/commjs/common";
import {guanzhou} from '@/assets/commjs/token'
import api1 from '@/api/pollution/pollution'
import { dicData } from "@/assets/commjs/dictypeData";
import api from "../../../api/integraliy/integraliy";
import timepicker from "@/views/cgy-components/TimePicker/index4";

import dataintegrity from "@/views/cgy-components/dataintegrity";
import dataintegrityechart from "@/views/cgy-components/dataintegrityechart";

export default {
  name: "sjwzx",
  components: {

    timepicker,
    dataintegrity,
    dataintegrityechart,
  },
  watch: {},
  computed: {},
  data() {
    return {
      formInline: {},
      loading: false,
      classt: "Power_Network",
      tablename: "tab1",
      thb: false,
      eacjartflag: true,
      interval: 3,
      treeData: [],
      idArr: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      deptName: "全国",
      deptIndex: "",
      name: "sjwzx",
      path: "/harmonic-boot/harmonic/getIntegrityData",
      asideheight: undefined,
      id: 1,
      title: "区域",
      xdata: [],
      ydata: [],
      classvalue: 0,
      activeName: "tab1",
      treenode: "",
      dataTree: "",
      voltageleve1: "",
      //电压等级
      voltageleveloption: [],
      terminal: "",
      terminaloption: [],
      interfere: "",
      interfereoption: [],
      classificationData: [],
      dictypeData: undefined,
      deptIndex: "",
      formData: {
        //后面需要修改
        deptIndex: "",
        monitorFlag: 2,
        powerFlag: 2,
        loadType: null,
        manufacturer: null,
        searchBeginTime: "",
        searchEndTime: "",
        statisticalType: "",
        scale: null,
      },
      periodBeginTime: "",
      periodEndTime: "",
      timehuanbiValue: [],
      tableData: [],
      ping: "",
      time: "",
      quyuname: undefined,
      vh:null
    };
  },
  created() {
    let data = window.sessionStorage.getItem("sysData");
    let yudata = eval("(" + data + ")");
    let str = yudata.dataReport.split("，");
    this.quyuname = str[1];
    var info = window.sessionStorage.getItem("Info");
    info = eval("(" + info + ")");
    this.formData.deptIndex = info.deptId;
    this.getAreaDept();
    this.getclassificationData();
    this.getVoltage();
    this.getManufacturer();
    this.getLoadType();
  },
  mounted() {
    this.vh = window.sessionStorage.getItem('appheight')-120
  },
  methods: {
     // 算法
     algorithm(name) {
      let pathInfo = this.$router.resolve({
       path:'/algorithm/algorithm',
       query:{
       name: name,
       }
     })
      window.open(pathInfo.href, '算法帮助');
    },
    guanzhou(){
        var data ={
           token:this.$route.query.token
        } 
        api1.guanzhou(data).then(res=>{
            if(res.code=='A0000'){
               return
              }else{
                this.$router.push('/error/massege/403')
              } 
        })
      },
    //切换统计类型
    changeclasss(val) {
      this.classt = val.code;
     
    },
    //时间格式转化
    dateFormat(dateData1, dateData2) {
      var timearr = [];
      var date = new Date(dateData1);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var f = date.getMinutes();
      f = f < 10 ? "0" + f : f;
      var s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      this.formData.searchBeginTime = y + "-" + m + "-" + d;
      timearr.push(this.formData.startTime);
      var date = new Date(dateData2);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var f = date.getMinutes();
      f = f < 10 ? "0" + f : f;
      var s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      this.formData.searchEndTime = y + "-" + m + "-" + d;
      timearr.push(this.formData.endTime);
      return timearr;
    },
    //部门绑定区域触发区域树节点
    handleNodeClick(data, node) {
  
      this.deptName = data.name;
      this.$refs.select1.blur();
      this.deptId = data.id;
      this.formData.deptIndex = data.id;
    },
    formatDate(date) {

    
      date = new Date(Date.parse(date.replace(/-/g, "/"))); //转换成Data();
    
      var y = date.getFullYear();
      
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    },
    //2次组件触发事件
  
    querfromdata(data, timehbValue, interval) {
      this.interval = interval;
      this.loading = true;
      if(this.$refs.fdf.intervald==3){
      let timedate = this.$refs.fdf.timeValue[1]
         let timedate1 = timedate.split('-')
         if(timedate1[2]=='01' || timedate1[2]=='02' || timedate1[2]=='03' ){
          let strTime = this.$refs.fdf.timeValue[0]
                    let strTime1 = this.$refs.fdf.timeValue[1]
                    let str1 = strTime.split('-')
                    let str2 = strTime1.split('-')
                    var now = new Date()
                    let month = now.getMonth()
                    if (month == 0) {
                        month = 12
                        str1[0] = str1[0] - 1
                        str2[0] = str2[0] - 1
                    }
                    if (month < 10) {
                        month = '0' + month
                    }
                    this.formData.searchBeginTime = str1[0] + '-' + month + '-' + str1[2]
          if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
            this.formData.searchEndTime = str2[0]+'-'+month+'-31'
          }else{
            this.formData.searchEndTime = str2[0]+'-'+month+'-30'
          }
        }else{
          this.formData.searchBeginTime = this.$refs.fdf.timeValue[0]
          this.formData.searchEndTime = this.$refs.fdf.timeValue[1]
        }
      }else if(this.$refs.fdf.intervald==4){
        let timedate = this.$refs.fdf.timeValue[1]
         let timedate1 = timedate.split('-')
         if(timedate1[2]=='01' || timedate1[2]=='02' || timedate1[2]=='03' ){
          // 获取前七天的日期
          var previousDates = [];
          for (var i = 6; i >= 0; i--) {
            //var previousDate = new Date(currentDate);
            let strTime =  this.$refs.fdf.timeValue[0]
            var currentDate = new Date(strTime);
            let previousDate = new Date(Date.parse(strTime.replace(/-/g,"/")))
            previousDate.setDate(currentDate.getDate() - i);
            previousDates.push(previousDate);
          }
          // 格式化日期
            var formattedDates = previousDates.map(function(date) {
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString().padStart(2, '0');
            var day = date.getDate().toString().padStart(2, '0');
           
            let d = year + '-' + month + '-' + day;
           // console.log("+++++++++++",d) 
           // 输出前七天的日期数组
           return d
          });
          this.formData.searchBeginTime = formattedDates[0]
          this.formData.searchEndTime = formattedDates[formattedDates.length-1]
        // console.log(formattedDates); 
        }else{
          this.formData.searchBeginTime = this.$refs.fdf.timeValue[0]
          this.formData.searchEndTime = this.$refs.fdf.timeValue[1]
        }
      }else if(this.$refs.fdf.intervald==5){
        let timedate = this.$refs.fdf.timeValue[1]
         let timedate1 = timedate.split('-')
         if(timedate1[2]=='01' || timedate1[2]=='02' || timedate1[2]=='03' ){
        let strTime =  this.$refs.fdf.timeValue[0]
        let currentDate = new Date(Date.parse(strTime.replace(/-/g,"/")))
       // console.log('当前日期（中国标准时间）：', currentDate);
      //  console.log("++++",currentDate)

        // 向前推一天
        currentDate.setDate(currentDate.getDate() - 1);

        // 格式化日期字符串
        const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };
        let strTime2 =  this.$refs.fdf.timeValue[1]
        let currentDate2 = new Date(Date.parse(strTime2.replace(/-/g,"/")))
       // console.log('当前日期（中国标准时间）：', currentDate);
      //  console.log("++++",currentDate)

        // 向前推一天
        currentDate.setDate(currentDate.getDate() - 1);


      
        // 格式化日期字符串
        const formatDate2 = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };
       // console.log('当前日期：', formatDate(new Date())); // 当前日期
      //  console.log('向前推一天：', formatDate(currentDate)); // 一天前的日期
        this.formData.searchBeginTime = formatDate(currentDate)
        this.formData.searchEndTime = formatDate(currentDate2)
      }else {
          this.formData.searchBeginTime = this.$refs.fdf.timeValue[0]
          this.formData.searchEndTime = this.$refs.fdf.timeValue[1]
      }


        //let estr = this.$refs.fff.timeValue[1]
      }else{
          this.formData.searchBeginTime = this.$refs.fdf.timeValue[0]
          this.formData.searchEndTime = this.$refs.fdf.timeValue[1]
      }

      // this.timeValue = data;
      // this.timehuanbiValue = timehbValue;
      // this.periodBeginTime = this.timehuanbiValue[0];
      // this.periodEndTime = this.timehuanbiValue[1];
      // this.ping = this.periodBeginTime + "至" + this.periodEndTime;
      // this.dateFormat(this.timeValue[0], this.timeValue[1]);
      // this.time =
      //   this.formData.searchBeginTime + "至" + this.formData.searchEndTime;
      api.integrityData(this.formData).then((res) => {
        if (res.code == "A0000") {
          if (res.data.length == 0) {
            this.tableData = [];
          } else {
            res.data.forEach((m) => {
              m.id = this.guid();
              m.children.forEach((n) => {
                n.id = this.guid();
                n.children.forEach((d) => {
                  d.id = this.guid();
                  d.children.forEach((p) => {
                    p.id = this.guid();
                  });
                });
              });
            });
            this.tableData = res.data;
            this.loading = false;
          }
        }
      });
      var data = {
        deptIndex: this.formData.deptIndex,
        loadType: this.formData.loadType,
        monitorFlag: this.formData.monitorFlag,
        manufacturer: this.formData.manufacturer,
        searchBeginTime: this.formData.searchBeginTime,
        searchEndTime: this.formData.searchEndTime,
        statisticalType: this.formData.statisticalType,
        scale: this.formData.scale,
        powerFlag: 2,
        periodBeginTime: this.periodBeginTime,
        periodEndTime: this.periodEndTime,
      };
      api.IntegrityIcon(data).then((res) => {
        this.eacjartflag = true;
        if (res.code == "A0000") {
          if(res.data.length==0){
            this.xdata =[]
            this.ydata =[]
            this.$nextTick(() => {
              this.$refs.child.dataintegrity();
            });
            this.loading = false;

          }else{
          var data = res.data
          data.sort((a,b) => {
            return a.type > b.type ? 1 : -1;
          })
          this.xdata =[]
          this.ydata =[]
          for(var i=0;i<data.length;i++){
            this.xdata.push(data[i].type)
            if(data[i].single==3.14159){
              this.ydata.push((data[i].single))
            }else{
              this.ydata.push((data[i].single).toFixed(2))
            }
             
          }
          this.$nextTick(() => {
              this.$refs.child.dataintegrity();
            });
            this.loading = false;
          }
         
          }
        
      });
    },
    //标签切换
    handleClick(tab, event) {
      this.tablename = tab.name;
      this.activeName = tab.name;
      if (tab.name == "tab1") {
        this.thb = false;
        this.eacjartflag = false;
        this.$nextTick(() => {
          this.$refs.child.dataintegrity();
        });
      } else if (tab.name == "tab2") {
        this.thb = true;
        this.eacjartflag = true;
        this.$nextTick(() => {
          this.$refs.child.dataintegrity();
        });
      }
    },
    //开关触发
    handleStatusChange(val) {
      this.formData.monitorFlag = val;
      //this.fiveTreeData()
    },
    //获取区域
    getAreaDept() {
      api.getAreaDept().then((res) => {
        if (res.code == "A0000") {
          var data = res.data;
          data.forEach((element) => {
            this.idArr.push(element.id);
          });
          this.treeData = data;
        }
      });
    },
    //字典获取数据电压等级
    getVoltage() {
      // debugger
      var code = "Dev_Voltage_Stand";
      this.voltageleveloption = dicData(code, []);
      this.formData.scale = this.voltageleveloption;
    },
    //字典获取数据终端厂家
    getManufacturer() {
      //debugger
      var code = "Dev_Manufacturers";
      this.terminaloption = dicData(code, []);
      this.formData.manufacturer = this.terminaloption;
    },
    //字典获取数据干扰源类型
    getLoadType() {
      //debugger
      var code = "Interference_Source";
      this.interfereoption = dicData(code, []);
      this.formData.loadType = this.interfereoption;
    },
    //获取统计类型
    getclassificationData() {
      //debugger
      var code = "Statistical_Type";
      this.classificationData = dicData(code, ["Report_Type",'Load_Type']);
      this.formData.statisticalType = this.classificationData[0];
    },

    //获取数据完整性列表数据
    getQueryData() {
      var data = {
        area: "0",
        comparison: 0,
        interference: [],
        manufacturer: [],
        searchBeginTime: "",
        searchEndTime: "",
        statisticalType: 0,
        voltageLevel: [],
      };
    },
    guid() {
      return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c === "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    //导出文件
    exportExcel() {
      api.getExportIntegrityData(this.formData).then((res) => {
        if (res.code == "A0000") {
          var path = res.data;
          //window.location.href=('/api/harmonic-boot/integrity/exportIntegrityDataExcel?filePath='+path)
          this.getpath(path);
        }
      });
    },
    getpath(path) {
      var fileName = path.substring(path.lastIndexOf("/") + 1, path.length); //获取文件名
      api.getExportIntegrityDataExcel(path).then((res) => {
        var blob = new Blob([res], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        }); //response是返回的数据对象
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.setAttribute("download", fileName);
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
    },
    rest() {
      this.deptName = "全国";
      this.formData = {
        deptIndex: "",
        monitorFlag: 2,
        loadType: null,
        manufacturer: null,
        searchBeginTime: "",
        searchEndTime: "",
        statisticalType: "",
        scale: null,
      };
    },
  },
};
</script>
<style lang="less" scoped>
@import url("../../../styles/common.less");
.main {
  overflow: hidden;
}
::-webkit-scrollbar {
  width: 5px;
  height: 0px;
}
::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #79878769;
}
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 10px;
}
//  ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
//         width: 8px; /*滚动条宽度*/
//         height: 8px; /*滚动条高度*/
//       }
//       ::v-deep .el-table__body-wrapper::-webkit-scrollbar-track {
//         border-radius: 0px; /*滚动条的背景区域的圆角*/
//         background-color: rgba(203, 208, 207, 0.286); /*滚动条的背景颜色*/
//         cursor: pointer;
//       }
//       ::v-deep .el-table__body-wrapper::-webkit-scrollbar-corner {
//         background-color: rgba(202, 207, 206, 0.286);
//         cursor: pointer;
//       }
//       ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
//         border-radius: 4px; /*滚动条的圆角*/
//         background-color: rgba(144, 148, 148, 0.979); /*滚动条的背景颜色*/
//       }
//       ::v-deep .el-tabs--border-card>.el-tabs__content {
//         padding: 10px;
//       }
::v-deep .el-select-dropdown__item,
.el-select-dropdown__item {
  background-color: #fff;
  padding: 0 5px !important;
}
::v-deep .demo-form-inline {
    height: 47px;
    overflow-y: auto;
}
</style>
