<template>
    <div class="app-container">
        <div ref="topContainerRef">
            <el-form :model="queryParams" :inline="true" v-show="showSearch" label-width="100px">
                <el-form-item label="机器人名称" prop="name">
                    <el-input v-model="queryParams.name" placeholder="请输入机器人名称" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="IP地址" prop="ipAddress">
                    <el-input v-model="queryParams.ipAddress" placeholder="请输入IP地址" clearable
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
        </div>

        <div :style="containerHeight">
            <el-table v-loading="loading" height="100%" style="width: 100%" :data="tableDataList">
                <el-table-column label="机器人名称" align="center" prop="robotName" />
                <el-table-column label="机器人类型" align="center" prop="robotType" />
                <el-table-column label="IP地址" align="center" prop="ipAddress" min-width="160" show-overflow-tooltip />
                <el-table-column label="电量" align="center" prop="batteryLevel" />
                <el-table-column label="状态" align="center" prop="status" />
                <el-table-column label="当前地图" align="center" prop="currentMapName" />
                <el-table-column label="操作" class-name="small-padding fixed-width" width="200" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>

        <!-- 添加或修改语料库对话框 -->
        <el-dialog :title="title" v-model="open" width="580px" append-to-body>
            <el-form ref="robotRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="机器人名称" prop="robotName">
                    <el-input v-model="form.robotName" placeholder="请输入机器人名称" />
                </el-form-item>
                <el-form-item label="机器人类型" prop="robotType">
                    <el-select v-model="form.robotType" placeholder="请输入机器人类型" clearable style="width: 100%">
                        <el-option v-for="type in robot_type" :key="type.value" :label="type.label"
                            :value="type.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="IP地址" prop="ipAddress">
                    <el-input class="test" v-model="form.ipAddress" placeholder="请输入IP地址" @input="ipChange">
                        <template #append>
                            <div class="connection" :class="{ success: connectionStatus }" @click="testConnection">
                                {{ connectionStatus ? '连接成功' : '测试连接' }}
                            </div>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="端口号" prop="port">
                    <el-input v-model="form.port" placeholder="请输入端口号" />
                </el-form-item>
                <el-form-item label="地图选择" prop="currentMapId">
                    <el-select v-model="form.currentMapId" placeholder="请选择地图" clearable style="width: 100%">
                        <el-option v-for="map in mapList" :key="map.value" :label="map.label" :value="map.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Corpus">
import { ElMessage, ElMessageBox } from "element-plus";
import { useContainerHeight } from "@/hooks/tableHeight";
import { addRobot, updateRobot, deleteRobot, getRobotList } from "../../../api/inspection/robot";
import { getMapList } from "../../../api/inspection/map";

const { proxy } = getCurrentInstance();
const { robot_type } = proxy.useDict(
    "robot_type"
);

const robotRef = ref();

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const tableDataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);

const total = ref(0);
const title = ref("");
const isNew = ref(true);

const mapList = ref([])

const data = reactive({
    form: {
        robotName: "",
        robotType: "",
        ipAddress: "",
        port: "",
        currentMapId: ""
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
    },
    rules: {
        robotName: [
            { required: true, message: "请输入机器人名称", trigger: "change" },
        ],
        robotType: [
            { required: true, message: "请输入机器人类型", trigger: "change" },
        ],
        ipAddress: [
            { required: true, message: "请输入IP地址", trigger: "change" },
            {
                pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
                message: "请输入正确的IP地址格式（例如：192.168.1.1）",
                trigger: "change"
            }
        ],
        port: [
            { required: true, message: "请输入端口号", trigger: "blur" },
            {
                pattern: /^\d+$/,
                message: "端口号只能为数字",
                trigger: "change"
            }
        ]
    },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询语料库列表 */
function getList() {
    loading.value = true;
    getRobotList(queryParams.value).then((response) => {
        tableDataList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    }).finally(() => {
        loading.value = false;
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    robotRef.value.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    queryParams.value.name = null;
    queryParams.value.ipAddress = null;
    handleQuery();
}


/** 新增按钮操作 */
function handleAdd() {
    open.value = true;
    title.value = "添加机器人";
    isNew.value = true;
}

const connectionStatus = ref(false);
/**
 * 测试连接按钮操作
 */
const testConnection = () => {
    // 模拟测试连接的逻辑
    if (form.value.ipAddress) {
        if (Math.random() > 0.5) {
            connectionStatus.value = true;
            ElMessage.success("连接成功！");
        } else {
            connectionStatus.value = false;
            ElMessage.error("连接失败！");
        }
    } else {
        ElMessage.error("请输入IP地址进行测试连接！");
    }
}

const ipChange = () => {
    connectionStatus.value = false; // IP地址改变后重置连接状态
}

/** 修改按钮操作 */
function handleUpdate(row) {
    form.value = { ...row };
    open.value = true;
    title.value = "修改机器人";
    isNew.value = false;
}

/** 提交按钮 */
function submitForm() {
    robotRef.value.validate((valid) => {
        if (valid) {
            if (isNew.value) {
                // 调用新增接口
                addRobot(form.value).then(() => {
                    ElMessage.success("机器人添加成功！");
                    getList();
                    reset();
                    open.value = false;
                });
            } else {
                // 调用修改接口
                updateRobot(form.value).then(() => {
                    ElMessage.success("机器人修改成功！");
                    getList();
                    reset();
                    open.value = false;
                });
            }
        } else {
            ElMessage.error("请完善表单信息！");
            return false;
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    ElMessageBox.confirm('确定要删除该机器人吗？', '提示', {}).then(() => {
        deleteRobot(row.id).then(() => {
            ElMessage.success("机器人删除成功！");
            getList();
        });
    }).catch(() => {
        // 用户取消删除
    });
}

const getMapArr = () => {
    getMapList({
        pageNum: 1,
        pageSize: 10000,
    }).then((response) => {
        mapList.value = response.rows.map(item => ({
            label: item.mapName,
            value: item.id
        }));
    });
}

getList();
getMapArr();
</script>
<style lang="scss" scoped>
.test {
    position: relative;

    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;

        &::after {
            content: '';
            position: absolute;
            right: 0;
            top: 0;
            bottom: 0;
            width: 1px;
            background-color: #fff;
            /* 覆盖右边阴影，需要与背景色相同 */
        }
    }

    :deep(.el-input-group__append) {
        background-color: transparent;

        .connection {
            background: #dcdfdf;
            font-size: 12px;
            padding: 0 10px;
            border-radius: 4px;
            cursor: pointer;
            height: calc(100% - 8px);
            display: flex;
            align-items: center;
        }

        .success {
            background: #67c23a;
            color: #fff;
        }
    }
}
</style>