<template lang="html">
  <div id="charts">
    <div id="instruct" :style="{width:'100%',height:'100%'}"></div>
  </div>
</template>

<script>
import * as Util from '../../Util'
import co from 'co'
import echarts from 'echarts'
import {HttpResetClass} from 'vue-client'

let getData = function* (self) {
  let load = new HttpResetClass()
  load.load('POST', 'api/af-revenue/sql/manage_homeInstructQuery', {
    data: {
      startDate: self.getStartOfRecentFiveDays() + ' 00:00:00',
      endDate: Util.toStandardDateString() + ' 23:59:59',
      f_orgid: self.orgid,
      condition: '1=1'
    }
  }, {
    resolveMsg: null,
    rejectMsg: null
  }).then((res) => {
    let data = res.data
    // 表型
    let xPro = data.map(x => x.f_meter_brand)
    console.log('表型', xPro)
    let f_total_num = data.map(x => x.f_total_num)
    let f_success_num = data.map(x => x.f_success_num)
    let f_failure_num = data.map(x => x.f_failure_num)
    self.set(xPro, f_total_num, f_success_num, f_failure_num)
  })
}
export default {
  props: {
    orgid: {
      type: String
    }
  },
  data () {
    return {
      texttile: '',
      xc: '',
      resizeHandler: null // 存储resize监听函数，方便销毁
    }
  },
  methods: {
    getStartOfRecentFiveDays (returnRaw = false) {
      const today = new Date()
      const startDate = new Date(today)
      startDate.setDate(today.getDate() - 4)
      if (returnRaw) {
        return startDate
      }
      const year = startDate.getFullYear()
      const month = String(startDate.getMonth() + 1).padStart(2, '0')
      const day = String(startDate.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    set (arrparams, f_total_num, f_success_num, f_failure_num) {
      this.xc = echarts.init(document.getElementById('instruct'))
      this.xc.setOption({
        title: {
          text: '近五天指令执行情况',
          subtext: '数据查询来源',
          x: 'left'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          x: 'center', // 图例居中，避免左侧挤压
          y: 'bottom',
          padding: [0, 0, 10, 0], // 底部预留padding，防止文字截断
          textStyle: {
            fontSize: 12
          },
          data: ['总数', '成功数量', '失败数量']
        },
        toolbox: {
          show: true,
          top: 10, // 工具栏上移，不占用下方空间
          right: 10,
          feature: {
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            restore: {show: true},
            saveAsImage: {show: true}
          }
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            axisLabel: {
              interval: 0,
              rotate: 30, // X轴标签旋转，避免文字重叠
              fontSize: 11, // 缩小X轴文字
              // 文字换行处理（可选，若表型名称过长）
              formatter: function(value) {
                let result = ''
                const len = value.length
                // 每4个字符换一行
                for (let i = 0; i < len; i += 4) {
                  result += value.substring(i, i + 4) + '\n'
                }
                return result.trim()
              }
            },
            data: arrparams
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              fontSize: 11 // 缩小Y轴文字
            }
          }
        ],
        series: [
          {
            name: '总数',
            type: 'bar',
            data: f_total_num,
            markLine: {
              data: [
                {type: 'average', name: '平均值'}
              ]
            }
          },
          {
            name: '成功数量',
            type: 'bar',
            data: f_success_num,
            markLine: {
              data: [
                {type: 'average', name: '平均值'}
              ]
            }
          },
          {
            name: '失败数量',
            type: 'bar',
            data: f_failure_num,
            markLine: {
              data: [
                {type: 'average', name: '平均值'}
              ]
            }
          }
        ]
      })
      // 绑定resize监听，自适应窗口变化
      this.resizeHandler = () => {
        if (this.xc) {
          this.xc.resize()
        }
      }
      window.addEventListener('resize', this.resizeHandler);
    },
    searchdata () {
      let getGen = getData(this)
      co(getGen)
    }
  },
  ready () {
    this.searchdata()
  },
  watch: {
    'startdate' (val) {
      this.searchdata()
    },
    'enddate' (val) {
      this.searchdata()
    },
    'orgid' (val) {
      this.searchdata()
    }
  },
  // 组件销毁时移除监听，避免内存泄漏
  beforeDestroy() {
    if (this.resizeHandler) {
      window.removeEventListener('resize', this.resizeHandler);
    }
    if (this.xc) {
      this.xc.dispose(); // 销毁ECharts实例
    }
  }
}
</script>

<style scoped>
/* 可选：若需要额外样式优化可添加 */
#charts {
  box-sizing: border-box;
}
</style>
