<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div ref="print" class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <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="6" :sm="8">-->
<!--            <a-form-item label="设备名称">-->
<!--              <j-select-device placeholder="请选择设备名称" :multiple="false" v-model="queryParam.deviceId" @change="deviceChange"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="4">
            <a-form-item label="传感器">
              <a-select
                placeholder="请选择传感器"
                :multiple="true"
                v-model="this.sensorId"
                @change="numberChange"
                :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 :span="6">
            <a-form-item label="检测项">
              <a-select placeholder="请选择检测项"
                        :multiple="true"
                        v-model="selectedValues"
                        mode="multiple"
                        @change="itemChange"
                        :filter-option="filterOption"
                          >
                <a-select-option v-for="d in itemDatas" :key="d.checkItem" :value="d.checkItem" >
                  {{d.checkItem}}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="7">
            <a-form-item label="日期">
              <a-date-picker
                v-model="selectTime"
                style="width:100%"
                :disabled="this.selectFlag"
                :disabledDate="disabledDate"
                @change="onChange1"
                @openChange="datePanelChange"
                :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 class="no-print" type="primary" @click="searchQuery1">查询</a-button>
              <a-button class="no-print" style="margin-left: 8px" @click="searchReset1">重置</a-button>
              <a-button class="no-print" style="margin-left: 8px"  @click="printChart()">打印</a-button>
              </span>
          </a-col>
        </a-row>
      </a-form>
      <div>
        <div id="myChart" :style="{height: '600px'}" style="display: inline-block;width: 100%;margin-bottom:24px;top: 50px"></div>
      </div>
    </div>
    <!-- 查询区域-END -->

    <bu-sensor-device-data-modal ref="modalForm" @ok="modalFormOk"></bu-sensor-device-data-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BuSensorDeviceDataModal from './modules/BuSensorDeviceDataModal'
  import JSelectDevice from '@comp/jeecgbiz/JSelectDevice'
  import { getAction } from '@api/manage'
  import JSelectSensor from '@comp/jeecgbiz/JSelectSensor'
  import LineSmooth from '../../components/chart/LineSmooth'
  import LineChartMultipleTwo from '@comp/chart/LineChartMultipleTwo'

  export default {
    name: 'BuSensorDeviceDataList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      LineSmooth,
      BuSensorDeviceDataModal,
      JSelectDevice,
      LineChartMultipleTwo,
      JSelectSensor,
    },
    data() {
      return {
        description: '设备传感器数据表管理页面',
        style:{},
        dataSourceChart: [],
        dataSourceSmooth: [],
        // aliasChart: [{field:this.lineNumber,alias:'U相电流监测'}],
        fieldsChart: [].concat(this.lineNumber),
        fieldsSmooth: [].concat(this.lineNumber),
        // 表头
        columns: [
        ],
        url: {
          list: "/sensor/buSensorDeviceData/list",
          delete: "/sensor/buSensorDeviceData/delete",
          deleteBatch: "/sensor/buSensorDeviceData/deleteBatch",
          exportXlsUrl: "/sensor/buSensorDeviceData/exportXls",
          importExcelUrl: "/sensor/buSensorDeviceData/importExcel",
          sensor: "/sensor/buSensorDeviceData/getSensorDatasgg",
          timeData: "/sensor/buSensorDeviceData/getTimeDatas",
          getSensorData: "/sensor/buSensor/getSensorData",
          getLimitValue: "/sensor/buSensor/getLimitValue",
          itemData: "/sensor/buSensor/getItemData",
          treeTest: "/device/buDevice/treeTest",
        },
        lineNumber: [],
        valueNumber: [],
        sensorDicDatas:[],
        createValue: [],
        checkItem: 'U相电压',
        selectFlag:false,
        timeStyleList:[],//时间后台返回数据
        itemDatas:[],
        selectedValues: ['U相电压'], //
        beginTime:'',
        endTime:'',
        selectTime:'',
        treeData:[],
        deviceId:'',//1384437889241600001     1个设备的deviceId
        deviceName:'',//牵引电机清洗机465010005
        sensorId:'',//1789927499070103554
        sensorName:''//电能表
      }
    },
    created() {
      let date = new Date();
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      this.selectTime = `${year.toString()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      this.beginTime = this.selectTime + " 00:00:00";
      this.endTime = this.selectTime + " 23:59:59";
      this.creatMethod()
      // this.treeTest()
      // this.getSensorDatas(this.deviceId)
      // this.numberChange0(this.sensorId)

      // this.getSensorData({beginTime: this.beginTime,endTime:
      //   this.endTime,checkItems: this.checkItem,sensorId:this.sensorId})
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      printChart() {
        this.$print(this.$refs.print,{type: "html",
          targetStyles: ["*"],ignoreElements: ["no-print"]})
        // printJS({
        //   printable: "printable",   // 设置需要打印片段id
        //   type: "html",
        //   targetStyles: ["*"],  // 需要保留的样式，*代表所有
        //   ignoreElements: ["no-print"],  // 需要忽略的元素，id集合
        // });
      },
      creatMethod() {
        this.treeTest().then(() => {
          this.deviceId = this.treeData[0].children[0].key
          this.deviceName = this.treeData[0].children[0].title
          this.getSensorDatas(this.deviceId).then(() =>{
            this.numberChange0(this.sensorId).then(() =>{
              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) {
        this.deviceName = event.$options.propsData.dataRef.title;
        this.deviceId = event.$options.propsData.dataRef.key;
        // this.sensorId='';
        this.getSensorDataSelect(this.deviceId);
      },
      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;
        }
      },
      datePanelChange (isShow,value) {
        if(!value){
          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('月', '')
            this.getTimeDatas(year,month);
            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);
            })
            // const dateDom = document.querySelector('.ant-calendar-ym-select')
            // dateDom.addEventListener('DOMCharacterDataModified', () => {
            //   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)
        }
      },

      searchQuery1() {
        this.getSensorData({beginTime: this.beginTime,endTime:
          this.endTime,checkItems: this.checkItem,sensorId:this.sensorId})
      },
      getSensorData(param){
        getAction(this.url.getSensorData, param, 'get').then((res) => {
          console.log(res.result);
          this.initChart("myChart",res.result,'采集数据');
        })
      },
      initChart(id,data,title){
        let myChart = this.$echarts.getInstanceByDom(document.getElementById(id));
        if (!myChart) {
          myChart = this.$echarts.init(document.getElementById("myChart"));
        }
        let xData= [];
        let com = this.checkItem.split(",");
        if(data!=null){
          for (let a=0; a<data[0]["x"].length; a++){
            xData.push(data[0]["x"][a]);
          }
        }

        function functionCount(data) {
          let ser = [];
          if(data!=null) {
            for (let i = 0; i < data.length; i++) {
              let yData = [];
              for (let j = 0; j < data[i]["x"].length; j++) {
                yData.push(data[i]["y"][j]);
              }
              let item = {name: com[i], data: yData, type: 'line', smooth: true, symbol: 'circle', connectNulls: true}
              // let item = {data: yData, type: 'scatter', symbolSize: 5}
              ser.push(item);
            }
          }
          return ser;
        }

        const myOptions = {
          animation: false,
          tooltip: {
            trigger: 'axis',
          },
          backgroundColor: '#fff',
          title:{
            left:'left',
            text:title
          },
          legend:{
            data: this.selectedValues,
          },
          lineStyle:{
            width: 20
          },
          // dataZoom:[
          //   {
          //     type:'inside',
          //     show:true,
          //     xAxisIndex: [0]
          //   }
          // ],
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 100
            },
            {
              type: 'slider',
              height: 20,
              showDetail: false,
              brushSelect:false,
              start: 10,
              end: 20
            }

          ],
          xAxis: {
            type: 'category',
            data: xData,
          },
          yAxis: {
            type: 'value',
            min: function (value) {
              return Math.floor(value.min - 0.1);
            },
          },
          series: functionCount(data)
        };
        myChart.setOption(myOptions,true)
      },
      numberChange0(value) {
        return new Promise((resolve, reject) => {
          this.sensorId = value;
          this.$http.get(this.url.itemData, {params: {sensorId: value}}).then(res => {
            this.itemDatas = res.result;
            // 在获取到itemDatas后设置默认选中值
            if (res.result && res.result.length > 0) {
              this.selectedValues = ['U相电压'];
              // 同时更新checkItem的值
              this.checkItem = 'U相电压';
            }
            // this.itemDatas = res.result;
            resolve()
          })
        })
      },
      numberChange (value) {
        this.sensorId = value;
        this.$http.get(this.url.itemData,{params:{sensorId: value}})
          .then(res => {
            this.itemDatas = res.result;
          })
        this.clearSelection()
      },
      clearSelection() {
        this.selectedValues = []; // 清空已选择的值
        this.selectTime='';
        this.selectFlag = false;
      },
      itemChange: function (value) {
        this.checkItem = value.join(",");
        this.selectFlag = false;
      },
      getTimeDatas(year,month){
        this.$http.get(this.url.timeData,{params:{deviceId: this.deviceId,sensorId: this.sensorId,year:year,month:month}})
          .then(res => {
            if(res.success){
              this.timeStyleList = res.result;
            }else{
              this.timeStyleList = []
              // this.$message.warning("数据不存在!");
            }
          })
      },
      getSensorDatas(deviceId){
        return new Promise((resolve, reject) => {
          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
              resolve()
            })
        })
      },
      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
        );
      },
      onChange1(date,dateString){
        this.beginTime = dateString + " 00:00:00";
        this.endTime = dateString + " 23:59:59";
        this.selectTime = dateString;
      },
      searchReset1() {
        this.queryParam = {};
        this.sensorId='';
        this.selectTime='';
        this.deviceName = '';
        this.selectedValues =[];
        this.selectFlag = false;
        this.loadData(1);
      },

    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>