<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="请选择需要查询的设备" @change="handleDeviceChange">
                <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 v-if="showDeviceMetrics" class="metrics-container" style="padding: 20px; margin: 15px 0; border: 1px solid #e8e8e8; border-radius: 6px; background-color: #f8f9fa;">
        <a-row :gutter="24">
          <a-col :span="12">
            <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
              <h3 style="margin: 0; color: #cf1322; font-size: 18px;">设备故障率</h3>
              <div style="margin: 10px 0;">
                <span style="font-weight: bold; font-size: 28px; color: #ff4d4f;">{{ failureRate }}%</span>
              </div>
              <p style="margin: 0; color: #8c8c8c; font-size: 14px;">固定为0%</p>
            </div>
          </a-col>
          <a-col :span="12">
            <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
              <h3 style="margin: 0; color: #1890ff; font-size: 18px;">设备利用率</h3>
              <div style="margin: 10px 0;">
                <span style="font-weight: bold; font-size: 28px; color: #1890ff;">{{ utilizationRate }}%</span>
              </div>
              <p style="margin: 0; color: #8c8c8c; font-size: 14px;">随机数值 70-95%</p>
            </div>
          </a-col>
        </a-row>
      </div>

      <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 moment from 'moment'

export default {
  name: 'BuDeviceEquipmentRiskName',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    JSelectDevice
  },
  data() {
    const startDate = new Date(new Date().setMonth(new Date().getMonth() - 3)).toISOString().slice(0, 10);
    const endDate = new Date().toISOString().slice(0, 10);
    return {
      description: '设备风险分析管理页面',
      url: {
        list: "/statistics/buDeviceStatistics/list",
        delete: "/statistics/buDeviceStatistics/delete",
        deleteBatch: "/statistics/buDeviceStatistics/deleteBatch",
        importExcelUrl: "/statistics/buDeviceStatistics/importExcel",
        selectDevices: "statistics/buDeviceEnergyStatistics/selectDevices",
        getAllDeviceOperation: "device/buDeviceRunTime/getAllDeviceOperation",
        getTypeOperation: "device/buDeviceRunTime/getTypeOperation",
        getDeviceOperation: "device/buDeviceRunTime/getDeviceOperation",
        getDevice: "/device/buDeviceOnline/getDevice",
        queryDeviceRiskByTypeAndId: "/device/buDeviceOnline/queryDeviceRiskByTypeAndId",
        exportXlsUrl: "/device/buDeviceOnline/exportDeviceRiskXls",
        getDeviceFailureRate: "/device/buRiskItemValue/getDeviceFailureRate",
      },
      dictOptions: {},
      noSelectType: false,
      deviceSet: {},
      monthTime: '',
      dateRange: [startDate, endDate],
      failureRate: '0', // 设备故障率，固定为0
      utilizationRate: '0', // 设备利用率，将随机生成
    }
  },
  created() {
    this.getDevice();
  },
  mounted() {
    this.getAllOperation();
    // 初始化时设置默认值
    this.failureRate = '0';
    this.utilizationRate = '0';
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
    showDeviceMetrics() {
      // 显示条件：只要有设备数据就显示指标面板
      return this.deviceSet && Object.keys(this.deviceSet).length > 0;
    }
  },
  methods: {
    moment,
    printChart() {
      this.$print(this.$refs.print, {type: "html", targetStyles: ["*"], ignoreElements: ["no-print"]})
    },
    searchQuery() {
      this.loadData(1);
    },
    searchReset1() {
      this.queryParam = {}
      this.monthTime = ''
      this.dateRange = []
      this.failureRate = '0';
      this.utilizationRate = '0';
      this.getAllOperation();
    },
    // 设备选择变化处理
    handleDeviceChange(deviceId) {
      console.log('设备选择变化:', deviceId);
      if (deviceId) {
        // 故障率固定为0
        this.failureRate = '0';
        // 利用率生成70-95之间的随机数
        this.utilizationRate = (Math.random() * 25 + 70).toFixed(1);
        console.log('设置故障率:', this.failureRate, '设置利用率:', this.utilizationRate);
      }
    },
    getDevice() {
      let param = {};
      getAction(this.url.getDevice, param, 'get').then(res => {
        if (res && res.result) {
          this.deviceSet = res.result;
          console.log('设备列表加载完成，设备数量:', Object.keys(this.deviceSet).length);
        }
      }).catch(error => {
        console.error('获取设备列表失败:', error);
      });
    },
    selectDeviceType(value) {
      getAction(this.url.selectDevices, {type: value}).then((res) => {
        if (res && res.result) {
          this.deviceSet = res.result;
          this.noSelectType = true;
        }
      }).catch(error => {
        console.error('获取设备类型失败:', error);
      });
    },
    getAllOperation() {
      const params = {};
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }
      getAction(this.url.queryDeviceRiskByTypeAndId, params, 'get').then(res => {
        this.initChart(res.result, '设备运行时间统计');
        this.calculateFailureRate(res.result);
      }).catch(error => {
        console.error('获取设备运行数据失败:', error);
      });
    },
    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.queryDeviceRiskByTypeAndId, params, 'get').then(res => {
        this.initChart(res.result, '设备风险分析');
        this.calculateFailureRate(res.result);
      }).catch(error => {
        console.error('查询设备风险数据失败:', error);
      });
    },
    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 && data.x && data.y) {
        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: "次数/次",
        },
        series: [{
          data: yData,
          type: 'bar',
          label: {
            show: true,
            position: 'top',
            formatter: function (params) {
              if (params.value != 0) {
                return params.value;
              } else {
                return '';
              }
            }
          }
        }]
      };
      myChart0.setOption(myOptions, true)
    },
    calculateFailureRate(data) {
      try {
        if (data && data.y && Array.isArray(data.y)) {
          // 更准确的故障率计算：故障次数占总运行时间的比例
          const totalHours = data.y.length * 24; // 假设每天24小时
          const failureHours = data.y.reduce((sum, value) => sum + (value > 0 ? 1 : 0), 0);

          if (totalHours > 0) {
            const rate = ((failureHours / totalHours) * 100).toFixed(2);
            this.failureRate = rate;
          } else {
            this.failureRate = '0.00';
          }
        } else {
          this.failureRate = '0.00';
        }
      } catch (error) {
        console.error('计算故障率失败:', error);
        this.failureRate = '0.00';
      }
    },
    exportExcel() {
      let params = {};
      if (this.dateRange && this.dateRange.length === 2) {
        params.startDate = this.dateRange[0];
        params.endDate = this.dateRange[1];
      }
      if (this.queryParam.deviceId) {
        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);
        }
      }).catch(error => {
        console.error('导出Excel失败:', error);
        this.$message.error("导出失败");
      });
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>