<template>
  <Dialog v-model="diaVisible" diaTitle="数据分析" width="90%" height="90%" @close="closeFun">
    <div class="analysis-container">
      <div class="analysis-header">
        <el-button @click="exportPdfFun">{{ $t('通用.导出PDF') }}</el-button>
      </div>
      <div class="analysis-wrap" ref="analysisRef">
        <div class="analysis-chart">
          <EchartCard
            title="指标分析"
            ref="analysisChartRef"
            :charts-id="'chart-1'"
            :bar-type="'scatterChart'"
            :showFilterContent="true"
            @refresh="changeAnalysisChartFun"
          >
            <template #formSlot>
              <el-form :model="filterFromData" label-width="auto">
                <el-form-item label="指标">
                  <el-select
                    class="select-width margin-right-12"
                    v-model="filterFromData.nodeCode"
                    @change="changeparamsFun"
                  >
                    <el-option
                      v-for="item in filterOptions"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
          </EchartCard>
        </div>
        <div class="analysis-table">
          <BaseTable
            ref="paramAnalsisTableRef"
            tableName="PARAMS_ANALYSIS_LIST"
            listTitle="指标分析结果"
            showIndex
            fullHeight
            hidePagination
          >
          </BaseTable>
        </div>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, watch, createApp } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import EchartCard from '@/components/common/echartCard/index.vue';
import paramsAnalysisTooltip from './paramsAnalysisTooltip.vue';
import { ElMessage } from 'element-plus';
import { exportToPdf } from '@/utils/exportPdf';
import dayjs from 'dayjs';

interface Props {
  modelValue: boolean;
  analysisData?: any;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  analysisData: [],
});

// #region 左侧图表
const analysisChartRef = ref();
const filterOptions = ref();
const chartData = ref();
const filterFromData = ref({
  nodeCode: '',
});
const changeparamsFun = () => {
  changeAnalysisChartFun();
};
// 渲染图表
const changeAnalysisChartFun = () => {
  const list = chartData.value.get(filterFromData.value.nodeCode);
  const data = list.map((item: { targetValue: any }, index: number) => {
    return [index + 1, item.targetValue];
  });
  // const data = [ [1, 8.04], [2, 7.58], [3, 6.95], [4, 12] ];
  // const highVal = list[0].highValue;
  // const lowVal = list[0].lowValue;
  const options = {
    dataset: [{ source: data }],
    tooltip: {
      trigger: 'item',
      padding: 0,
      formatter: (p: any) => {
        const index = p.data[0] - 1;
        const tooltipApp = createApp(paramsAnalysisTooltip, { row: list[index] });
        const mountNode = document.createElement('div');
        tooltipApp.mount(mountNode);
        return mountNode.outerHTML;
      },
    },
    xAxis: {
      minInterval: 1,
    },
    yAxis: {
      name: '分析值',
    },
    series: [
      {
        type: 'scatter',
        // datasetIndex: 0,
        // 12.31  dzh  勿删
        // markLine: {
        //   show: true,
        //   symbol: ['none', 'none'], // 去掉两端箭头
        //   lineStyle: {
        //     color: '#67c23a',
        //     width: 1,
        //     type: 'solid',
        //   },
        //   label: {
        //     show: true,
        //     position: 'end', // 标签位置
        //     color: '#67c23a', // 标签颜色
        //     formatter: '{b}', // 显示标记名称
        //   },
        //   data: [
        //     { yAxis: lowVal, name: 'y=' + lowVal },
        //     { yAxis: highVal, name: 'y=' + highVal },
        //   ],
        // },
        // markArea: {
        //   silent: true,
        //   itemStyle: {
        //     color: 'rgba(149, 212, 117, 0.2)',
        //   },
        //   label: {
        //     show: true,
        //     position: 'inside', // 标签位置
        //     color: '#67c23a', // 标签颜色
        //     fontSize: 16, // 标签字体大小
        //     fontWeight: 'bold', // 字体粗细
        //     formatter: '标准区域', // 标签文本
        //   },
        //   data: [[ { yAxis: lowVal }, { yAxis: highVal } ]],
        // },
      },
    ],
  };
  analysisChartRef.value.commonChartRef.disposeEchartsByKey('chart-1');
  analysisChartRef.value.commonChartRef.option = { ...options };
  analysisChartRef.value.commonChartRef.initChart();
};
// #endregion

// #region 右侧表格
const paramAnalsisTableRef = ref();

// 根据nodeCode分组，并计算出targetValue（分析值targetValue  2026.1.6 ldy确认）的平均值作为averageVal
const groupAndCalculateAverage = (data: any) => {
  const groupedData = new Map<string, any[]>();
  const selectOptions: any[] = [];
  data
    .filter((v: { nodeCode: any }) => v.nodeCode)
    .forEach((item: any) => {
      const key = item.nodeCode;
      // item.targetValue = Math.random() * 100; // 测试数据
      if (!groupedData.has(key)) {
        groupedData.set(key, []);
        selectOptions.push({
          label: item.nodeName + '(' + item.nodeCode + ')',
          value: item.nodeCode,
        });
      }
      groupedData.get(key)?.push(item);
    });
  // 计算每组的平均值并构建结果
  const result: any[] = [];
  groupedData.forEach((group: any[]) => {
    const firstItem = group[0]; // 取第一个项目的基础信息
    // 计算 targetValue 的平均值、最大值、最小值
    const arr = group.map((item) => Number(item.targetValue || 0));
    const maxVal = Math.max(...arr);
    const minVal = Math.min(...arr);
    const averageVal =
      group.reduce((sum, item) => sum + Number(item.targetValue || 0), 0) / group.length;

    result.push({
      nodeName: firstItem.nodeName,
      nodeCode: firstItem.nodeCode,
      nodeId: firstItem.nodeId,
      highValue: firstItem.highValue,
      lowValue: firstItem.lowValue,
      averageVal: Number(averageVal.toFixed(2)), // 保留两位小数
      maxVal,
      minVal,
    });
  });
  return [result, selectOptions, groupedData];
};

// #endregion

watch(
  () => props.modelValue,
  (val: boolean) => {
    diaVisible.value = val;
    if (!val) return;
    nextTick(() => {
      const res = groupAndCalculateAverage(props.analysisData);
      // 格式化的表格数据
      paramAnalsisTableRef.value.setDataFun(res[0]);
      // 格式化的指标类型下拉框
      filterOptions.value = res[1];
      // 格式化的原始分组数据
      chartData.value = res[2];
      // 展示图表
      filterFromData.value.nodeCode = filterOptions.value[0].value;
      changeAnalysisChartFun();
    });
  }
);

const emit = defineEmits(['update:modelValue']);
const diaVisible = ref(false);
const closeFun = () => {
  emit('update:modelValue', false);
};

const analysisRef = ref();
const exportPdfFun = () => {
  ElMessage.success('文件正在导出，请稍后');
  exportToPdf(analysisRef.value, `指标分析_${dayjs().format('YYYYMMDDHHmm')}`);
};
</script>

<style lang="scss" scoped>
.analysis-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.analysis-header {
  text-align: right;
  padding-bottom: 10px;
}
.analysis-wrap {
  width: 100%;
  flex: 1;
  height: 0;
  display: flex;
  justify-content: space-between;
  .analysis-chart {
    width: 50%;
    height: 100%;
    .el-form {
      margin-top: 16px;
      margin-right: 16px;
      .el-form-item {
        width: 240px;
      }
    }
  }
  .analysis-table {
    width: calc(50% - 20px);
  }
}
</style>
