<template>
    <div>
        <el-collapse v-model="activeNames">
            <el-collapse v-model="activeNames">
                <el-collapse-item title="电压波动/闪变评估结果" :name="1">
                    <div class="flickerWaves">
                        <vxe-table
                            :data="undulation"
                            height="110px"
                            v-bind="defaultAttribute"
                            :cell-class-name="getCellClassName"
                            style="width: 50%"
                        >
                            <vxe-column title="冲击负荷数量" field="inPactLoadNum" />
                            <vxe-column title="电压波动" field="data" />
                            <vxe-column title="国标限值" field="limitData" />
                            <vxe-column title="判断">
                                <template #default="{ row }">
                                    <span v-if="!row.limitData || row.limitData === ''"></span>
                                    <el-tag v-else-if="row.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-table>
                        <vxe-table
                            :data="flicker"
                            height="110px"
                            v-bind="defaultAttribute"
                            :cell-class-name="getCellClassName"
                            style="width: 50%"
                        >
                            <vxe-column title="冲击负荷数量" field="inPactLoadNum" />
                            <vxe-column title="闪变" field="data" />
                            <vxe-column title="国标限值" field="limitData" />
                            <vxe-column title="判断">
                                <template #default="{ row }">
                                    <span v-if="!row.limitData || row.limitData === ''"></span>
                                    <el-tag v-else-if="row.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-table>
                    </div>
                </el-collapse-item>
                <el-collapse-item title="电压偏差评估结果" :name="2">
                    <vxe-table
                        :data="voltageDeviation"
                        height="330px"
                        :merge-cells="mergeCells"
                        v-bind="defaultAttribute"
                        :cell-class-name="getCellClassName2"
                        style="width: 100%"
                    >
                        <vxe-column field="name" width="80px">
                            <template #default="{ row }">
                                <div class="textName">{{ row.name }}</div>
                            </template>
                        </vxe-column>
                        <vxe-colgroup title="用户无功设备情况">
                            <vxe-column field="name1" title="用户项目负载/出力(%)" min-width="160px" />
                        </vxe-colgroup>
                        <vxe-colgroup title="用户无功设备不运行">
                            <vxe-column field="capOff.percent" title="百分比(%)" min-width="90px" />
                            <vxe-column field="capOff.voltagePercent" title="有名值(%)" min-width="90px" />
                            <vxe-column field="capOff.capUP" title="上限值(%)" min-width="90px" />
                            <vxe-column field="capOff.capDown" title="下限值(%)" min-width="90px" />
                            <vxe-column title="判断" min-width="80px">
                                <template #default="{ row }">
                                    <span v-if="!row.capOff || !row.capOff.percent"></span>
                                    <el-tag v-else-if="row.capOff.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-colgroup>
                        <vxe-colgroup title="用户无功设备全部运行">
                            <vxe-column field="capOn.percent" title="百分比(%)" min-width="90px" />
                            <vxe-column field="capOn.voltagePercent" title="有名值(%)" min-width="90px" />
                            <vxe-column field="capOn.capUP" title="上限值(%)" min-width="90px" />
                            <vxe-column field="capOn.capDown" title="下限值(%)" min-width="90px" />
                            <vxe-column title="判断" min-width="80px">
                                <template #default="{ row }">
                                    <span v-if="!row.capOff || !row.capOff.percent"></span>
                                    <el-tag v-else-if="row.capOn.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-colgroup>
                    </vxe-table>
                </el-collapse-item>
                <el-collapse-item title="三相电压不平衡评估结果" :name="3">
                    <vxe-table
                        :data="imbalance"
                        height="110px"
                        v-bind="defaultAttribute"
                        :cell-class-name="getCellClassName"
                        style="width: 100%"
                    >
                        <vxe-column title="估算方式" field="name" />
                        <vxe-column title="负序电压不平衡度(%)" field="data" />
                        <vxe-column title="国标限值(%)" field="limitData" />
                        <vxe-column title="判断">
                            <template #default="{ row }">
                                <span v-if="!row.data || row.data === ''"></span>
                                <el-tag v-else-if="row.isQualified" type="success">合格</el-tag>
                                <el-tag v-else type="warning">不合格</el-tag>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </el-collapse-item>
                <el-collapse-item title="谐波电流/电压评估结果" :name="4">
                    <div class="flickerWaves" style="height: 520px">
                        <vxe-table :data="harmonicCurrents" height="520px" v-bind="defaultAttribute"    :cell-class-name="getCellClassName3" style="width: 50%">
                            <vxe-column title="谐波次数" field="name" width="90px"/>
                            <vxe-colgroup title="电容器谐波电流评估值(A)">
                                <vxe-column field="notInvested" title="未投入" />
                                <vxe-column field="hasInvested" title="已投入" />
                            </vxe-colgroup>
                            <vxe-column title="国标限值(%)" field="limitData" />
                            <vxe-column title="判断">
                                <template #default="{ row }">
                                    <span v-if="!row.limitData || row.limitData === ''"></span>
                                    <el-tag v-else-if="row.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-table>
                        <vxe-table
                            :data="harmonicVoltage"
                            height="520px"
                            v-bind="defaultAttribute"
                            :cell-class-name="getCellClassName3"
                            style="width: 50%"
                        >
                            <vxe-column title="谐波次数" field="name" width="90px"/>
                            <vxe-colgroup title="电容器谐波电压评估值(%)">
                                <vxe-column field="notInvested" title="未投入" />
                                <vxe-column field="hasInvested" title="已投入" />
                            </vxe-colgroup>
                            <vxe-column title="国标限值(A)" field="limitData" />
                            <vxe-column title="判断">
                                <template #default="{ row }">
                                    <span v-if="!row.limitData || row.limitData === ''"></span>
                                    <el-tag v-else-if="row.isQualified" type="success">合格</el-tag>
                                    <el-tag v-else type="warning">不合格</el-tag>
                                </template>
                            </vxe-column>
                        </vxe-table>
                      
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-collapse>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import {getResult} from '@/api/advance-boot/assess'
// 定义 props
const props = defineProps({
  nodeId: {
    type: [String, Number],
    default: null
  }
})

const activeNames = ref([1, 2, 3, 4, 5, 6, 7])
// 波动
const undulation = ref([
    {
        inPactLoadNum:'',
        data:'',
        limitData:'',
    }
])
// 闪变
const flicker = ref([
    {
        inPactLoadNum:'',
        data:'',
        limitData:'',
    }
])
// 电压偏差
const voltageDeviation = ref([
    {
        name: '电网高峰负荷',
        name1: '100',
        capOff: {}, // 不投入状态数据
        capOn: {}   // 全部投入状态数据
    },
    {
        name: '电网高峰负荷',
        name1: '60',
        capOff: {}, // 不投入状态数据
        capOn: {}   // 全部投入状态数据
    },
    {
        name: '电网高峰负荷',
        name1: '0',
        capOff: {},
        capOn: {}
    },
    {
        name: '电网低谷负荷',
        name1: '100',
        capOff: {},
        capOn: {}
    },
    {
        name: '电网低谷负荷',
        name1: '60',
        capOff: {},
        capOn: {}
    },
    {
        name: '电网低谷负荷',
        name1: '0',
        capOff: {},
        capOn: {}
    }
])
// 三相电压
const imbalance = ref([
    {
        name: '严格估算',
        data: '',
        limitData: ''
    },
    {
        name: '一般估算',
        data: '',
        limitData: ''
    }
])
// 谐波电压
const harmonicVoltage:any = ref([])
// 谐波电流
const harmonicCurrents:any = ref([])
// 合并单元格
const mergeCells = ref([
    { row: 0, col: 0, rowspan: 3, colspan: 1 },
    { row: 3, col: 0, rowspan: 3, colspan: 1 }
])
// 添加单元格class
const getCellClassName = ({ row, columnIndex }: { row: any; columnIndex: number }) => {
    if (row.isQualified === false && columnIndex == 1) {
        return 'custom-cell-bg' // 为 Alice 的单元格添加背景
    }
    return ''
}

//谐波判判合格
const getCellClassName3 = ({ row, column, columnIndex }: { row: any; column: any; columnIndex: number }) => {
    if (column.field === 'notInvested') {
        if (row.isNotQualified == false && columnIndex == 0) {
        return 'custom-cell-bg' // 为 Alice 的单元格添加背景
        }
    }
   
    if (row.isHasQualified == false&& columnIndex == 1) {
        return 'custom-cell-bg' // 为 Alice 的单元格添加背景
    }
    return ''
}
//电压偏差判合格
const getCellClassName2 = ({ row, column, columnIndex }: { row: any; column: any; columnIndex: number }) => {
    // 用户无功设备不运行 - 百分比列
    if (column.field === 'capOff.percent') {
            if (row.capOff && row.capOff.isQualified === false) {
                return 'custom-cell-bg';
            }
        }
        
        // 用户无功设备全部运行 - 百分比列
        if (column.field === 'capOn.percent') {
            if (row.capOn && row.capOn.isQualified === false) {
                return 'custom-cell-bg';
            }
        }
    return ''
}


const emit = defineEmits<{
  (e: 'data-status', status: boolean): void
  (e: 'data-loaded'): void 
}>()

// 监听 nodeId 变化并执行相应操作
watch(() => props.nodeId, async (newId) => {
  if (newId) {
        // 重置电压偏差数据到初始状态
        resetVoltageDeviationData();
        // 重置三相电压不平衡数据到初始状态
        resetImbalanceData();
        // 重置谐波数据
        initializeHarmonicVoltage();
        initializeHarmonicCurrents();

        // 确保谐波次数已初始化
        if (harmonicVoltage.value.length === 0) {
        for (let i = 2; i <= 50; i++) {
            harmonicVoltage.value.push({
            name: i
            });
        }
        }
        
        if (harmonicCurrents.value.length === 0) {
        for (let i = 2; i <= 50; i++) {
            harmonicCurrents.value.push({
            name: i
            });
        }
        }
        
    getResult({}, newId).then(res => { 
        if(res.data == null){
           emit('data-status', false);// 通知父组件无数据
           resetAllTableData();
           return
        }
        emit('data-status', true);
        // 处理电压波动数据 - 确保是数组
        if (res?.data?.fluc) {
            if (Array.isArray(res.data.fluc)) {
            undulation.value = res.data.fluc;
            } else {
            // 如果是单个对象，包装成数组
            undulation.value = [res.data.fluc];
            }
        } else {
            // 提供默认值
            undulation.value = [{
            inPactLoadNum: '',
            data: '',
            limitData: ''
            }];
        }

        // 处理闪变数据
        if (res?.data?.plt) {
            flicker.value = Array.isArray(res.data.plt) ? res.data.plt : [res.data.plt];
        } else {
            flicker.value = [{
            inPactLoadNum: '',
            data: '',
            limitData: ''
            }];
        }

        // 处理电压偏差数据
        if (res?.data?.capOff || res?.data?.capOn) {
            let capOffData: string|any[] = [];
            let capOnData: string|any[] = [];
            
            if (res.data.capOff) {
                capOffData = Array.isArray(res.data.capOff) ? res.data.capOff : [res.data.capOff];
            }
            
            if (res.data.capOn) {
                capOnData = Array.isArray(res.data.capOn) ? res.data.capOn : [res.data.capOn];
            }
            
            // 合并数据并保持原有结构
            voltageDeviation.value = voltageDeviation.value.map((item, index) => {
                const capOffItem = capOffData[index] || {};
                const capOnItem = capOnData[index] || {};
                
                return {
                    ...item,
                    capOff: capOffItem,
                    capOn: capOnItem
                };
            });
        
            // 动态调整合并单元格
            const totalDataLength = Math.max(capOffData.length, capOnData.length);
            updateMergeCellsConfiguration(totalDataLength);
        }
      
        /// 处理三相电压不平衡数据
        if (res?.data?.unblance) {
        const unbalanceData = Array.isArray(res.data.unblance) ? res.data.unblance : [res.data.unblance];
        
        // 保持预定义结构，合并新数据
        imbalance.value = imbalance.value.map((item, index) => ({
            ...item,
            ...(unbalanceData[index] || {})
        }));
        }
      
        // 处理谐波数据
        if (res?.data?.harmV) {
                const harmVData = Array.isArray(res.data.harmV) ? res.data.harmV : [res.data.harmV];
            
                // 按索引将API数据与已有的谐波次数合并
                harmonicVoltage.value = harmonicVoltage.value.map((item, index) => {
                    const apiData = harmVData[index];
                    return apiData ? { ...item, ...apiData } : item;
                });
        }
        if (res?.data?.harmI) {  const harmIData = Array.isArray(res.data.harmI) ? res.data.harmI : [res.data.harmI];

                // 按索引将API数据与已有的谐波次数合并
                harmonicCurrents.value = harmonicCurrents.value.map((item, index) => {
                    const apiData = harmIData[index];
                    return apiData ? { ...item, ...apiData } : item;
                });
        }
    })
     // 等待 DOM 更新后延迟触发
    await nextTick()
    setTimeout(() => {
        emit('data-loaded')
    }, 1000) // 3秒延迟
}
}, { immediate: true });

// 添加重置所有表格数据的函数
function resetAllTableData() {
  // 重置电压波动数据
  undulation.value = [];
  
  // 重置闪变数据
  flicker.value = [];
  
  // 重置电压偏差数据到初始状态
  voltageDeviation.value = []
  
  // 重置三相电压不平衡数据到初始状态
  imbalance.value = []
  // 重置谐波数据
  harmonicVoltage.value = [];
  harmonicCurrents.value = []; 

}

// 重置电压偏差数据到初始状态
function resetVoltageDeviationData() {
  voltageDeviation.value = [
    {
      name: '电网高峰负荷',
      name1: '100',
      capOff: {}, // 不投入状态数据
      capOn: {}   // 全部投入状态数据
    },
    {
      name: '电网高峰负荷',
      name1: '60',
      capOff: {}, // 不投入状态数据
      capOn: {}   // 全部投入状态数据
    },
    {
      name: '电网高峰负荷',
      name1: '0',
      capOff: {},
      capOn: {}
    },
    {
      name: '电网低谷负荷',
      name1: '100',
      capOff: {},
      capOn: {}
    },
    {
      name: '电网低谷负荷',
      name1: '60',
      capOff: {},
      capOn: {}
    },
    {
      name: '电网低谷负荷',
      name1: '0',
      capOff: {},
      capOn: {}
    }
  ];

  updateMergeCellsConfiguration(6); // 固定为6条数据
}

// 重置三相电压不平衡数据到初始状态
function resetImbalanceData() {
  imbalance.value = [
    {
      name: '严格估算',
      data: '',
      limitData: ''
    },
    {
      name: '一般估算',
      data: '',
      limitData: ''
    }
  ];
}

// 初始化谐波电压数据
function initializeHarmonicVoltage() {
  harmonicVoltage.value = [];
  for (let i = 2; i <= 50; i++) {
    harmonicVoltage.value.push({
      name: i
    });
  }
}

// 初始化谐波电流数据
function initializeHarmonicCurrents() {
  harmonicCurrents.value = [];
  for (let i = 2; i <= 50; i++) {
    harmonicCurrents.value.push({
      name: i
    });
  }
}

// 添加更新合并单元格配置的函数
function updateMergeCellsConfiguration(dataLength) {
  // 根据实际数据长度动态计算合并策略
  const newMergeCells = [];
  
  if (dataLength >= 6) {
    // 如果数据足够，按原来的方式合并（前3行和后3行）
    newMergeCells.push({ row: 0, col: 0, rowspan: 3, colspan: 1 });
    newMergeCells.push({ row: 3, col: 0, rowspan: 3, colspan: 1 });
  } else if (dataLength >= 4) {
    // 如果只有4条数据，前2行和后2行分别合并
    newMergeCells.push({ row: 0, col: 0, rowspan: 2, colspan: 1 });
    newMergeCells.push({ row: 2, col: 0, rowspan: 2, colspan: 1 });
  } else if (dataLength >= 2) {
    // 如果只有2条数据，每行单独合并
    newMergeCells.push({ row: 0, col: 0, rowspan: 1, colspan: 1 });
    newMergeCells.push({ row: 1, col: 0, rowspan: 1, colspan: 1 });
  }
  
  mergeCells.value = newMergeCells;
}


</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
    padding-left: 20px;
    font-size: 16px !important;
    &::before {
        content: '' !important; /* 添加星号 */
    }
    
}
:deep(.el-descriptions__cell) {
    width: 12.5%;
}
:deep(.custom-cell-bg) {
    background-color: var(--el-color-warning-light-7);
}
.flickerWaves {
    // height: 120px;
    display: flex;
}
.textName {
    white-space: pre-line;

    font-weight: 600 !important;
}
</style>
