<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="通讯协议" 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" prop="association" :required="isMonitorDeviceType">
                <div style="display: flex;">
                    <el-cascader v-model.trim="form.association" filterable :options="engineeringList"
                        :props="cascaderProps" clearable placeholder="请选择关联项目" />
                    <el-button type="primary" icon="el-icon-Plus" class="ml10" @click="addProject" />
                </div>
            </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" :loading="loading">确定</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<{
    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 loading = ref(false)
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' }],
    association: [{
        validator: (_rule: any, value: any, callback: (error?: Error) => void) => {
            if (isMonitorDevType(form.devType)) {
                if (!Array.isArray(value) || value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error('请选择关联项目'))
                    return
                }
            }
            callback()
        },
        trigger: 'change'
    }]
})

const getDevTypeOptions = () => {
    if (form.devAccessMethod === 'CLD') {
        return Array.isArray(props.devTypeOptions2)
            ? props.devTypeOptions2
            : props.devTypeOptions2
                ? [props.devTypeOptions2]
                : []
    }
    return props.devTypeOptions
}

const isMonitorDevType = (devType: unknown) => {
    if (!devType) return false
    const selected = getDevTypeOptions().find((item: any) => (item.value || item.id) == devType)
    return selected?.name === '监测设备' || selected?.label === '监测设备' || selected?.code === 'DEV_CLD'
}

const isMonitorDeviceType = computed(() => isMonitorDevType(form.devType))

function getDefaultForm() {
    return {
        cntractNo: '',
        devAccessMethod: 'MQTT',
        devModel: '',
        devType: '',
        name: '',
        ndid: '',
        associatedEngineering: '',
        associatedProject: '',
        association: [] as any[],
        sort: 0,
        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,
    }
}

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 = ''
    nextTick(() => {
        ruleFormRef.value?.clearValidate('association')
        if (isMonitorDevType(e)) {
            ruleFormRef.value?.validateField('association')
        }
    })
}

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 addProject = () => {
    sessionStorage.setItem('factoryNeedRefreshEngineeringList', '1')
    router.push({
        name: 'govern/manage/engineering',
    })
}
const onSubmit = () => {
    ruleFormRef.value.validate((valid: boolean) => {
        if (!valid) return
        loading.value = true
        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')
            }).finally(() => {
                loading.value = false
            })
        } else {
            editEquipmentDelivery(payload).then(() => {
                ElMessage.success('修改成功')
                resetForm()
                emit('success')
            }).finally(() => {
                loading.value = false
            })
        }

    })
}

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