<template>
    <div class="default-main">
        <div class="default">
            <div style="flex: 1">
                <TableHeader>
                    <template v-slot:select>
                        <el-form-item label="前置等级">
                            <el-select
                                v-model="tableStore.table.params.nodeGrade"
                                clearable
                                placeholder="请选择前置等级"
                                filterable
                            >
                                <el-option
                                    v-for="item in fontdveoption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="状态">
                            <el-select
                                v-model="tableStore.table.params.searchState"
                                clearable
                                placeholder="请选择状态"
                                filterable
                            >
                                <el-option
                                    v-for="item in statusoption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </template>
                    <template v-slot:operation>
                        <el-button type="primary" class="ml10" @click="add" icon="el-icon-Plus">新增</el-button>
                    </template>
                </TableHeader>
                <Table
                    ref="tableRef"
                    :row-config="{ isCurrent: true, isHover: true }"
                    @current-change="currentChangeEvent"
                ></Table>
            </div>
            <div class="pd10" style="width: 400px" v-loading="loading">
                <el-input
                    v-model="filterText"
                    placeholder="请输入内容"
                    clearable
                    maxlength="32"
                    show-word-limit
                    @input="change"
                >
                    <template #prefix>
                        <Icon name="el-icon-Search" style="font-size: 16px" />
                    </template>
                </el-input>
                <el-tree
                    :style="height"
                    style="overflow-y: auto"
                    :data="dataSource"
                    node-key="id"
                    ref="treeRef"
                    default-expand-all
                    :props="defaultProps"
                    :filter-node-method="filterNode"
                >
                    <template #default="{ node, data }">
                        <div class="custom-tree-node">
                            <span>
                                <span v-if="data.processState != null">
                                    {{ node.label }}
                                </span>
                                <span v-else>{{ data.subName }}_{{ data.name }}</span>
                                <span
                                    v-if="data.processState != null"
                                    class="iconSpan"
                                    :style="{ background: data.processState == 0 ? '#ff0000' : '#00b07d' }"
                                ></span>
                            </span>
                            <div>
                                <!-- <el-button type="primary" v-if="data.id == undefined" link icon="el-icon-Plus" ></el-button> -->
                                <el-button
                                    style="margin-left: 4px"
                                    icon="el-icon-Edit"
                                    v-if="data.id"
                                    type="primary"
                                    @click="edit(data)"
                                    link
                                ></el-button>

                                <el-popconfirm
                                    v-else
                                    class="box-item"
                                    title="确定重启吗？"
                                    placement="left"
                                    @confirm="restart(data)"
                                >
                                    <template #actions="{ confirm, cancel }">
                                        <el-button size="small" @click="cancel">取消</el-button>
                                        <el-button type="warning" size="small" @click="confirm">确认</el-button>
                                    </template>

                                    <template #reference>
                                        <el-button
                                            style="margin-left: 4px"
                                            icon="el-icon-Refresh"
                                            type="warning"
                                            link
                                            @click.stop
                                        ></el-button>
                                        <!-- @click.stop="restart(data)" -->
                                    </template>
                                </el-popconfirm>
                            </div>
                        </div>
                    </template>
                </el-tree>
            </div>
        </div>
        <el-dialog
            draggable
            :title="dialogTitle"
            v-model="dialogFormVisible"
            :close-on-click-modal="false"
            width="700px"
            :before-close="resetForm"
        >
            <el-form :model="formData" label-width="120px" :rules="rules" ref="ruleFormRef">
                <el-form-item label="名称:" prop="name">
                    <el-input
                        v-model="formData.name"
                        placeholder="请输入名称"
                        maxlength="32"
                        show-word-limit
                        @input="handleInput"
                    ></el-input>
                </el-form-item>
                <el-form-item label="IP:" prop="ip" class="top">
                    <el-input v-model="formData.ip" placeholder="请输入Ip"></el-input>
                </el-form-item>
                <el-form-item label="等级:" prop="nodeGrade" class="top">
                    <el-select v-model="formData.nodeGrade" placeholder="请选择等级" style="width: 100%" filterable>
                        <el-option
                            v-for="item in fontdveoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="最大终端数:" prop="nodeDevNum" class="top">
                    <el-input
                        v-model.trim.number="formData.nodeDevNum"
                        onkeyup="value = value.replace(/[^0-9]/g,'')"
                        maxlength="5"
                        placeholder="请输入最大终端数"
                    ></el-input>
                </el-form-item>
                <el-form-item label="最大进程数:" prop="maxProcessNum" class="top">
                    <el-input
                        v-model.trim.number="formData.maxProcessNum"
                        onkeyup="value = value.replace(/[^0-9]/g,'')"
                        maxlength="5"
                        placeholder="请根据监测点规模填写合适进程数（1个进程最大可承载200个监测点）"
                    ></el-input>
                    <!-- <el-select v-model="formData.maxProcessNum" placeholder="请选择等级" style="width: 100%">
                        <el-option
                            v-for="item in NumList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select> -->
                </el-form-item>
                <el-form-item label="排序:" prop="sort" class="top">
                    <el-input v-model="formData.sort" placeholder="请输入排序"></el-input>
                </el-form-item>
                <el-form-item label="描述:" prop="remark" class="top">
                    <el-input
                        v-model="formData.remark"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"
                        placeholder="请输入描述"
                    ></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="resetForm">取 消</el-button>
                <el-button type="primary" @click="onSubmit">确 定</el-button>
            </template>
        </el-dialog>

        <!-- 绑定监测点 -->
        <Bind ref="bindRef" />
        <!-- 绑定进程号 -->
        <el-dialog draggable title="绑定进程号" v-model="popUps" :close-on-click-modal="false" width="400px">
            <el-select v-model="processNo" placeholder="请选择进程号" style="width: 100%" filterable>
                <el-option
                    v-for="item in dataSource"
                    :key="item.name"
                    :label="item.name"
                    :value="item.name"
                ></el-option>
            </el-select>

            <template #footer>
                <el-button @click="popUps = false">取 消</el-button>
                <el-button type="primary" @click="bindTheProcess">确 定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive, nextTick } from 'vue'
import {
    addNode,
    delNode,
    updateNode,
    nodeDeviceTree,
    updateDeviceProcess,
    askRestartProcess,
    allotTerminal
} from '@/api/device-boot/Business'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElButton } from 'element-plus'
import { mainHeight } from '@/utils/layout'
import Bind from './bind.vue'
const VITE_FLAG = import.meta.env.VITE_NAME == 'hainan'
defineOptions({
    name: 'BusinessAdministrator/TerminalManagement/FrontManagement'
})
const filterText = ref('')
const fontdveoption: any = ref([
    { id: 0, name: '极重要' },
    { id: 1, name: '普通' },
    { id: 2, name: '备用' }
])
const statusoption: any = ref([
    { id: 0, name: '未启用' },
    { id: 1, name: '启用' }
])
const height = mainHeight(70)
const bindRef = ref()
const loading = ref(false)
const popUps = ref(false)
const tableRef = ref()
const processNo = ref('')
const ruleFormRef = ref()
const dataSource: any = ref([])
const deviceInfoList: any = ref([])
const defaultProps = {
    children: 'deviceInfoList',
    label: 'name'
}
const formData: any = ref({
    name: '',
    ip: '',
    nodeGrade: '',
    nodeDevNum: '',
    sort: '',
    remark: '',
    maxProcessNum: ''
})
const rules = reactive({
    name: [{ required: true, message: '名称不可为空', trigger: 'blur' }],
    ip: [{ required: true, message: 'ip不可为空', trigger: 'blur' }],
    nodeGrade: [{ required: true, message: '等级不可为空', trigger: 'blur' }],
    nodeDevNum: [{ required: true, message: '最大终端数不可为空', trigger: 'blur' }],
    maxProcessNum: [{ required: true, message: '最大进程数不可为空', trigger: 'blur' }],
    sort: [{ required: true, message: '排序不可为空', trigger: 'blur' }],
    remark: [{ required: true, message: '描述不可为空', trigger: 'blur' }]
})
const dialogFormVisible = ref(false)

const dialogTitle = ref('新增前置机')
const processId = ref('')
const tableStore = new TableStore({
    url: '/device-boot/node/nodeList',
    method: 'POST',
    column: [
        { title: '名称', field: 'name' },
        { title: 'IP', field: 'ip', width: '120px' },
        {
            title: '等级',
            field: 'nodeGrade',
            render: 'tag',
            custom: {
                0: 'success',
                1: 'warning',
                2: 'info'
            },
            replaceValue: {
                0: '极重要',
                1: '普通',
                2: '备用'
            }
        },
        {
            title: '最大终端数量',
            field: 'nodeDevNum'
        },
        {
            title: '最大进程数',
            field: 'maxProcessNum'
        },
        {
            title: '排序',
            field: 'sort'
        },
        {
            title: '状态',
            field: 'state',
            render: 'tag',
            custom: {
                0: 'warning',
                1: 'success'
            },
            replaceValue: {
                0: '未启用',
                1: '启用'
            }
        },
        { title: '描述', field: 'remark' },

        {
            title: '操作',
            fixed: 'right',
            align: 'center',
            width: '180',
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    title: '编辑',
                    type: 'primary',
                    icon: 'el-icon-EditPen',
                    render: 'basicButton',

                    click: async row => {
                        dialogFormVisible.value = true
                        dialogTitle.value = '前置机修改'
                        formData.value = JSON.parse(JSON.stringify(row))
                    }
                },
                {
                    name: 'edit',
                    title: '重启',
                    type: 'warning',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    disabled: row => {
                        return VITE_FLAG
                    },
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'warning',
                        title: '确定重启吗？'
                    },
                    click: row => {
                        askRestartProcess({
                            deviceRebootType: 1,
                            nodeId: row.id,
                            processNo: 1
                        }).then(res => {
                            ElMessage.success('重启成功')
                            tableStore.index()
                        })
                    }
                },

                {
                    name: 'del',
                    title: '删除',
                    type: 'danger',
                    icon: 'el-icon-Delete',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'danger',
                        title: '确定删除吗？'
                    },
                    click: row => {
                        if (hasDevices.value) {
                            ElMessage.warning('此前置机绑定了设备，无法删除！')
                            return
                        }

                        delNode(row.id).then(res => {
                            ElMessage.success('删除成功')
                            tableStore.index()
                        })
                    }
                },
                {
                    name: 'edit',
                    title: '分配终端',
                    type: 'primary',
                    icon: 'InfoFilled',
                    render: 'confirmButton',
                    popconfirm: {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        confirmButtonType: 'primary',
                        title: '确定分配终端吗？'
                    },
                    click: row => {
                        // if (!hasDevices.value) {
                        //     ElMessage.warning('此前置机下无设备，无法分配终端！')
                        //     return
                        // }
                        allotTerminal({
                            nodeId: row.id
                        }).then(res => {
                            ElMessage.success(res.message)
                            tableStore.index()
                        })
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        for (let key in tableStore.table.params) {
            if (tableStore.table.params[key] === '' && key !== 'nodeGrade' && key !== 'searchState') {
                delete tableStore.table.params[key]
            }
        }
    },
    loadCallback: () => {
        tableRef.value.getRef().setCurrentRow(tableStore.table.data[0])
        setTimeout(() => {
            currentChangeEvent()
        }, 100)
    }
})
const nodeId = ref('')
const hasDevices = ref(false)
/// 点击行
const currentChangeEvent = () => {
    // 确保 tableRef 和当前记录存在

    if (!tableRef.value || !tableRef.value.getRef().getCurrentRecord()) {
        loading.value = false
        dataSource.value = []
        hasDevices.value = false
        return
    }

    loading.value = true
    dataSource.value = []
    nodeDeviceTree({
        nodeId: tableRef.value.getRef().getCurrentRecord().id
    })
        .then(res => {
            nodeId.value = tableRef.value.getRef().getCurrentRecord().id
            // 检查返回的数据是否存在且不为空
            if (res.data && res.data.processDeviceList) {
                // 检查是否有设备绑定
                const hasAnyDevices = res.data.processDeviceList.some(
                    item => item.deviceInfoList && item.deviceInfoList.length > 0
                )
                hasDevices.value = hasAnyDevices

                dataSource.value = res.data.processDeviceList.filter(item => {
                    item.name = item.processNo + '号进程'
                    return true // 保持原有的过滤逻辑
                })
            } else {
                dataSource.value = []
                hasDevices.value = false
            }
            loading.value = false
        })
        .catch(() => {
            // 添加错误处理，确保 loading 状态也能关闭
            dataSource.value = []
            hasDevices.value = false
            loading.value = false
        })

    // const row = tableRef.value.getRef().getCurrentRecord()
}

// 重启进程
const restart = (data: any) => {
    // console.log('🚀 ~ restart ~ data:', data)
    askRestartProcess({
        deviceRebootType: null,
        nodeId: nodeId.value,
        processNo: data.processNo
    }).then(res => {
        ElMessage.success('重启成功')
        currentChangeEvent()
    })
}
const treeRef = ref()
// 树过滤
const change = val => {
    treeRef.value!.filter(filterText.value)
}
const edit = (data: any) => {
    // console.log('🚀 ~ edit ~ data:', data)
    processNo.value = data.processNo
    processId.value = data.id
    popUps.value = true
}
// 更新进程号
const bindTheProcess = () => {
    updateDeviceProcess({
        id: processId.value,
        processNo: processNo.value
    }).then(res => {
        ElMessage.success('修改成功！')
        popUps.value = false
        currentChangeEvent()
    })
}
const filterNode = (value: string, data: any, node: any) => {
    if (!value) return true
    // return data.name.includes(value)
    if (data.name) {
        return chooseNode(value, data, node)
    }
}

// 过滤父节点 / 子节点 (如果输入的参数是父节点且能匹配，则返回该节点以及其下的所有子节点；如果参数是子节点，则返回该节点的父节点。name是中文字符，enName是英文字符.
const chooseNode = (value: string, data: any, node: any) => {
    if ((data.subName + data.name).indexOf(value) !== -1) {
        return true
    }
    const level = node.level
    // 如果传入的节点本身就是一级节点就不用校验了
    if (level === 1) {
        return false
    }
    // 先取当前节点的父节点
    let parentData = node.parent
    // 遍历当前节点的父节点
    let index = 0
    while (index < level - 1) {
        // 如果匹配到直接返回，此处name值是中文字符，enName是英文字符。判断匹配中英文过滤
        if (parentData.data.name.indexOf(value) !== -1) {
            return true
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent
        index++
    }
    // 没匹配到返回false
    return false
}
const bind = () => {}

tableStore.table.params.orderBy = 'desc'
tableStore.table.params.nodeGrade = ''
tableStore.table.params.searchState = ''
provide('tableStore', tableStore)

// 新增
const add = () => {
    dialogFormVisible.value = true
    dialogTitle.value = '新增前置机'
}

// 确认
const onSubmit = () => {
    ruleFormRef.value.validate((valid: any) => {
        if (valid) {
            if (dialogTitle.value == '新增前置机') {
                addNode(formData.value).then(res => {
                    ElMessage.success('新增前置机')
                    resetForm()
                    tableStore.onTableAction('search', {})
                })
            } else {
                updateNode(formData.value).then(res => {
                    ElMessage.success('修改成功')
                    resetForm()
                    tableStore.onTableAction('search', {})
                })
            }
        }
    })
}
// 清空表格
const resetForm = () => {
    dialogFormVisible.value = false
    formData.value = {
        name: '',
        ip: '',
        nodeGrade: '',
        nodeDevNum: '',
        sort: '',
        remark: ''
    }
}

const handleInput = (val: string) => {
    formData.value.name = val.replace(/\s+/g, '')
}

onMounted(() => {
    setTimeout(() => {
        tableStore.index()
    }, 100)
})

const addMenu = () => {}
</script>
<style lang="scss" scoped>
.qrcode-label {
    position: absolute;
    top: 0;
    right: 0;
    z-index: -99;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 180px;
    height: 180px;
    padding: 10px;
    background: #fff;
    flex-direction: column;

    .qrcode-label-title {
        margin-bottom: 10px;
        font-size: 14px;
        font-weight: bold;
    }

    .qrcode-label-img {
        width: 140px;
        height: 140px;
    }
}
:deep(.default) {
    display: flex;
    .row--current {
        // background-color: var(--el-color-primary-light-8) !important;
    }
}
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    width: 300px;
}
.iconSpan {
    display: inline-block;
    width: 8px;
    height: 8px;
    margin-left: 3px;
    border-radius: 50%;
    margin-bottom: 2px;
}
</style>
