<template>
    <el-dialog  :title="dialogTitle" :model-value="visible" @close="handleCancel" v-bind="dialogBig">
        <el-tabs type="border-card">
            <el-tab-pane label="基础信息">
                <div class="form-grid">
                    <el-form :model="formData" ref='formRuleRef' :rules='rules'>
                        <el-row  :gutter="120" >
                            <el-col :span="9">
                                <el-form-item label="误差体系名称" prop="name">
                                    <el-input v-model='formData.name' placeholder="标准号+年份+设备等级"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item  label="参照标准名称" prop="standard_Name">
                                    <el-input  v-model='formData.standard_Name'/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="7">
                                <el-form-item label="发布时间" prop="standard_Time">
                                    <el-input v-model="formData.standard_Time" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row  :gutter="120" >
                            <el-col :span="9">
                                <el-form-item label="适用设备等级" prop="dev_Level">
                                    <el-select v-model='formData.dev_Level' placeholder="请选择设备等级">
                                        <el-option
                                                v-for="item in dictStore.getDictData('errorLevel')"
                                                :key="item.id"
                                                :label="item.label"
                                                :value="item.code"
                                            />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            
                            <el-col :span="8">
                                <el-form-item label="状态" prop="enable">
                                    <el-select v-model='formData.enable' placeholder="请选择状态">
                                        <el-option
                                                v-for="item in dictStore.getDictData('status')"
                                                :key="item.id"
                                                :label="item.label"
                                                :value="item.code"
                                            />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </el-tab-pane>
        </el-tabs>
        <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' } " :cell-style="{ textAlign: 'center' }" style="width: 100%"  @selection-change="handleSelectionChange" >
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="序号" width="60" />
                    <el-table-column prop="type" label="电能质量检测指标类型" width="181">
                        <template #default="{ row }">
                            <el-select v-model="row.type" placeholder="选择指标类型">
                                <el-option v-for="option in typeList" :key="option.value" :label="option.label" :value="option.value"/>
                            </el-select>
                            </template>
                    </el-table-column>
                    <el-table-column label="起止范围" >
                        <el-table-column label="起始">
                            <template #default="{ row }">
                                <el-row type="flex">
                                    <el-col :span="14">
                                        <el-select v-model="row.startSelect" placeholder="选择起始值" style="width: 70px;">
                                            <el-option v-for="option in errorStartOptions" :key="option.value" :label="option.label" :value="option.value"/>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="10">
                                        <el-input v-model= "row.startRange" style="width: 70px;"
                                        />
                                    </el-col>
                                </el-row>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束">
                            <template #default="{ row }">
                                <el-row type="flex" >
                                    <el-col :span="14">
                                        <el-select v-model="row.endSelect" placeholder="选择结束值" style="width: 70px;">
                                            <el-option v-for="option in errorEndOptions" :key="option.value" :label="option.label" :value="option.value"/>
                                        </el-select>
                                    </el-col>
                                    <el-col :span="10">
                                        <el-input v-model= "row.endRange" style="width: 70px;"/>
                                    </el-col>
                                </el-row>
                            </template>
                        </el-table-column>
                        <el-table-column label="单位" width="115">
                            <template #default="{ row }">
                            <el-select v-model="row.unit" placeholder="选择单位">
                                <el-option
                                v-for="option in errorUnitOptions"
                                :key="option.value"
                                :label="option.label"
                                :value="option.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.startRange" style="width: 70px;"/>
                            </template>
                        </el-table-column>
                        <el-table-column label="误差类型">
                            <template #default="{ row }">
                            <el-select v-model="row.errorType" placeholder="选择误差类型">
                                <el-option
                                v-for="option in errorTypeOptions"
                                :key="option.value"
                                :label="option.label"
                                :value="option.value"
                                />
                            </el-select>
                            </template>
                        </el-table-column>
                    </el-table-column>
                    <el-table-column label="操作" 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 #footer>
            <div >
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">保存</el-button>
            </div>
        </template>
    </el-dialog>


</template>
  
  <script lang="ts" setup name="ErrorSystemDialog">
  import{ElMessage, FormInstance,FormItemRule}from'element-plus'
  import { defineProps, defineEmits, reactive,watch,ref, Ref } from 'vue';
  import { dialogBig,dialogMiddle} from '@/utils/elementBind'
  //import IndicatorTypeDialog from "@/views/machine/errorSystem/components/IndicatorTypeDialog.vue"; // 导入子组件
  import {CirclePlus, Delete, EditPen,FolderOpened,CopyDocument} from '@element-plus/icons-vue'
  import { useDictStore } from '@/stores/modules/dict'
  const dictStore = useDictStore()
  const props = defineProps<{
    visible: boolean;
    dialogTitle: string;
    
    formData: {
        id: string;//误差体系表Id
        name: string;//误差体系名称
        standard_Name:string;//参照标准名称
        standard_Time:string;//标准推行时间
        dev_Level:string;//使用设备等级
        enable:number;//状态：0-不启用 1-启用
        state:number;//0-删除 1-正常
    };
  }>();


// 定义规则
const formRuleRef = ref<FormInstance>()
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '误差体系名称必填！', trigger: 'blur' }],
    standard_Name: [{ required: true, message: '参照标准名称必填！', trigger: 'blur' }],
    standard_Time: [{ required: true, message: '标准推行时间必填！', trigger: 'blur' }],
    dev_Level:[{ required: true, message: '请选择一项设备等级', trigger: 'change' },],
    enable:[{ required: true, message: '请选择一项状态', trigger: 'change '},]
});    


  let multipleSelection = ref<number[]>([])
  const errorTypeOptions = [
  { label: '绝对值-标称值', value: 'type1' },
  { label: '相对值-I类', value: 'type2' },
  { label: '相对值-II类', value: 'type3' },
  { label: '绝对值-值类型', value: 'type4' },
];

const errorUnitOptions = [
  { label: '标称值', value: 'type1' },
  { label: '值', value: 'type2' },
  { label: '无', value: 'type3' },
];

const errorStartOptions = [
  { label: '>', value: 'type1' },
  { label: '>=', value: 'type2' },
  { label: '无', value: 'type3' },
];

const errorEndOptions = [
  { label: '<', value: 'type1' },
  { label: '<=', value: 'type2' },
  { label: '无', value: 'type3' },
];
const typeList = [
      { label: '电压', value: '电压' },
      { label: '频率', value: '频率' },
      { label: '电压三相不平衡度', value: '电压三相不平衡度' },
      { label: '电流三相不平衡度', value: '电流三相不平衡度' },
      { label: '电压波动', value: '电压波动' },
      { label: '短时闪变', value: '短时闪变' },
      { label: '谐波电压', value: '谐波电压' },
      { label: '谐波电流', value: '谐波电流' },
      { label: '谐波相角', value: '谐波相角' },
      { label: '谐波功率', value: '谐波功率' },
      { label: '间谐波电压', value: '间谐波电压' },
      { label: '间谐波电流', value: '间谐波电流' },
      { label: '功率', value: '功率' },
      { label: '电流', value: '电流' },
      { label: '暂态电压幅值', value: '暂态电压幅值' },
      { label: '暂态持续时间', value: '暂态持续时间' },
    ];


  const tableData = ref([
  {
    id: 1,
    type: '电压',
    startSelect: 'type1',
    startRange: '0.1',
    endSelect: 'type2',
    endRange: '1.5',
    unit:'type1',
    maxErrorValue:'0.001',
    errorType:'type1'
  },
  {
    id: 2,
    type: '电流',
    startSelect: 'type2',
    startRange: '0.01',
    endSelect: 'type1',
    endRange: '0.05',
    unit:'type1',
     maxErrorValue:'0.005',
     errorType:'type1'
  },
  {
    id: 3,
    type: '频率',
    startSelect: 'type2',
    startRange: '42.5',
    endSelect: 'type2',
    endRange: '57.5',
    unit:'type1',
     maxErrorValue:'0.01',
     errorType:'type4'
  },
  
])

  const emit = defineEmits<{
    (e: 'update:visible', value: boolean): void;
    (e: 'submit', data: any): void;
  }>();
  
  const handleCancel = () => {
    //重置表单内容
    //取消表单校验状态
    formRuleRef.value && formRuleRef.value.resetFields()
    emit('update:visible', false); // 关闭对话框
  };
  
  const handleSubmit = () => {
    //ElMessage.info('业务数据提交')
    try {
    formRuleRef.value?.validate((valid: boolean) => {
    if (valid) 
    {
        // 将表单数据转为json,发送到后端
        let confirmFormData = JSON.parse(JSON.stringify(props.formData));
       // console.log(confirmFormData)
        emit('submit', props.formData); // 提交表单数据
        emit('update:visible', false); // 提交后关闭对话框             
    } 
    else 
    {
        ElMessage.error('表单验证失败！')
    }
    })
    } catch (error) {
        console.error('验证过程中发生错误', error)
    }
  };
  
  // 当 props.visible 改变时，更新 formData
  watch(() => props.visible, (newVal) => {
    if (!newVal) {
      // 这里可以重置表单数据，如果需要的话
     
    }
  });



//选中
 // 处理选择变化
 const handleSelectionChange = (selection: any[]) => {
    multipleSelection.value = selection.map(row => row.id); // 更新选中的行
    
  };
  const openAddDialog = () => {
    tableData.value.push({
        id: tableData.value.length + 1,
        type: '',
        startSelect: '',
        startRange: '',
        endSelect: '',
        endRange: '',
        unit:'',
        maxErrorValue:'',
        errorType:''
  });
};


const copyRow = (row: any) => {
  tableData.value.push({ ...row, id: tableData.value.length + 1, });
};

const deleteRow = (row: { id: number; type: string; startSelect: string; startRange: string; endSelect: string; endRange: string; unit: string; maxErrorValue: string; errorType: string; }) => {
  const index = tableData.value.indexOf(row);
  if (index !== -1) {
    tableData.value.splice(index, 1);
  }
};


const deleteSelectedRows = () => {
  tableData.value = tableData.value.filter(row => !multipleSelection.value.includes(row.id));
  multipleSelection.value = []; // 清空已选择的行
};
  </script>
  
  <style scoped>
  
.form-grid {
    display: flex;
    flex-direction: row; /* 横向排列 */
    flex-wrap: wrap; /* 允许换行 */
}
.form-grid .el-form-item {
    flex: 1 1 30%; /* 控件宽度 */
    margin-right: 20px; /* 控件间距 */
}
.form-grid .el-form-item:last-child {
    margin-right: 0; /* 最后一个控件不需要右边距 */
}
.dialog-footer {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px; /* 调整这里的值以增加或减少间距 */
}
.el-tabs {
    margin-bottom: 20px; /* 添加底部边距 */
}

.el-table th, .el-table td {
  text-align: center; /* 所有单元格文字居中 */
}

.table-container {
  max-height: 400px; /* 根据需要调整高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动条 */
}
</style>