<template>
    <el-dialog :title="dialogTitle" v-model="visible" :close-on-click-modal="false" :before-close="handleBeforeClose"
        draggable width="800px">
        <el-form :model="form" label-width="auto" :rules="rules" ref="ruleFormRef" class="form-two">
            <el-form-item label="设备名称" prop="name">
                <el-input maxlength="32" show-word-limit v-model.trim="form.name" autocomplete="off" clearable
                    placeholder="请输入（项目名称+设备名称）"></el-input>
            </el-form-item>
            <el-form-item label="网络设备ID" prop="ndid" class="top">
                <el-input maxlength="32" show-word-limit v-model.trim="form.ndid" autocomplete="off"
                    placeholder="请输入网络设备ID"></el-input>
            </el-form-item>
            <el-form-item label="设备类型" prop="devType" class="top">
                <el-select v-model.trim="form.devType" placeholder="请选择设备类型" @change="formDevTypeChange" clearable>
                    <el-option v-for="item in formDevTypeOptions" :key="item.value" :label="item.label || item.name"
                        :value="item.value || item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="设备型号" prop="devModel" class="top">
                <el-select v-model.trim="form.devModel" filterable placeholder="请选择设备型号" clearable>
                    <el-option v-for="item in formDevModelOptionsFilter" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="治理类型"  class="top">
                <el-select v-model.trim="form.governType" filterable placeholder="请选择治理类型" clearable>
                    <el-option label="暂态" value="event"></el-option>
                    <el-option label="稳态" value="harmonic"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="敏感用户"class="top">
                <div style="display: flex;">
                    <el-select v-model.trim="form.monitorUser" style="width: 230px;" filterable placeholder="请选择敏感用户"
                        clearable>
                        <el-option v-for="option in userList" :key="option.id" :label="option.name"
                            :value="option.id"></el-option>
                    </el-select>
                    <el-button type="primary" icon="el-icon-Plus" class="ml10" @click="addMonitorUser" />
                </div>
            </el-form-item>
            <el-form-item label="治理方法"  class="top">
                <el-input maxlength="32" show-word-limit v-model="form.governMethod" autocomplete="off" clearable
                    placeholder="例: 250A APF 或 100kVar SVG"></el-input>
            </el-form-item>
            <el-form-item label="通讯协议" prop="devAccessMethod" class="top">
                <el-select v-model.trim="form.devAccessMethod" placeholder="请选择通讯协议" clearable disabled>
                    <el-option label="MQTT" value="MQTT"></el-option>
                    <el-option label="CLD" value="CLD"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="关联项目" class="top">
                <el-cascader v-model.trim="form.association" filterable :options="engineeringList"
                    :props="cascaderProps" clearable placeholder="请选择关联项目" />
            </el-form-item>
            <el-form-item label="排序" class="top" prop="sort">
                <el-input-number v-model.trim="form.sort" style="width: 100%;" :min="0" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
    addEquipmentDelivery,
    editEquipmentDelivery,
    portableDeviceRegister,
} from '@/api/cs-system-boot/device'
import { useRouter } from 'vue-router'
const router = useRouter() // 路由对象
const props = defineProps<{
    userList: any[]
    engineeringList: any[]
    devTypeOptions: any[]
    devTypeOptions2: any
    devModelOptions: any[]
    devModelOptions2: any[]
}>()

const emit = defineEmits<{
    success: []
}>()

const visible = defineModel<boolean>('visible', { default: false })

const dialogTitle = ref('新增设备')
const ruleFormRef = ref()
const form: any = reactive(getDefaultForm())

const cascaderProps = {
    label: 'projectName',
    value: 'projectId',
    children: 'projectInfoList'
}

const rules = reactive({
    name: [{ required: true, message: '请输入设备名', trigger: 'blur' }],
    ndid: [{ required: true, message: '请输入网络设备id', trigger: 'blur' }],
    devType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    devModel: [{ required: true, message: '请选择设备型号', trigger: 'change' }],
    devAccessMethod: [{ required: true, message: '请输入接入方式', trigger: 'blur' }],
    cntractNo: [{ required: true, message: '请输入合同号', trigger: 'blur' }],
    sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
})

function getDefaultForm() {
    return {
        cntractNo: '',
        devAccessMethod: 'MQTT',
        devModel: '',
        devType: '',
        name: '',
        ndid: '',
        associatedEngineering: '',
        associatedProject: '',
        association: [] as any[],
        sort: 0,
        monitorUser: '',
        governType: '',
        governMethod: '',
        id: undefined as string | number | undefined,
    }
}

const normalizeFormValue = (value: unknown, fallback = '') =>
    value == null ? fallback : value

const buildSubmitPayload = () => {
    const association = Array.isArray(form.association) ? form.association : []
    return {
        id: form.id,
        cntractNo: normalizeFormValue(form.cntractNo),
        devAccessMethod: normalizeFormValue(form.devAccessMethod, 'MQTT'),
        devModel: normalizeFormValue(form.devModel),
        devType: normalizeFormValue(form.devType),
        name: normalizeFormValue(form.name),
        ndid: normalizeFormValue(form.ndid),
        associatedEngineering: normalizeFormValue(association[0]),
        associatedProject: normalizeFormValue(association[1]),
        sort: form.sort ?? 0,
        monitorUser: normalizeFormValue(form.monitorUser),
        governType: normalizeFormValue(form.governType),
        governMethod: normalizeFormValue(form.governMethod),
    }
}

const formDevModelOptionsFilter = computed(() => {
    if (form.devAccessMethod === 'CLD') {
        return props.devModelOptions2.filter((item: any) => {
            return form.devType ? item.pid == form.devType : true
        })
    }
    return props.devModelOptions.filter((item: any) => {
        return form.devType ? item.pid == form.devType : true
    })
})

const formDevTypeOptions = computed(() => {
    if (form.devAccessMethod === 'CLD') {
        return [props.devTypeOptions2]
    }
    return props.devTypeOptions
})

const formDevTypeChange = (e: any) => {
    if (!e) return
    form.devModel = ''
}

const openAdd = () => {
    dialogTitle.value = '新增设备'
    Object.assign(form, getDefaultForm())
    visible.value = true
}

const openEdit = (row: any) => {
    dialogTitle.value = '编辑设备'
    Object.assign(form, getDefaultForm())
    for (const key in form) {
        if (key in row) {
            form[key] = row[key]
        }
    }
    form.association = row.associatedProject ? [row.associatedEngineering, row.associatedProject] : []
    form.id = row.id
    visible.value = true
}

const clearForm = () => {
    ruleFormRef.value?.resetFields()
    nextTick(() => {
        Object.assign(form, getDefaultForm())
    })
}

const handleCancel = () => {
    clearForm()
    visible.value = false
}

const handleBeforeClose = (done: () => void) => {
    clearForm()
    done()
}

const resetForm = () => {
    clearForm()
    visible.value = false
}

const addMonitorUser = () => {
    sessionStorage.setItem('factoryNeedRefreshUserList', '1')
    router.push({
        name: 'govern/sensitiveLoadMange/index',
    })
}
const onSubmit = () => {
    ruleFormRef.value.validate((valid: boolean) => {
        if (!valid) return

        const payload = buildSubmitPayload()

        if (dialogTitle.value === '新增设备') {
            addEquipmentDelivery(payload).then(res => {
                ElMessage.success('新增成功')
                const devType = props.devTypeOptions.find((item: any) => item.value == payload.devType)
                if (devType?.code === 'Portable') {
                    setTimeout(() => {
                        ElMessage.warning('设备正在接入中，请稍等。')
                    }, 3000)
                    portableDeviceRegister({ nDid: res.data.ndid })
                        .then(pres => {
                            ElMessage.success(pres.message)
                        })
                        .catch(() => { })
                }
                resetForm()
                emit('success')
            })
        } else {
            editEquipmentDelivery(payload).then(() => {
                ElMessage.success('修改成功')
                resetForm()
                emit('success')
            })
        }
    })
}

defineExpose({ openAdd, openEdit })
</script>
