<template>
  <a-card :bordered="false" style="height: 100vh">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :md="5" :sm="7">
            <a-form-item label="设备名称">
              <a-tree-select placeholder="请选择设备名称"
              v-model="this.deviceName"
              :tree-data="this.treeData"
              tree-default-expand-all
              :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
              @select="handleSelectChange"
              >
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="7">
            <a-form-item label="传感器">
              <a-select
                placeholder="请选择传感器"
                :multiple="true"
                v-model="this.sensorId"
                @change="onMenuChange"
                :filter-option="filterOption"
              >
                <a-select-option v-for="d in sensorDicDatas" :key="d.id" :value="d.id">
                  {{d.name+d.dataUnit}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="7">
            <a-form-item label="日期">
              <a-date-picker
                style="width:100%"
                v-model="this.beginTime"
                :disabled="this.selectFlag"
                :disabledDate="disabledDate"
                @change="onChange"
                @openChange="dateOpenChange"
                :allowClear="false">
                <template slot="dateRender" slot-scope="current, today">
                  <div class="ant-calendar-date" :style="getCurrentStyle(current, today)">
                    {{ current.date() }}
                  </div>
                </template>
              </a-date-picker>
            </a-form-item>
          </a-col>
          <a-col>
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" >查询</a-button>
              <a-button @click="searchReset1" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
<!--       //初始化调用-->
      <BuDipAngleList   v-if="menuKey.includes('倾角')" ref="dipAngleList"></BuDipAngleList>
      <BuAirSmokeList   v-if="menuKey.includes('烟雾')" ref="smokeList"></BuAirSmokeList>
      <BuAirWaterList   v-if="menuKey.includes('水浸')" ref="waterList"></BuAirWaterList>
      <BuAirQualityList v-if="menuKey.includes('空气')" ref="airList" ></BuAirQualityList>
      <BuElectricList   v-if="menuKey.includes('电能表')" ref="electricList" ></BuElectricList>
      <BuVibrationList  v-if="menuKey.includes('振动')" ref="vibrationList" ></BuVibrationList>
      <BuFlowOnlineList  v-if="menuKey.includes('流量')" ref="FlowList" ></BuFlowOnlineList>
      <BuAirNoiseList   v-if="menuKey.includes('噪声')" ref="noiseList" ></BuAirNoiseList>
      <UnderList   v-if="menuKey.includes('PLC')" ref="UnderList" ></UnderList>

  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin';
import JDictSelectTag from '@comp/dict/JDictSelectTag';
import BuAirQualityList from "@views/energy/BuAirQualityList";
import BuElectricList from "@views/energy/BuElectricList";
import BuVibrationList from "@views/energy/BuVibrationList";
import BuAirNoiseList from "@views/energy/BuAirNoiseList";
import BuAirSmokeList from "@views/energy/BuAirSmokeList.vue";
import BuAirWaterList from "@views/energy/BuAirWaterList.vue";
import BuDipAngleList from "@views/energy/BuDipAngleList.vue";
import UnderList from "@views/energy/UnderList.vue";
import BuFlowOnlineList from "@views/energy/BuFlowOnlineList.vue";
import {getAction} from "@api/manage";
const moment = require('moment');
export default {
  name: 'HistoryDataList',
  mixins:[mixinDevice],
  components: {
    BuAirNoiseList,
    BuAirSmokeList,
    BuAirWaterList,
    BuAirQualityList,
    BuElectricList,
    BuVibrationList,
    BuDipAngleList,
    UnderList,
    BuFlowOnlineList,
    JDictSelectTag
  },
  data () {
    return {
      description: 'HistoryDataList',
      url: {
        treeTest: "/device/buDevice/treeTest",
        timeData: "/sensor/buSensorDeviceData/getHistoryTimeDatas",
        sensor: "/sensor/buSensorDeviceData/getSensorDatas",
        queryById:"/sensor/buSensor/queryById",
      },
      treeData:[],
      expandedKeys:[],
      childrenList:[],
      deviceId:'',//1384437889241600001
      deviceName:'',//牵引电机清洗机465010005
      sensorId:'',//1789927499070103554
      sensorName:'',//电能表
      status:'',
      beginTime:'',
      inTime:'',
      outTime:'',
      menuKey: '电能表',
      selectFlag:false,
      timeStyleList:[],//时间后台返回数据 单节落车01 1384437889241600001
      sensorDicDatas:[],

    }
  },
  created() {
    let date = new Date();
    let year = date.getFullYear(); // 年
    let month = date.getMonth() + 1; // 月
    let day = date.getDate(); // 日
    this.beginTime = `${year.toString()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    // this.beginTime = this.selectTime + " 00:00:00";
    this.endTime = this.beginTime + " 23:59:59";
    this.creatMethod()
    // this.getSensorDatas(this.deviceId)
  },
  computed: {
  },
  methods: {
    callback(key) {
      //console.log(key)
    },
    onMenuChange: function (value) {
      this.sensorId = value;
      this.$http.get(this.url.queryById,{params:{id:value}})
        .then(res => {
          this.menuKey = res.result.name
          console.log("res.result.name" + res.result.name)
        })
    },
    onChange(data,dataString){
      this.beginTime = dataString + " 00:00:00";
      this.endTime = dataString + " 23:59:59";
    },
    getCurrentStyle(current, today) {
      var dd = current.format('MM-DD')
      const style = {};
      this.timeStyleList.forEach(e=>{
        if (e===dd) {
          style.border = '2px solid #1890ff';
          style.borderRadius = '50%';
        }
      })
      return style;
    },
    disabledDate(current) {
      var dd = current.format('MM-DD')
      if(!this.timeStyleList.includes(dd)){
        return true;
      }
    },


    dateOpenChange (isShow,data) {
      if(!data){
        var year = this.beginTime.substring(0,4);
        var month = this.beginTime.substring(5,7);
        this.getTimeDatas(year,month);
      }
      if (isShow) {
        setTimeout(() => {
          const year = document.querySelector('.ant-calendar-year-select').innerText.replace('年', '')
          let month = document.querySelector('.ant-calendar-month-select').innerText.replace('月', '')
          console.log("2222222",year)
          this.getTimeDatas(year,month);
          // const dateDom = document.querySelector('.ant-calendar-ym-select')
          const prevYearBtn = document.querySelector('.ant-calendar-prev-year-btn');
          const nextYearBtn = document.querySelector('.ant-calendar-next-year-btn');
          const prevMonthBtn = document.querySelector('.ant-calendar-prev-month-btn');
          const nextMonthBtn = document.querySelector('.ant-calendar-next-month-btn');
          prevYearBtn.addEventListener('click', () => {
            const year = document.querySelector('.ant-calendar-year-select').innerText.replace('年', '')
            let month = document.querySelector('.ant-calendar-month-select').innerText.replace('月', '')
            this.getTimeDatas(year,month);
          })
          nextYearBtn.addEventListener('click', () => {
            const year = document.querySelector('.ant-calendar-year-select').innerText.replace('年', '')
            let month = document.querySelector('.ant-calendar-month-select').innerText.replace('月', '')
            this.getTimeDatas(year,month);
          })
          prevMonthBtn.addEventListener('click', () => {
            const year = document.querySelector('.ant-calendar-year-select').innerText.replace('年', '')
            let month = document.querySelector('.ant-calendar-month-select').innerText.replace('月', '')
            this.getTimeDatas(year,month);
          })
          nextMonthBtn.addEventListener('click', () => {
            const year = document.querySelector('.ant-calendar-year-select').innerText.replace('年', '')
            let month = document.querySelector('.ant-calendar-month-select').innerText.replace('月', '')
            this.getTimeDatas(year,month);
          })
        }, 0)
      }
    },
    getTimeDatas(year,month){
      this.$http.get(this.url.timeData,{params:{deviceId: this.deviceId,name: this.menuKey,sensorId:this.sensorId,year:year,month:month}})
        .then(res => {
          if(res.success){
            this.timeStyleList = res.result;
          }else{
            this.timeStyleList = []
            // this.$message.warning("数据不存在!");
          }
        })
    },

    isSameMonth(date1, date2) {
      return date1.year() === date2.year() && date1.month() === date2.month();
    },
    creatMethod() {
      this.treeTest().then(() => {
        if (this.treeData.length > 0 && this.treeData[0].children && this.treeData[0].children.length > 0) {
          console.log("this.treeData[0].children[0].key" + this.treeData[0].children[0].key);
          console.log("this.treeData[0].children[0].title" + this.treeData[0].children[0].title);

          this.deviceId = this.treeData[0].children[0].key
          this.deviceName = this.treeData[0].children[0].title
          this.getSensorDatas(this.deviceId)
        }
        //this.searchQuery1()
      });
    },
    treeTest(){
      return new Promise((resolve, reject) => {
        getAction(this.url.treeTest).then((res) => {
          if (res) {
            res.forEach(type=>{
              this.childrenList = []
              if(type.children && type.children.length>0){
                type.children.forEach(device=>{
                  this.childrenList.push({title:device.deviceName+device.deviceCode,key:device.id,value: device.id,typeId:device.deviceTypeId})
                })
              }else{
                this.childrenList.push({})
              }
              this.treeData.push({title:type.typeName,key:type.id,value: type.id,children:this.childrenList,selectable:false,})
            })
            resolve();
          }else{}
        })
      });
    },
    handleSelectChange(selectedKeys, event) {
      console.log("event.$options.propsData.dataRef.title",event.$options.propsData.dataRef.title)
      this.deviceName = event.$options.propsData.dataRef.title;
      this.deviceId = event.$options.propsData.dataRef.key;
      this.getSensorDataSelect(this.deviceId);
    },
    getSensorDatas(deviceId){
      this.$http.get(this.url.sensor,{params:{deviceId:deviceId}}).then(res => {
        this.sensorDicDatas = res.result
        this.sensorId = res.result[0].id
        this.sensorName = res.result[0].name
        this.$http.get(this.url.queryById,{params:{id:this.sensorId}})
          .then(res => {
            this.menuKey = res.result.name
            this.searchQuery1()
          })
      })
    },
    getSensorDataSelect(deviceId){
      this.$http.get(this.url.sensor,{params:{deviceId:deviceId}}).then(res => {
          this.sensorDicDatas = res.result
      })
    },
    filterOption(input, option) {
      console.log(option);
      return (
        option.data.attrs.tag.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    searchQuery1(){
      if(this.menuKey.includes('倾角')){
        this.$refs.dipAngleList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.dipAngleList.loadData1(1);
      }else if(this.menuKey.includes('烟雾')){
        this.$refs.smokeList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.smokeList.loadData1(1);
      }else if(this.menuKey.includes('水浸')){
        this.$refs.waterList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.waterList.loadData1(1);
      }else if(this.menuKey.includes('空气')){
        this.$refs.airList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.airList.loadData1(1);
      }else if(this.menuKey.includes('电能表')){
        this.$refs.electricList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.electricList.loadData1(1);
      }else if(this.menuKey.includes('振动')){
        this.$refs.vibrationList.queryParam =
            {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.vibrationList.loadData1(1);
      }else if(this.menuKey.includes('流量')){
        this.$refs.FlowList.queryParam =
          {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.FlowList.loadData1(1);
      }
      else if(this.menuKey.includes('PLC')){
        this.$refs.UnderList.queryParam =
          {deviceId:this.deviceId,code:this.status, sensorId:this.sensorId, beginTime:this.beginTime,endTime:this.endTime,inTime:this.inTime,outTime:this.outTime};
        this.$refs.UnderList.loadData1(1);
      }
    },
    searchReset1(){
      this.selectFlag = false
      this.menuKey ='';
      this.deviceName = '';
      this.deviceId ='';
      this.sensorId='';
      this.beginTime = '';
      this.endTime = '';
      this.status='';
      this.inTime = '';
      this.outTime = '';
      this.createValue ='';
      this.$refs.dipAngleList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.smokeList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.waterList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.airList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.electricList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.vibrationList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.FlowList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
      this.$refs.UnderList.queryParam = {deviceId:'',code:'',sensorId:'',beginTime:'',endTime:'',inTime:'',outTime:''};
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>