<template>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" @close="close" v-bind="dialogBig" align-center>
        <div>
            <el-form
                :model="formContent"
                ref="dialogFormRef"
                :rules="rules"
                :disabled="tableIsDisable"
                label-width="auto"
                class="form-three"
            >
                <el-form-item label="设备类型" prop="devType">
                    <el-select v-model="formContent.devType" placeholder="请选择源设备类型">
                        <el-option
                            v-for="item in dictStore.getDictData(dictTypeCode)"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="检测源类型" prop="type">
                    <el-select v-model="formContent.type" placeholder="请选择检测源类型">
                        <el-option
                            v-for="item in dictStore.getDictData('Pq_Source_Type')"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="最大电压" prop="maxVoltage">
                    <el-input-number
                        v-model="formContent.maxVoltage"
                        :min="0"
                        :precision="2"
                        :step="0.1"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="最大电流" prop="maxCurrent">
                    <el-input-number
                        v-model="formContent.maxCurrent"
                        :min="0"
                        :precision="2"
                        :step="0.1"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>
        </div>

        <ParameterTable
            :parameterStr="formContent.parameter"
            @change-parameter="changeParameter"
            ref="parameterTable"
            :is-disable="tableIsDisable"
        />
        <template #footer>
            <div>
                <el-button :disabled="tableIsDisable" @click="close()">取消</el-button>
                <el-button :disabled="tableIsDisable" type="primary" @click="save()">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup name="ErrorSystemDialog">
import { ElMessage, type FormItemRule } from 'element-plus'
import { computed, ref, type Ref } from 'vue'
import { dialogBig } from '@/utils/elementBind'
import { addTestSource, getTestSourceById, updateTestSource } from '@/api/device/testSource/index'
import { type TestSource } from '@/api/device/interface/testSource'
import { useDictStore } from '@/stores/modules/dict'

const dialogFormRef = ref()
const dictStore = useDictStore()
const mode = ref()
const modeId = ref()
const parameterTable = ref()
const tableIsDisable = ref(true)

function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<TestSource.ResTestSource>({
        id: '',
        pattern: modeId.value,
        parameter: '',
        type: '',
        devType: '',
        maxVoltage: undefined,
        maxCurrent: undefined,
        state: 1
    })
    return { dialogVisible, titleType, formContent }
}

const { dialogVisible, titleType, formContent } = useMetaInfo()

const resetFormContent = () => {
    formContent.value = {
        id: '',
        pattern: modeId.value,
        parameter: '',
        type: '',
        devType: '',
        maxVoltage: undefined,
        maxCurrent: undefined,
        state: 1
    }
}

const dialogTitle = computed(() => {
    switch (titleType.value) {
        case 'add':
            tableIsDisable.value = false
            return '新增检测源'
        case 'edit':
            tableIsDisable.value = false
            return '编辑检测源'
        case 'view':
            tableIsDisable.value = true
            return '查看检测源'
        default:
            return ''
    }
})

const dictTypeCode = computed(() => {
    return 'S_Dev_Type_' + dictStore.getDictData('Pattern').find(item => item.id === modeId.value)?.code
})

const validateNonNegative = (label: string) => {
    return (_rule: FormItemRule, value: number | undefined, callback: (error?: Error) => void) => {
        if (value != null && value < 0) {
            callback(new Error(`${label} cannot be negative`))
            return
        }
        callback()
    }
}

const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '检测源名称必填', trigger: 'blur' }],
    devType: [{ required: true, message: '请选择一项设备类型', trigger: 'change' }],
    type: [{ required: true, message: '请选择一项检测源类型', trigger: 'change' }],
    maxVoltage: [{ validator: validateNonNegative('最大电压'), trigger: 'change' }],
    maxCurrent: [{ validator: validateNonNegative('最大电流'), trigger: 'change' }]
})

const close = () => {
    dialogVisible.value = false
    resetFormContent()
    dialogFormRef.value?.resetFields()
    parameterTable.value?.clearData()
}

const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                if (formContent.value.id) {
                    await updateTestSource(formContent.value)
                    ElMessage.success({ message: `${dialogTitle.value}成功` })
                } else {
                    await addTestSource(formContent.value)
                    ElMessage.success({ message: `${dialogTitle.value}成功` })
                }
                close()
                await props.refreshTable?.()
            }
        })
    } catch (err) {
        console.error('验证过程中出现错误', err)
    }
}

const open = async (sign: string, data: TestSource.ResTestSource, currentMode: string) => {
    titleType.value = sign
    dialogVisible.value = true
    mode.value = currentMode
    modeId.value = dictStore.getDictData('Pattern').find(item => item.name === currentMode)?.id
    if (data.id) {
        const result = await getTestSourceById(data)
        const sourceData = (result?.data ?? {}) as Partial<TestSource.ResTestSource>
        formContent.value = {
            id: sourceData.id ?? data.id,
            pattern: sourceData.pattern ?? modeId.value,
            parameter: sourceData.parameter ?? '',
            type: sourceData.type ?? '',
            devType: sourceData.devType ?? '',
            maxVoltage: sourceData.maxVoltage ?? undefined,
            maxCurrent: sourceData.maxCurrent ?? undefined,
            state: sourceData.state ?? 1,
            name: sourceData.name,
            createBy: sourceData.createBy,
            createTime: sourceData.createTime,
            updateBy: sourceData.updateBy,
            updateTime: sourceData.updateTime
        }
    } else {
        resetFormContent()
    }
    dialogFormRef.value?.resetFields()
}

const changeParameter = (parameterArr: any) => {
    formContent.value.parameter = JSON.stringify(parameterArr)
}

defineExpose({ open })
const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined
}>()
</script>
<style></style>
