<template>
    <el-dialog draggable width="800px" v-model="dialogVisible" :title="title">
        <el-scrollbar>
            <el-form :inline="false" ref="formRef" :model="form" label-width="auto" :rules="rules" class="form-two">
                <!-- 变压器参数维护 -->
                <el-form-item v-for="(item, index) in child" :key="index" :label="item.title" :prop="item.field">
                    <el-select
                        v-if="item.field == 'transtypeId'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择变压器型号"
                    >
                        <el-option
                            v-for="item in transformer"
                            :key="item.transtypeId"
                            :label="item.transtypeName"
                            :value="item.transtypeId"
                        ></el-option>
                    </el-select>
                     <!-- 用户负荷参数维护 -->
                    <el-select
                        v-else-if="item.field == 'harmId'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择谐波源"
                    >
                        <el-option
                            v-for="item in characteristic"
                            :key="item.harmId"
                            :label="item.harmName"
                            :value="item.harmId"
                        ></el-option>
                    </el-select>
                     <!-- 冲击负荷参数维护 -->
                    <el-select
                        v-else-if="item.field == 'inpactloadtypeId'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择冲击负荷类型"
                         @change="handleImpactLoadTypeChange"
                    >
                        <el-option
                            v-for="item in shockList"
                            :key="item.inpactloadtypeId"
                            :label="item.inpactloadtypeName"
                            :value="item.inpactloadtypeId"
                        ></el-option>
                    </el-select>
                    <el-select
                        v-else-if="item.field == 'inpactloadStartup'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择启动方式"
                         @change="handleStartupChange"
                    >
                        <el-option
                        v-for="startup in startupOptions"
                        :key="startup.value"
                        :label="startup.label"
                        :value="startup.value"
                        />
                    </el-select>
                    <el-select
                        v-else-if="item.field == 'inpactloadFreq'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择负荷频度"
                    >
                        <el-option label="N≤4次/d" value="01"></el-option>
                        <el-option label="N>4次/d且N≤2次/h" value="02"></el-option>
                        <el-option label="2次/h<N≤10次/h" value="03"></el-option>
                    </el-select>
                    <el-select
                        v-else-if="item.field == 'isIsolationtrans'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择是否隔离变"
                    >
                    <el-option label="是" value="01" />
                    <el-option label="否" value="00" />
                    </el-select>
                    <el-select
                        v-else-if="item.field == 'inpactloadhighScale'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择高压侧电压"
                    >
                    <el-option
                        v-for="item in voltageleveloption"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                    </el-select>
                    <el-select
                        v-else-if="item.field == 'inpactloadlowScale'"
                        v-model="form[item.field]"
                        filterable
                        clearable
                        placeholder="请选择低压侧电压"
                    >
                    <el-option
                        v-for="item in voltageleveloption"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    ></el-option>
                    </el-select>
                    
                    <el-input-number
                        v-else-if="item.field == 'powerFactor'"
                        style="width: 100%"
                        v-model="form[item.field]"
                        :min="0.1"
                        :max="0.9"
                        :step="0.1"
                        :precision="1"
                        placeholder="请输入功率因数"
                        />
                    <el-input-number
                    
                        v-else-if="item.field == 'flickerCoeff' || item.field == 's'"
                        style="width: 100%"
                        v-model="form[item.field]"
                        show-word-limit
                        :min="0"
                        :max="99"
                        placeholder="请输入值"
                        />
                    <el-input-number
                        v-else-if="
                            item.field == 'transNum' ||
                            item.field == 'capacitorNum' ||
                            item.field == 'capacitorCapacity' ||
                            item.field == 'capacitorReactance' ||
                            item.field == 'transhighCapacity'||
                            item.field == 'transImpedance'||
                            item.field == 'nonlinearloadPower' ||
                            item.field == 'inpactloadNum' ||
                            item.field =='isolationtransImpedance'
                        "
                        style="width: 100%"
                        v-model="form[item.field]"
                        show-word-limit
                        :min="1"
                        :max="9999"
                        placeholder="请输入值"
                    ></el-input-number>

                    <el-select
                        v-else-if="
                            item.field == 'capacitorScale' ||
                            item.field == 'linevoltageScale' ||
                            item.field == 'translowScale'
                        "
                        v-model="form[item.field]"
                        filterable
                        placeholder="请选择电压等级"
                    >
                        <el-option
                            v-for="item in voltageleveloption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>

                    
                    <el-input v-else v-model.trim="form[item.field]" placeholder="请输入内容" show-word-limit maxlength="32" :disabled= "item.field == 'inpactloadPower'"/>
                </el-form-item>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, inject } from 'vue'
import { reactive } from 'vue'
import { useDictData } from '@/stores/dictData'
import {
    transformerList,
    characteristicList,
    assessTransformerParamAdd,
    assessTransformerParamEdit,
    capacitorAdd,
    capacitorEdit,
    windPowerAdd,
    windPowerDdit,
    loadParamAdd,
    loadParamEdit,
    shockAdd,
    shockEdit,
    loadList
} from '@/api/advance-boot/assess'
import { ElMessage, ElMessageBox, ElDatePicker } from 'element-plus'
const emits = defineEmits(['init'])
const child: any = ref([])
const transformer: any = ref([])
const characteristic: any = ref([])
const shockList: any = ref([])
const form: any = ref({})
const dictData = useDictData()
//字典获取电压等级
const voltageleveloption = dictData.getBasicData('Dev_Voltage_Stand')
const rules = {
    transName: [{ required: true, message: '请输入用户变压器名称', trigger: 'blur' }],
    transtypeId: [{ required: true, message: '请选择变压器型号', trigger: 'change' }],
    transNum: [{ required: true, message: '请输入变压器台数', trigger: 'blur' }],
    capacitorName: [{ required: true, message: '请输入用户电容器名称', trigger: 'blur' }],
    capacitorNum: [{ required: true, message: '请输入电容器组数量', trigger: 'blur' }],
    capacitorCapacity: [{ required: true, message: '请输入单组容量', trigger: 'blur' }],
    capacitorReactance: [{ required: true, message: '请输入电抗率', trigger: 'blur' }],
    capacitorScale: [{ required: true, message: '请选择电压等级', trigger: 'change' }],
    windgeneratorName: [{ required: true, message: '请输入风机名称', trigger: 'blur' }],
    flickerCoeff: [{ required: true, message: '请输入闪变叠加系数', trigger: 'blur' }],
    s: [{ required: true, message: '请输入风机额定视在功率', trigger: 'blur' }],
    loadName: [{ required: true, message: '请输入负荷名称', trigger: 'blur' }],
    transhighCapacity: [{ required: true, message: '请输入配变容量', trigger: 'blur' }],
    transImpedance: [{ required: true, message: '请输入配电变压器阻抗', trigger: 'blur' }],
    nonlinearloadPower: [{ required: true, message: '请输入非线性负荷功率', trigger: 'blur' }],
    powerFactor: [{ required: true, message: '请输入功率因数', trigger: 'blur' }],
    linevoltageScale: [{ required: true, message: '请选择进线电压', trigger: 'change' }],
    harmId: [{ required: true, message: '请选择谐波源特性', trigger: 'change' }],
    translowScale: [{ required: true, message: '请选择配变低压侧电压', trigger: 'change' }],
    inpactloadtypeId: [{ required: true, message: '请选择冲击负荷类型', trigger: 'change' }],
    inpactloadStartup: [{ required: true, message: '请选择启动方式', trigger: 'change' }],
    inpactloadNum:[{ required: true, message: '请输入数量', trigger: 'blur' }],
    inpactloadPower:[{ required: true, message: '请输入容量率', trigger: 'blur' }],
    isIsolationtrans:[{ required: true, message: '请选择是否隔离变', trigger: 'change' }],
    isolationtransImpedance:[{ required: true, message: '请输入隔离变阻抗', trigger: 'blur' }],
    inpactloadhighScale:[{ required: true, message: '请选择高压侧电压', trigger: 'change' }],
    inpactloadlowScale:[{ required: true, message: '请选择低压侧电压', trigger: 'change' }],
    inpactloadFreq:[{ required: true, message: '请选择负荷频度', trigger: 'change' }],

}

const formRef = ref()
const dialogVisible = ref(false)
const title = ref('')

const open = async (row: any) => {
    await info()  // 等待数据加载完成
    title.value = row.title + `_${row.item.name}`
    child.value = row.item.child
    if (row.title == '新增') {
        row.item.child.forEach((item: any) => {
            form.value[item.field] = ''
        })
        form.value.assessId = row.assessId
    } else {
        row.item.child.forEach((item: any) => {
            form.value = JSON.parse(JSON.stringify(row.row))
        })
       
        // 如果是冲击负荷类型，需要设置启动方式下拉选项
        if (form.value.inpactloadtypeId) {
            // 根据选中的冲击负荷类型ID筛选数据
            currentImpactLoadOptions.value = shockList.value.filter(
                (item: any) => item.inpactloadtypeId === form.value.inpactloadtypeId
            )
            
            // 构建启动方式选项
            const uniqueStartups = new Map()
            currentImpactLoadOptions.value.forEach((item: any) => {
                uniqueStartups.set(item.inpactloadStartup, {
                    label: item.inpactloadStartup,
                    value: item.inpactloadStartup
                })
            })
            
            startupOptions.value = Array.from(uniqueStartups.values())

            // 如果有选项，默认选择第一个
            if (startupOptions.value.length > 0) {
                form.value.inpactloadStartup = startupOptions.value[0].value
            } else {
                form.value.inpactloadStartup = ''
            }
        }
    }

    dialogVisible.value = true
}

const info = async () => {
    try {
        // 使用 Promise.all 并行执行请求以提高性能
        const [transformerRes, characteristicRes, shockRes] = await Promise.all([
            transformerList({}),
            characteristicList({}),
            loadList({})
        ])
        
        transformer.value = transformerRes.data
        characteristic.value = characteristicRes.data
        shockList.value = shockRes.data
    } catch (error) {
        console.error('加载数据失败:', error)
    }
}

// 添加启动方式选项数据
const startupOptions = ref<Array<{ label: string; value: string }>>([])
// 存储当前冲击负荷类型的选项
const currentImpactLoadOptions = ref([])
// 处理冲击负荷类型变化
const handleImpactLoadTypeChange = (value: any) => {
  if (value) {
    // 直接根据选中的冲击负荷类型ID筛选数据
    currentImpactLoadOptions.value = shockList.value.filter(
      (item: any) => item.inpactloadtypeId === value
    )
    
    // 构建启动方式选项
    const uniqueStartups = new Map()
    currentImpactLoadOptions.value.forEach((item: any) => {
      uniqueStartups.set(item.inpactloadStartup, {
        label: item.inpactloadStartup,
        value: item.inpactloadStartup
      })
    })
    
    startupOptions.value = Array.from(uniqueStartups.values())
    
    // 如果有选项，默认选择第一个
    if (startupOptions.value.length > 0) {
      form.value.inpactloadStartup = startupOptions.value[0].value
    } else {
      form.value.inpactloadStartup = ''
    }
    
    // 清空之前选择的容量
    form.value.inpactloadPower = null
    
    // 触发启动方式变化事件，自动设置对应的容量
    if (startupOptions.value.length > 0) {
      handleStartupChange(startupOptions.value[0].value)
    }
  } else {
    startupOptions.value = []
    currentImpactLoadOptions.value = []
    form.value.inpactloadStartup = ''
    form.value.inpactloadPower = null
  }
}

// 处理启动方式变化
const handleStartupChange = (value: any) => {
    if (value && currentImpactLoadOptions.value.length > 0) {
    // 根据启动方式查找对应的容量倍数
    const selectedOption = currentImpactLoadOptions.value.find(
      (item: any) => item.inpactloadStartup === value
    )
    if (selectedOption) {
      // 设置容量为倍数，实际应用中可能需要根据其他参数计算具体容量值
      form.value.inpactloadPower = selectedOption.inpactloadMultiple
    } else {
      form.value.inpactloadPower = null
    }
  } else {
    form.value.inpactloadPower = null
  }
}
const submit = async () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            if (title.value == '新增_变压器参数维护') {
                await assessTransformerParamAdd(form.value).then((res: any) => {
                    ElMessage.success('新增成功')
                    emits('init', 0)
                })
            } else if (title.value == '编辑_变压器参数维护') {
                await assessTransformerParamEdit(form.value).then((res: any) => {
                    ElMessage.success('修改成功')
                    emits('init', 0)
                })
            } else if (title.value == '新增_电容器组参数维护') {
                await capacitorAdd(form.value).then((res: any) => {
                    ElMessage.success('新增成功')
                    emits('init', 1)
                })
            } else if (title.value == '编辑_电容器组参数维护') {
                await capacitorEdit(form.value).then((res: any) => {
                    ElMessage.success('修改成功')
                    emits('init', 1)
                })
            } else if (title.value == '新增_风电参数') {
                await windPowerAdd(form.value).then((res: any) => {
                    ElMessage.success('新增成功')
                    emits('init', 2)
                })
            } else if (title.value == '编辑_风电参数') {
                await windPowerDdit(form.value).then((res: any) => {
                    ElMessage.success('修改成功')
                    emits('init', 2)
                })
            } else if (title.value == '新增_用户负荷') {
                await loadParamAdd(form.value).then((res: any) => {
                    ElMessage.success('新增成功')
                    emits('init', 3)
                })
            } else if (title.value == '编辑_用户负荷') {
                await loadParamEdit(form.value).then((res: any) => {
                    ElMessage.success('修改成功')
                    emits('init', 3)
                })
            }else if (title.value == '新增_冲击负荷') {
                await shockAdd(form.value).then((res: any) => {
                    ElMessage.success('新增成功')
                    emits('init', 4)
                })
            } else if (title.value == '编辑_冲击负荷') {
                await shockEdit(form.value).then((res: any) => {
                    ElMessage.success('修改成功')
                    emits('init', 4)
                })
            }
            dialogVisible.value = false
        }
    })
}

defineExpose({ open })
</script>
