<template>
    <div class="devices-container">
        <!-- 参数缺失时的友好提示 -->
        <div v-if="!route.query.deliveryId" class="error-container">
            <el-result
                icon="warning"
                title="参数缺失"
                sub-title="缺少必要的参数，无法加载设备列表"
            >
                <template #extra>
                    <el-button type="primary" @click="goBack">返回上一页</el-button>
                </template>
            </el-result>
        </div>

        <!-- 正常内容 -->
        <div v-else>
            <div class="header-info">
                <el-page-header @back="goBack">
                    <template #content>
                        <div class="header-title">
                            <span class="text-large font-600 mr-3">
                                运送清单设备管理 - {{ route.query.deliveryNumber || '未知运单' }}
                            </span>
                        </div>
                    </template>
                </el-page-header>
            </div>

            <!-- 设备统计 -->
            <div class="statistics-box">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <el-statistic title="智能主机" :value="hostTotal">
                                <template #suffix>个</template>
                            </el-statistic>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <el-statistic title="智能耳标" :value="earTotal">
                                <template #suffix>个</template>
                            </el-statistic>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <el-statistic title="智能项圈" :value="collarTotal">
                                <template #suffix>个</template>
                            </el-statistic>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <el-statistic title="设备总数" :value="totalDevices">
                                <template #suffix>个</template>
                            </el-statistic>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 设备列表Tab -->
            <div class="main-container">
                <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                    <!-- 智能主机 -->
                    <el-tab-pane label="智能主机" name="host">
                        <el-table v-loading="hostLoading" :data="hostList" border>
                            <el-table-column label="设备ID" prop="deviceId" width="200"></el-table-column>
                            <el-table-column label="设备SN" prop="sn" width="200"></el-table-column>
                            <el-table-column label="运单号" prop="deliveryNumber"></el-table-column>
                            <el-table-column label="绑定时间" prop="bindTime"></el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="scope">
                                    <el-button type="danger" link @click="unbindDevice(scope.row, 1)">解绑</el-button>
                                </template>
                            </el-table-column>
                            <template #empty>
                                <div class="dataListOnEmpty">暂无数据</div>
                            </template>
                        </el-table>
                    </el-tab-pane>

                    <!-- 智能耳标 -->
                    <el-tab-pane label="智能耳标" name="ear">
                        <el-table v-loading="earLoading" :data="earList" border>
                            <el-table-column label="设备ID" prop="deviceId" width="200"></el-table-column>
                            <el-table-column label="运单号" prop="deliveryNumber"></el-table-column>
                            <el-table-column label="重量(kg)" prop="weight"></el-table-column>
                            <el-table-column label="车牌号" prop="carNumber"></el-table-column>
                            <el-table-column label="绑定时间" prop="bindTime"></el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="scope">
                                    <el-button type="danger" link @click="unbindDevice(scope.row, 2)">解绑</el-button>
                                </template>
                            </el-table-column>
                            <template #empty>
                                <div class="dataListOnEmpty">暂无数据</div>
                            </template>
                        </el-table>
                        <pagination v-model:limit="earForm.pageSize" v-model:page="earForm.pageNum" :total="earTotal" @pagination="getEarList" />
                    </el-tab-pane>

                    <!-- 智能项圈 -->
                    <el-tab-pane label="智能项圈" name="collar">
                        <el-table v-loading="collarLoading" :data="collarList" border>
                            <el-table-column label="设备SN" prop="sn" width="200"></el-table-column>
                            <el-table-column label="设备ID" prop="deviceId" width="200"></el-table-column>
                            <el-table-column label="运单号" prop="deliveryNumber"></el-table-column>
                            <el-table-column label="车牌号" prop="carNumber"></el-table-column>
                            <el-table-column label="绑定时间" prop="bindTime"></el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="scope">
                                    <el-button type="danger" link @click="unbindDevice(scope.row, 4)">解绑</el-button>
                                </template>
                            </el-table-column>
                            <template #empty>
                                <div class="dataListOnEmpty">暂无数据</div>
                            </template>
                        </el-table>
                        <pagination v-model:limit="collarForm.pageSize" v-model:page="collarForm.pageNum" :total="collarTotal" @pagination="getCollarList" />
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { pageDeviceList } from '@/api/abroad.js';
import { unbindDevice as unbindDeviceAPI } from '@/api/shipping.js';

const route = useRoute();
const router = useRouter();

const activeTab = ref('host');
const hostLoading = ref(false);
const earLoading = ref(false);
const collarLoading = ref(false);

const hostList = ref([]);
const earList = ref([]);
const collarList = ref([]);

const hostTotal = ref(0);
const earTotal = ref(0);
const collarTotal = ref(0);

const earForm = reactive({
    pageNum: 1,
    pageSize: 10,
});

const collarForm = reactive({
    pageNum: 1,
    pageSize: 10,
});

// 计算设备总数
const totalDevices = computed(() => {
    return hostTotal.value + earTotal.value + collarTotal.value;
});

// 返回上一页
const goBack = () => {
    router.back();
};

// Tab切换
const handleTabChange = (tabName) => {

};

// 获取智能主机列表
const getHostList = async () => {
    if (!route.query.deliveryId) {
        console.warn('deliveryId为空，跳过主机列表查询');
        return;
    }

    hostLoading.value = true;
    try {
        const res = await pageDeviceList({
            pageNum: 1,
            pageSize: 100,
            deliveryId: parseInt(route.query.deliveryId),
            deviceType: 1,
        });


        if (res.code === 200) {
            const hostDevices = res.data.filter(device => device.deviceType === 1 || device.deviceType === '1');
            hostList.value = hostDevices || [];
            hostTotal.value = hostDevices.length || 0;
        } else {
            ElMessage.error(res.msg || '获取主机设备失败');
        }
    } catch (error) {
        console.error('获取主机设备失败:', error);
        ElMessage.error('获取主机设备失败');
    } finally {
        hostLoading.value = false;
    }
};

// 获取智能耳标列表
const getEarList = async () => {
    if (!route.query.deliveryId) {
        console.warn('deliveryId为空，跳过耳标列表查询');
        return;
    }

    earLoading.value = true;
    try {
        const res = await pageDeviceList({
            pageNum: earForm.pageNum,
            pageSize: earForm.pageSize,
            deliveryId: parseInt(route.query.deliveryId),
            deviceType: 2,
        });


        if (res.code === 200) {
            const earDevices = res.data.filter(device => device.deviceType === 2 || device.deviceType === '2');
            earList.value = earDevices || [];
            earTotal.value = earDevices.length || 0;
        } else {
            ElMessage.error(res.msg || '获取耳标设备失败');
        }
    } catch (error) {
        console.error('获取耳标设备失败:', error);
        ElMessage.error('获取耳标设备失败');
    } finally {
        earLoading.value = false;
    }
};

// 获取智能项圈列表
const getCollarList = async () => {
    if (!route.query.deliveryId) {
        console.warn('deliveryId为空，跳过项圈列表查询');
        return;
    }

    collarLoading.value = true;
    try {
        const res = await pageDeviceList({
            pageNum: collarForm.pageNum,
            pageSize: collarForm.pageSize,
            deliveryId: parseInt(route.query.deliveryId),
            deviceType: 4,
        });


        if (res.code === 200) {
            const collarDevices = res.data.filter(device => device.deviceType === 4 || device.deviceType === '4');
            collarList.value = collarDevices || [];
            collarTotal.value = collarDevices.length || 0;
        } else {
            ElMessage.error(res.msg || '获取项圈设备失败');
        }
    } catch (error) {
        console.error('获取项圈设备失败:', error);
        ElMessage.error('获取项圈设备失败');
    } finally {
        collarLoading.value = false;
    }
};

// 解绑设备
const unbindDevice = (device, deviceType) => {
    const deviceTypeName = deviceType === 1 ? '智能主机' : (deviceType === 2 ? '智能耳标' : '智能项圈');
    const deviceIdDisplay = device.deviceId || device.sn;

    ElMessageBox.confirm(
        `确定要解绑${deviceTypeName}设备 ${deviceIdDisplay} 吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            const res = await unbindDeviceAPI(device.deviceId || device.sn);
            if (res.code === 200) {
                ElMessage.success('设备解绑成功');
                // 刷新对应列表
                if (deviceType === 1) {
                    getHostList();
                } else if (deviceType === 2) {
                    getEarList();
                } else if (deviceType === 4) {
                    getCollarList();
                }
            } else {
                ElMessage.error(res.msg || '设备解绑失败');
            }
        } catch (error) {
            console.error('设备解绑失败:', error);
            ElMessage.error('设备解绑失败');
        }
    }).catch(() => {
        ElMessage.info('已取消解绑');
    });
};

onMounted(() => {

    if (!route.query.deliveryId) {
        console.warn('deliveryId为空，无法加载设备列表');
        ElMessage.error('缺少必要的参数，请从列表页面点击"查看设备"按钮进入');
        return;
    }

    // 加载所有设备列表
    getHostList();
    getEarList();
    getCollarList();
});
</script>

<style lang="less" scoped>
.devices-container {
    padding: 20px;
}

.error-container {
    padding: 50px;
    text-align: center;
}

.header-info {
    margin-bottom: 20px;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
}

.statistics-box {
    margin: 20px 0;
}

.main-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
}

.dataListOnEmpty {
    padding: 50px;
    text-align: center;
    color: #909399;
    font-size: 14px;
}
</style>

