<template>
     <div class="dialog-footer">
                <el-button :icon='CirclePlus' type="primary" @click="openAddDialog">新增</el-button>
                <el-button :icon='Delete' type="danger"  plain :disabled='!multipleSelection.length' @click="deleteSelectedRows">删除</el-button>
    </div>
      <div class="table-container">
            <el-table :data="tableData"  
                  :header-cell-style="{ textAlign: 'center',backgroundColor: '#003078',color: '#fff' } " 
                  :cell-style="{ textAlign: 'center' }" 
                  style="width: 100%"  
                  :style="{ height: '250px',maxHeight: '400px',overflow:'hidden'}"
                  @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="sort" label="序号" width="60" />
                    <el-table-column prop="type" label="误差类型" min-width="180">
                        <template #default="{ row }">
                            <el-cascader style="min-width: 180px;" 
                                         :options="errorOptions" 
                                         v-model="row.errorType" 
                                         :props="{ checkStrictly: false, emitPath: false }" 
                                         placeholder="请选择误差类型"
                                         @change="handleErrorTypeChange($event, row)"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="脚本类型" min-width="230">
                        <template #default="{ row }">
                            <el-cascader style="min-width: 230px;" 
                                         :options="scriptOptions" 
                                         v-model="row.scriptType" 
                                         :props="{ checkStrictly: false, emitPath: false }" 
                                         placeholder="请选择脚本类型" 
                                        />
                        </template>
                    </el-table-column>
                    <el-table-column label="起止范围" >
                        <el-table-column label="起始" width="150">
                            <template #default="{ row }">
                                <el-row type="flex" :gutter="24">
                                    <el-col :span="12">
                                        <el-select v-model="row.startFlag" placeholder="选择起始值" style="width: 70px;" @change="(value) => handleStartFlagChange(row, value)">
                                            <el-option label="无" :value="2"></el-option>
                                            <el-option label=">=" :value="1"></el-option>
                                            <el-option label=">" :value="0"></el-option>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-input v-model= "row.startValue" style="width: 60px;"  :disabled="isStartValueDisabled[row.sort]"
                                        />
                                    </el-col>
                                </el-row>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束" width="150">
                            <template #default="{ row }">
                                <el-row type="flex" :gutter="24" >
                                    <el-col :span="12">
                                        <el-select v-model="row.endFlag" placeholder="选择结束值" style="width: 70px;" @change="(value) => handleEndFlagChange(row, value)">
                                            <el-option label="无" :value="2"></el-option>
                                            <el-option label="<=" :value="1"></el-option>
                                            <el-option label="<" :value="0"></el-option>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-input v-model= "row.endValue" style="width: 60px;" :disabled="isEndValueDisabled[row.sort]"/>
                                    </el-col>
                                </el-row>
                            </template>
                        </el-table-column>
                        <el-table-column label="单位" width="130">
                            <template #default="{ row }">
                            <el-select v-model="row.conditionType" placeholder="选择单位">
                                <el-option
                                v-for="item in dictStore.getDictData('Condition_Type')"
                                :key="item.id"
                                :label="item.name"
                                :value="Number(item.value)"
                                />
                            </el-select>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column  label="最大误差">
                        <el-table-column prop="maxErrorValue" label="最大误差值" width="100">
                            <template #default="{ row }">
                                <el-input v-model= "row.maxErrorValue" style="width: 70px;"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="误差类型" width="180">
                            <template #default="{ row }">
                            <el-select v-model="row.errorValueType" placeholder="选择误差类型">
                                <el-option
                                 v-for="item in dictStore.getDictData('Error_Value_Type')"
                                :key="item.id"
                                :label="item.name"
                                :value="Number(item.value)"
                                />
                            </el-select>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column label="操作" min-width="150">
                    <template  #default="{ row }">
                        <el-button type="primary" link :icon='CopyDocument' @click="copyRow(row)">复制</el-button>
                        <el-button  type='primary' link :icon='Delete'  @click="deleteRow(row)">删除</el-button>
                    </template>
                    </el-table-column>
            </el-table>
        </div>
</template>

<script setup lang="ts">
  import { type ErrorSystem } from '@/api/device/interface/error';
  import { useDictStore, } from '@/stores/modules/dict'
  import {CirclePlus, Delete, EditPen,CopyDocument} from '@element-plus/icons-vue'
  import { type CascaderOption, type FormItemRule } from 'element-plus';
import { el } from 'element-plus/es/locale';
  import { type PropType, type Ref, ref, watch } from 'vue';
  import { defineEmits } from 'vue';
  const emit = defineEmits(['updateTableData']);
  const multipleSelection = ref<number[]>([])
  const dictStore = useDictStore()
  const isStartValueDisabled = ref<{ [key: number]: boolean }>({});
  const isEndValueDisabled = ref<{ [key: number]: boolean }>({});
  const props = defineProps({
    errorOptions: {
      type: Array as PropType<CascaderOption[]>,
      required: true
    },

    scriptOptions: {
      type: Array as PropType<CascaderOption[]>,
      required: true
    },

    tableData: {
    type: Array as PropType<ErrorSystem.ErrorSystemDetail[]>,
    default: () => []
  }
});


// 定义一个 Map 来存储误差和脚本系统信息
const errSysAndScriptMap = new Map<string, string>([
  ['Freq_Deviation_Freq','FREQ'],//频率偏差/频率---频率
  ['Vol_Deviation_Vol','VRMS'],//电压偏差/电压---电压/相电压有效值
  ['MSQI_V','V_UNBAN'],//三相不平衡/电压---电压/三相电压负序不平衡度
  ['MSQI_CUR','I_UNBAN'],//三相不平衡/电流---电流/三相电流负序不平衡度
  ['Voltage Fluctuation_Voltage Amplitude',''],//电压波动/电压幅值---
  ['Voltage Fluctuation_Duration',''],//电压波动/持续时间---
  ['Short Time Flicker Item','PST'],//闪变/短时间闪变---闪变/短时间闪变
  ['Harmonic_Voltage','V2-50'],//谐波/电压---谐波/谐波电压含有率
  ['Harmonic_Current','I2-50'],//谐波/电流---谐波/谐波电流幅值
  ['Harmonic_Angle','VA2-50'],//谐波/相角---谐波/谐波电压相角
  ['Harmonic_Angle','IA2-50'],//谐波/相角---谐波/谐波电流相角
  ['Harmonic_Power','P2-50'],//谐波/功率---谐波/谐波有功功率
  ['Interharmonic_Voltage','SV_1-49'],//间谐波/电压---谐波/间谐波电压含有率
  ['Interharmonic_Current','SI_1-49'],//间谐波/电流---谐波/间谐波电流幅值
  ['High Frequency Harmonic_Voltage',''],//高频次谐波/电压
  ['High Frequency Harmonic_Current',''],//高频次谐波/电流
  ['Power Item','P'],//功率/功率---功率
  ['Current Item','IRMS'],//电流/电流---电流/电流有效值
  ['Dip & Swell & Short duration interruption_Voltage','MAG'],//暂态/电压幅值/电压---暂态/电压幅值
  ['Dip & Swell & Short duration interruption_Duration','DUR'],//暂态/持续时间/时间---暂态/持续时间
]);

const handleErrorTypeChange = (value: any, row: any) =>{

  // const matchedRow = findRowById(row.errorType, props.errorOptions);//选中误差id找对应结构中的含chilren的code
  // console.log('matchedRow.code',matchedRow.code)
  // const code = errSysAndScriptMap.get(matchedRow?.code || '') || ''; // 确保 code 不为 undefined
  // console.log('code',code)
  // if (code) {
  //   const matchedRow2 = findRowByCode(code, props.scriptOptions);//误差code映射脚本code，找对应脚本结构中含children的id
  //   console.log('matchedRow2',matchedRow2)
  //   if (matchedRow2) {
  //     row.scriptType = matchedRow2.value;
  //   }else{
  //     row.scriptType = '';//如果没有找到匹配的脚本，置空
  //   }
  // }else{
  //   row.scriptType = '';//如果没有找到匹配的脚本，置空
  // }  
}


// 假设 props.errorOptions 是一个数组，每个元素可能包含 children 属性
const findRowById = (id: string, options: any[]): any | null => {
  for (const option of options) {
    if (option.value === id) {
      return option;
    }
    if (option.children && option.children.length > 0) {
      const result = findRowById(id, option.children);
      if (result) {
        return result;
      }
    }
  }
  return null;
};


// 假设 props.errorOptions 是一个数组，每个元素可能包含 children 属性
const findRowByCode = (code: string, options: any[]): any | null => {
  for (const option of options) {
    if (option.code === code) {
      return option;
    }
    if (option.children && option.children.length > 0) {
      const result = findRowByCode(code, option.children);
      if (result) {
        return result;
      }
    }
  }
  return null;
};
 

// 监听 props.tableData 的变化，确保每次数据变化时都重新设置 sort
watch(() => props.tableData, async (newTableData) => {
  for (let i = 0; i < newTableData.length; i++) {
    newTableData[i].sort = i + 1;
    if (newTableData[i].startFlag === 2) {
      newTableData[i].startValue = null; // 设置 startValue 为 null
    }
    if (newTableData[i].endFlag === 2) {
      newTableData[i].endValue = null; // 设置 endValue 为 null
    }
  }
  // 重新设置 isStartValueDisabled 和 isEndValueDisabled,并清空输入框
  props.tableData.forEach(row => {
    isStartValueDisabled.value[row.sort] = row.startFlag === 2;
    
  });
  props.tableData.forEach(row => {
    isEndValueDisabled.value[row.sort] = row.endFlag === 2;
  });
}, { immediate: true });
 

// 处理 startFlag 变化的方法
const handleStartFlagChange = (row: ErrorSystem.ErrorSystemDetail, value: number) => {
  if (value === 2) {
    row.startValue = null; // 清空输入框
    isStartValueDisabled.value[row.sort] = true; // 禁用输入框
  } else {
    isStartValueDisabled.value[row.sort] = false; // 启用输入框
  }
};

// 处理 endFlag 变化的方法
const handleEndFlagChange = (row: ErrorSystem.ErrorSystemDetail, value: number) => {
  if (value === 2) {
    row.endValue = null; // 清空输入框
    isEndValueDisabled.value[row.sort] = true; // 禁用输入框
  } else {
    isEndValueDisabled.value[row.sort] = false; // 启用输入框
  }
};

 //选中
   const handleSelectionChange = (selection: ErrorSystem.ErrorSystemDetail[]) => {
    multipleSelection.value = selection.map(row => row.sort); // 更新选中的行
  };
  //新增
  const openAddDialog = () => {
     // 获取字典数据
     const conditionTypes = dictStore.getDictData('Condition_Type');
     const errorValueTypes = dictStore.getDictData('Error_Value_Type');
      const newRow = {
      sort: props.tableData.length + 1,
      id: '',
      startFlag:2,
      endFlag:2,
      conditionType: conditionTypes.length > 0 ? Number(conditionTypes[3].value) : 0, // 设置默认值为第一个选项的值
      errorValueType:errorValueTypes.length > 0 ? Number(errorValueTypes[0].value) : 0, // 设置默认值为第一个选项的值
      errorSysId: "",
      errorType: "",
      scriptType: "",
      maxErrorValue: 0
  };

  emit('updateTableData', [...props.tableData, newRow]);

};
  
const copyRow = (row: ErrorSystem.ErrorSystemDetail) => {
  // 深拷贝行数据
  const newRow = { ...row };
  const maxNextId = Math.max(...props.tableData.map(item => item.sort), 0);
  newRow.sort = maxNextId + 1;
  emit('updateTableData', [...props.tableData, newRow]);
};
//删除行
const deleteRow = (row:ErrorSystem.ErrorSystemDetail) => {
  const index = props.tableData.indexOf(row);
  if (index !== -1) {
    const newTableData = [...props.tableData];
    newTableData.splice(index, 1);
    emit('updateTableData', newTableData);
  }
};
//批量删除选中行
const deleteSelectedRows = () => {
    const newTableData = props.tableData.filter(row => !multipleSelection.value.includes(row.sort));
    multipleSelection.value = []; // 清空已选择的行
  emit('updateTableData', newTableData);
};


</script>

<style scoped>
.dialog-footer {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px; /* 调整这里的值以增加或减少间距 */
    margin-top: 10px;
}

.el-table th, .el-table td {
  text-align: center; /* 所有单元格文字居中 */
}
.table-container {
  max-height: 400px; /* 根据需要调整高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动条 */
}
</style>