<template>
    <el-dialog class="cn-operate-dialog" draggable v-model="dialogVisible" :title="title" width="800px"
        @closed="handleClosed">
        <el-scrollbar max-height="60vh">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" class="form-two">
                <el-form-item label="指标名称" prop="indexName">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.indexName" placeholder="请输入指标名称"
                        clearable />
                </el-form-item>

                <el-form-item label="指标Code" prop="indexCode">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.indexCode" placeholder="请输入指标Code"
                        clearable />
                </el-form-item>


                <el-form-item label="表名" prop="influxdbTableName">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.influxdbTableName" placeholder="请输入表名"
                        clearable />
                </el-form-item>
                <el-form-item label="列属性" prop="influxdbColumnName">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.influxdbColumnName" placeholder="实体类属性名"
                        clearable />
                </el-form-item>
                <el-form-item label="谐波次数">
                    <el-slider v-model.trim="form.harmSlider" range :max="50" style="width: 90%" />
                </el-form-item>
                <el-form-item label="相别" prop="phaseList">
                    <el-select v-model.trim="form.phaseList" filterable multiple clearable collapse-tags
                        collapse-tags-tooltip placeholder="请选择相别">
                        <el-option v-for="item in phaseSelect" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="指标下限" prop="minValue">
                    <el-input-number v-model="form.minValue" style="width: 100%" placeholder="下限" />
                </el-form-item>
                <el-form-item label="指标上限" prop="maxValue">
                    <el-input-number v-model="form.maxValue" style="width: 100%" placeholder="上限" />
                </el-form-item>
                <el-form-item label="电压等级参与" prop="isVoltage">
                    <el-radio-group v-model="form.isVoltage">
                        <el-radio :value="0">不参与</el-radio>
                        <el-radio :value="1">参与</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="CT变比参与" prop="ctAttendFlag">
                    <el-radio-group v-model="form.ctAttendFlag">
                        <el-radio :value="0">不参与</el-radio>
                        <el-radio :value="1">参与</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="数据来源" prop="dataSource">
                    <el-select v-model="form.dataSource" placeholder="请选择" clearable style="width: 100%">
                        <el-option label="InfluxDB" value="InfluxDB" />
                        <!-- <el-option label="oracle" value="oracle" /> -->
                        <el-option label="MySql" value="MySql" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属系统" prop="belongingSystem">
                    <el-select v-model="form.belongingSystem" placeholder="请选择" clearable style="width: 100%">
                        <el-option label="pqs" value="pqs" />
                        <el-option label="govern" value="govern" />
                    </el-select>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-input maxlength="32" show-word-limit v-model.trim="form.unit" placeholder="请输入单位" clearable />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" :min="0" style="width: 100%;" :precision="0" />
                </el-form-item>
                <!-- <el-form-item label="状态" prop="state">
                    <el-select v-model="form.state" placeholder="请选择" style="width: 100%">
                        <el-option label="正常" :value="1" />
                        <el-option label="删除" :value="0" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="条件描述" prop="otherAlgorithm" class="form-item-full">
                    <el-input show-word-limit v-model.trim="form.otherAlgorithm" type="textarea" :rows="2"
                        placeholder="无具体范围时的判断条件描述" maxlength="300" />
                </el-form-item>
                <el-form-item label="备注" prop="remark" class="form-item-full">
                    <el-input show-word-limit v-model.trim="form.remark" type="textarea" :rows="2" placeholder="备注"
                        maxlength="300" />
                </el-form-item>
            </el-form>
        </el-scrollbar>
        <template #footer>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="onSubmit" :loading="loading">确定</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { save, update } from '@/api/algorithm-boot/scopeConfig'
const emit = defineEmits(['Cancels'])

const dialogVisible = ref(false)
const title = ref('')
const formRef = ref()
const loading = ref(false)
const phaseSelect = [
    {
        name: 'A相',
        id: 'A'
    },
    {
        name: 'B相',
        id: 'B'
    },
    {
        name: 'C相',
        id: 'C'
    },
    {
        name: '无相别',
        id: 'T'
    },
    {
        name: 'AB相',
        id: 'AB'
    },
    {
        name: 'BC相',
        id: 'BC'
    },
    {
        name: 'CA相',
        id: 'CA'
    },
    // {
    //     name: '无相别',
    //     id: 'M'
    // },
]
const defaultForm = () => ({
    id: '',
    indexCode: '',
    indexName: '',
    harmSlider: [0, 0],
    harmStart: undefined as number | undefined,
    harmEnd: undefined as number | undefined,
    phaseType: '',
    phaseList: [] as any,
    influxdbTableName: '',
    influxdbColumnName: '',
    minValue: undefined as number | undefined,
    maxValue: undefined as number | undefined,
    isVoltage: 0,
    ctAttendFlag: 0,
    dataSource: '',
    otherAlgorithm: '',
    remark: '',
    unit: '',
    sort: 100,
    belongingSystem: 'govern',
    state: 1
})

const form = reactive(defaultForm())



const validateMinMax = (_rule: any, _value: any, callback: (e?: Error) => void) => {
    if (form.minValue == null || form.maxValue == null) {
        callback()
        return
    }
    if (form.minValue > form.maxValue) {
        callback(new Error('指标下限不能大于指标上限'))
    } else {
        callback()
    }
}

const rules: any = {
    indexCode: [{ required: true, message: '请输入指标Code', trigger: 'blur' }],
    indexName: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
    phaseList: [{ required: true, message: '请输入指标名称', trigger: 'change' }],

    influxdbTableName: [{ required: true, message: '请输入表名', trigger: 'blur' }],
    influxdbColumnName: [{ required: true, message: '请输入列属性', trigger: 'blur' }],
    minValue: [
        { required: true, message: '请输入指标下限', trigger: 'blur' },
        { validator: validateMinMax, trigger: 'change' }
    ],
    maxValue: [
        { required: true, message: '请输入指标上限', trigger: 'blur' },
        { validator: validateMinMax, trigger: 'change' }
    ],
    isVoltage: [{ required: true, message: '请选择电压等级是否参与', trigger: 'change' }],
    ctAttendFlag: [{ required: true, message: '请选择Ct变比是否参与', trigger: 'change' }],
    dataSource: [{ required: true, message: '请选择数据来源', trigger: 'change' }],
    belongingSystem: [{ required: true, message: '请选择所属系统', trigger: 'change' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    state: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const isEdit = () => title.value.includes('修改')

const resetForm = () => {
    Object.assign(form, defaultForm())
}

const fillForm = (row: any) => {
    const keys = Object.keys(defaultForm()) as (keyof ReturnType<typeof defaultForm>)[]
    keys.forEach(key => {
        if (row[key] === undefined || row[key] === null) return
        if (['harmStart', 'harmEnd', 'sort', 'isVoltage', 'ctAttendFlag', 'state'].includes(key)) {
            ; (form as any)[key] = Number(row[key])
        } else if (['minValue', 'maxValue'].includes(key)) {
            ; (form as any)[key] = Number(row[key])
        } else {
            ; (form as any)[key] = row[key]
        }
    })
    form.phaseList = form.phaseType.split(',')

    form.harmSlider = [form.harmStart || 0, form.harmEnd || 0]
}

const open = (e: { text: string; row?: any }) => {
    formRef.value?.resetFields()
    title.value = e.text
    dialogVisible.value = true
    resetForm()
    if (e.row) {

        fillForm(e.row)
    }
}

const handleCancel = () => {
    dialogVisible.value = false
    emit('Cancels')
}

const handleClosed = () => {
    resetForm()
}

const onSubmit = () => {
    formRef.value?.validate(async (valid: boolean) => {
        if (!valid) return
        loading.value = true
        form.harmStart = form.harmSlider[0]
        form.harmEnd = form.harmSlider[1]
        form.phaseType = form.phaseList.join(',')
        const payload = { ...form }
        try {
            if (isEdit()) {
                await update(payload)
                ElMessage.success('修改成功!')
            } else {
                await save({ ...payload, id: '' })
                ElMessage.success('新增成功!')
            }
            dialogVisible.value = false
            emit('Cancels')
        } catch {
            /* 统一错误提示 */
        } finally {
            loading.value = false
        }
    })
}

defineExpose({ open })
</script>

<style scoped>
.form-item-full {
    grid-column: 1 / -1;
}
</style>