
<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>
          <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 :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="myChart" :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 } from '@api/manage'
import { downFile } from '@api/manage'
import FaultStatistics from '@views/statistics/FaultStatistics'
const DataSet = require('@antv/data-set')
export default {
  name: 'BuDeviceStatisticsType',
  mixins:[JeecgListMixin, mixinDevice],
  components: {
    FaultStatistics,
    JSelectDevice
  },
  data () {
    // 设置默认日期范围：2024年1月1日到当前日期
    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",
        //exportXlsUrl: "/statistics/buDeviceStatistics/exportXls",
        importExcelUrl: "/statistics/buDeviceStatistics/importExcel",
        selectDevices: "statistics/buDeviceEnergyStatistics/selectDevices",
        getTypeOperation: "device/buDeviceRunTime/getTypeOperation",
        getDeviceOperation: "device/buDeviceRunTime/getDeviceOperation",
        getTypePower: "device/buDeviceRunTime/queryDeviceEnergyByTypeAndId",

      },
      dictOptions:{},
      noSelectType:false,
      deviceSet:{},
      dateRange: [startDate, endDate]
    }
  },
  created() {
  },
  mounted() {
    this.getAllOperation();
  },
  computed: {
    importExcelUrl: function(){
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    // initDictConfig(){
    // },
    printChart() {
      this.$print(this.$refs.print,{type: "html",
        targetStyles: ["*"],ignoreElements: ["no-print"]})
      // printJS({
      //   printable: "printable",   // 设置需要打印片段id
      //   type: "html",
      //   targetStyles: ["*"],  // 需要保留的样式，*代表所有
      //   ignoreElements: ["no-print"],  // 需要忽略的元素，id集合
      // });
    },
    searchQuery() {
      this.loadData(1);
    },
    searchReset1(){
      this.queryParam = {}
      this.dateRange = []
      this.getAllOperation();
    },
    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];
      }
      getAction(this.url.getTypeOperation, 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 {
        // 否则使用当前月份作为默认值
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        params.selectMonth = `${year}-${month}`;
      }

      if (this.queryParam.typeId === undefined){
        // 如果没有选择设备类型，调用时仍需要提供deviceType参数，但可以为空
        params.deviceType = "";
        getAction(this.url.getTypeOperation, params, 'get').then(res => {
          this.initChart(res.result,'设备运行时间统计');
        })
      }
      else {
        params.deviceType = this.queryParam.typeId;
        getAction(this.url.getTypeOperation, params, 'get').then(res => {
          this.initChart(res.result,'设备运行时间统计');
        })
      }
    },
    initChart(data,title){
      let myChart = this.$echarts.getInstanceByDom(document.getElementById("myChart"));
      if (!myChart) {
        myChart = this.$echarts.init(document.getElementById("myChart"));
      }
      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 '';
              }
            }
          }
        }]
      };
      myChart.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.deviceType = this.queryParam.typeId;
      }

      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';*/
/* 在外部CSS文件或Vue组件的<style>中 */
@media print {
  .print-container {
    width: 800px !important; /* 修改弹窗宽度 */
    height: 600px !important; /* 修改弹窗高度 */
    color: #2f61ef !important; /* 确保颜色在打印时显示 */
  }
}
</style>