<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="物料">
              <j-dict-select-tag type="list" v-model="queryParam.materialId" dictCode="v_bu_material_info,name,id" placeholder="请选择物料" />
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="11" :md="12" :sm="24">
            <a-form-item label="统计时间">
              <j-date placeholder="请选择开始日期" class="query-group-cust" v-model="queryParam.usageTime_begin"></j-date>
              <span class="query-group-split-cust"></span>
              <j-date placeholder="请选择结束日期" class="query-group-cust" v-model="queryParam.usageTime_end"></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" icon="download" @click="handleExportXls('物料消耗统计')" style="margin-left: 8px">导出</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 视图切换区域 -->
    <div class="view-switch">
      <a-radio-group v-model="viewType" button-style="solid">
        <a-radio-button value="list">
          <a-icon type="table" />列表视图
        </a-radio-button>
        <a-radio-button value="chart">
          <a-icon type="bar-chart" />图表视图
        </a-radio-button>
      </a-radio-group>
    </div>

    <!-- 列表视图 -->
    <div v-if="viewType === 'list'">
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
      </a-table>
    </div>

    <!-- 图表视图 -->
    <div v-else class="chart-container">
      <a-spin :spinning="chartLoading">
        <div ref="chartRef" style="width: 100%; height: 500px;"></div>
      </a-spin>
    </div>
  </a-card>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  //导入getAction
  import { getAction } from '@/api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import * as echarts from 'echarts'

  export default {
    name: 'BuMaterialUsage',
    mixins:[JeecgListMixin, mixinDevice],
    data () {
      return {
        description: '物料消耗统计页面',
        viewType: 'list', // 视图类型：list-列表，chart-图表
        chart: null, // echarts实例
        chartLoading: false, // 图表加载状态
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'物料',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'规格型号',
            align:"center",
            dataIndex: 'specification'
          },
          {
            title:'消耗总量',
            align:"center",
            dataIndex: 'totalQuantity',
            sorter: (a, b) => a.totalQuantity - b.totalQuantity
          },
          {
            title:'计量单位',
            align:"center",
            dataIndex: 'unit_dictText'
          },
          {
            title:'消耗次数',
            align:"center",
            dataIndex: 'usageCount'
          },
          {
            title:'最后消耗时间',
            align:"center",
            dataIndex: 'lastUsageTime'
          }
        ],
        url: {
          list: "/material/buMaterialUsage/statistics",
          exportXlsUrl: "/material/buMaterialUsage/exportStatistics",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    mounted() {
      // 初始化图表
      this.initChart();
      // 监听窗口大小变化，重绘图表
      window.addEventListener('resize', this.resizeChart);
    },
    beforeDestroy() {
      // 销毁图表实例
      if (this.chart) {
        this.chart.dispose();
      }
      // 移除窗口大小变化监听
      window.removeEventListener('resize', this.resizeChart);
    },
    methods: {
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'materialId',text:'物料',dictCode:''})
        fieldList.push({type:'date',value:'usageTime',text:'消耗时间'})
        this.superFieldList = fieldList
      },
      // 初始化图表
      initChart() {
        if (!this.$refs.chartRef) return;
        this.chart = echarts.init(this.$refs.chartRef);
        this.updateChart();
      },
      // 更新图表数据
      updateChart() {
        if (!this.chart || !this.dataSource || this.dataSource.length === 0) {
          this.chartLoading = false;
          return;
        }

        this.chartLoading = true;
        try {
          const option = {
            title: {
              text: '物料消耗统计',
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function(params) {
                const data = params[0];
                return `${data.name}<br/>消耗总量：${data.value}`;
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '15%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: this.dataSource.map(item => item.materialName),
              axisLabel: {
                interval: 0,
                rotate: 30
              }
            },
            yAxis: {
              type: 'value',
              name: '消耗总量'
            },
            series: [
              {
                name: '消耗总量',
                type: 'bar',
                data: this.dataSource.map(item => item.totalQuantity),
                itemStyle: {
                  color: '#1890ff'
                }
              }
            ]
          };

          this.chart.setOption(option);
        } catch (error) {
          console.error('图表更新失败:', error);
        } finally {
          this.chartLoading = false;
        }
      },
      // 重绘图表
      resizeChart() {
        if (this.chart) {
          this.chart.resize();
        }
      },
      // 重写父类的loadData方法，在数据加载完成后更新图表
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!");
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = [];
        }
        var params = this.getQueryParams();//查询条件
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records;
            this.ipagination.total = res.result.total;
            // 更新图表
            if (this.viewType === 'chart') {
              this.$nextTick(() => {
                this.initChart();
              });
            }
          }
          if(res.code===510){
            this.$message.warning(res.message)
          }
          this.loading = false;
        })
      }
    },
    watch: {
      // 监听视图类型变化
      viewType(newVal) {
        if (newVal === 'chart' && this.dataSource && this.dataSource.length > 0) {
          this.$nextTick(() => {
            this.initChart();
          });
        }
      }
    }
  }
</script>

<style scoped>
  @import '~@assets/less/common.less';
  .view-switch {
    margin-bottom: 16px;
  }
  .chart-container {
    background: #fff;
    padding: 24px;
    border-radius: 2px;
  }
</style>

