
<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 :span="5">-->
          <!--            <a-form-item label="设备类型">-->
          <!--              <j-dict-select-tag placeholder="请选择设备类型" v-model="queryParam.typeId" dict-code="bu_device_type,type_name,id" @change="selectDeviceType"/>-->
          <!--            </a-form-item>-->
          <!--          </a-col> v-if="noSelectType" mode="multiple" -->
          <a-col :span="5">
            <a-form-item label="设备名称">
              <a-select v-model="queryParam.deviceId" placeholder="请选择需要查询的设备">
                <a-select-option v-for="i in deviceSet" :key="i.deviceId" :value="i.deviceId">
                  {{ i.deviceName+i.deviceCode }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="日期范围">
              <a-range-picker
                v-model="dateRange"
                :placeholder="['开始日期', '结束日期']"
                valueFormat="YYYY-MM-DD"                style="width: 100%" />
            </a-form-item>
          </a-col>
          <!--          <a-col :span="4">-->
          <!--            <a-form-item label="请选择年月">-->
          <!--              <j-month-picker v-model="monthTime" mode="month" placeholder="请选择查询年月"/>-->
          <!--            </a-form-item>-->
          <!--          </a-col>-->
          <a-col :md="6" :sm="8">
            <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="exportExcel">导出</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="myChart0" :style="{height: '600px'}" style="display: inline-block;width: 100%;margin-bottom:24px;"></div>
      </div>
    </div>
    <!-- 查询区域-END -->
  </a-card>
</template>

<script>import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JSelectDevice from '@comp/jeecgbiz/JSelectDevice'
import { getAction, downFile } from '@api/manage'
import FaultStatistics from '@views/statistics/FaultStatistics'
import JMonthPicker from "@comp/jeecg/JMonthPicker";

const DataSet = require('@antv/data-set')
export default {
  name: 'BuDeviceStatisticsName',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    FaultStatistics,
    JSelectDevice,
    JMonthPicker
  },
  data() {
    const startDate = new Date(new Date().setMonth(new Date().getMonth() - 3)).toISOString().slice(0, 10);
    const endDate = new Date().toISOString().slice(0, 10); // 当前日期，格式为 YYYY-MM-DD
    return {
      description: '设备开机率管理页面',
      countSource1: [],
      countSource2: [],
      url: {
        list: "/statistics/buDeviceStatistics/list",
        delete: "/statistics/buDeviceStatistics/delete",
        deleteBatch: "/statistics/buDeviceStatistics/deleteBatch",
        exportXlsUrl: "/device/buDeviceRunTime/exportRuntimeXls",
        importExcelUrl: "/statistics/buDeviceStatistics/importExcel",
        selectDevices: "statistics/buDeviceEnergyStatistics/selectDevices",
        getTypeOperation: "device/buDeviceRunTime/getTypeOperation",
        getDeviceOperation: "device/buDeviceRunTime/getTypeOperation",
        getDevice: "/device/buDeviceOnline/getDevice",
      },
      dictOptions: {},
      noSelectType: false,
      deviceSet: {},
      monthTime: '',
      dateRange: [startDate, endDate]
    }
  },
  created() {
    this.getDevice()
  },
  mounted() {
    this.getAllOperation();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },

  methods: {
    printChart() {
      this.$print(this.$refs.print, {type: "html", targetStyles: ["*"], ignoreElements: ["no-print"]})
    },
    // initDictConfig(){
    // },
    searchQuery() {
      this.loadData(1);
    },
    searchReset1() {
      this.queryParam = {}
      this.monthTime = ''
      this.dateRange = []
      this.getAllOperation();
    },
    getDevice() {
      let param = {};
      getAction(this.url.getDevice, param, 'get').then(res => {
        this.deviceSet = res.result;
      })
    },
    selectDeviceType(value) {
      //通过设备类型id，查询当前类型下所有设备，放入设备选择的集合
      getAction(this.url.selectDevices, {type: value}).then((res) => {
        this.deviceSet = res.result;
        this.noSelectType = true;
      })
    },
    getAllOperation() {
      const params = {};
      // 如果选择了日期范围，则使用日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      } else {
        // 否则使用默认值：2024年1月1日到当前日期
        params.startDate = new Date(new Date().setMonth(new Date().getMonth() - 6)).toISOString().slice(0, 10);
        params.endDate = new Date().toISOString().slice(0, 10);
      }
      getAction(this.url.getDeviceOperation, params, 'get').then(res => {
        this.initChart(res.result, '设备运行时间统计');
      })
    },
    searchQuery1() {
      const params = {};

      // 设置日期参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      } else if (this.monthTime) {
        // 否则使用月份参数
        params.selectMonth = this.monthTime;
      } else {
        // 默认使用当前月份
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        params.selectMonth = `${year}-${month}`;
      }
      if (this.queryParam.deviceId) {
        params.deviceId = this.queryParam.deviceId;
        getAction(this.url.getDeviceOperation, params, 'get').then(res => {
          this.initChart(res.result,'设备运行时间统计');
        })
      }
      else {
        params.deviceId = this.queryParam.deviceId;
        getAction(this.url.getDeviceOperation, params, 'get').then(res => {
          this.initChart(res.result,'设备运行时间统计');
        })
      }
    },
    initChart(data, title) {
      let myChart0 = this.$echarts.getInstanceByDom(document.getElementById("myChart0"));
      if (!myChart0) {
        myChart0 = this.$echarts.init(document.getElementById("myChart0"));
      }
      let xData = [];
      let yData = [];
      if (data) {
        for (var i = 0; i < data["x"].length; i++) {
          xData.push(data["x"][i]);
          yData.push(Math.round(data["y"][i]));
        }
      }
      const myOptions = {
        title: {
          left: 'center',
          text: title
        },
        tooltip: {
          trigger: 'axis',
        },
        xAxis: {
          type: 'category',
          data: xData,
          name: "日期"
        },
        yAxis: {
          type: 'value',
          name: "运行时间/min",
        },
        series: [{
          data: yData,
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              if (params.value != 0) {
                var minutes = params.value;
                var hours = Math.floor(minutes / 60);
                var mins = minutes % 60;
                return hours == 0 ? mins + '分钟' : hours + '小时' + mins + '分钟';
              } else {
                return '';
              }
            }
          }
        }]
      };
      myChart0.setOption(myOptions, true)
    },
    // 导出Excel功能
    exportExcel() {
      // 构造参数对象
      let params = {};

      // 设置日期参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }

      // 设置设备类型ID参数
      if (this.queryParam.typeId) {
        params.deviceId = this.queryParam.deviceId;
      }

      downFile(this.url.exportXlsUrl, params).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), '设备运行时间统计.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '设备运行时间统计.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    }
  }
}
</script>
<style scoped>/*@import '~@assets/less/common.less';*/
</style>