<template>
    <el-dialog v-model="data.dialogVisible" :title="data.title" style="width: 650px; padding-bottom: 20px" :before-close="handleClose">
        <el-tabs v-model="data.activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="未分配" name="first">
                <el-button type="primary" @click="batchAssign" :loading="data.assignLoading">批量分配</el-button>
                <el-table
                    :data="data.rows"
                    border
                    v-loading="data.dataListLoading"
                    element-loading-text="数据加载中..."
                    style="width: 100%"
                    :row-key="getRowKey"
                    @selection-change="unassignedSelected"
                    ref="multipleTableUnRef"
                >
                    <el-table-column type="selection" reserve-selection width="55" />
                    <el-table-column label="设备类型" prop="deviceTypeName"> </el-table-column>
                    <el-table-column label="设备编号" prop="deviceId"> </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button link type="primary" @click="assignClick(scope.row.deviceId)">分配</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="已分配" name="second">
                <el-button type="primary" @click="batchDel" :loading="data.delLoading">批量删除</el-button>
                <el-table
                    :data="data.rows"
                    border
                    v-loading="data.dataListLoading"
                    element-loading-text="数据加载中..."
                    style="width: 100%"
                    :row-key="getRowKey"
                    @selection-change="assignedSelected"
                    ref="multipleTableRef"
                >
                    <el-table-column type="selection" reserve-selection width="55" />
                    <el-table-column label="设备类型" prop="deviceTypeName"> </el-table-column>
                    <el-table-column label="设备编号" prop="deviceId"> </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button link type="primary" @click="delClick(scope.row.deviceId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <pagination 
            v-model:page="form.pageNum" 
            v-model:limit="form.pageSize" 
            :total="data.total || 0" 
            @pagination="getDataList" 
        />
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deviceList, deviceAssign, deviceDel, tenantList } from '@/api/sys.js';
import { queryEarTagList, queryHostList } from '@/api/device.js';
import { iotDeviceAssignableList, iotDeviceAssign, iotDeviceAssignToTenant, iotDeviceUnassignFromTenant } from '@/api/hardware.js';

const emits = defineEmits(['success']);
const multipleTableUnRef = ref(null);
const multipleTableRef = ref(null);
const data = reactive({
    dialogVisible: false,
    title: '设备分配',
    activeName: 'first',
    unassignedSelect: [],
    assignedSelect: [],
    rows: [],
    dataListLoading: false,
    total: 0,
    deviceType: '', // 设备类型1：主机，2：耳标，4：项圈
    allotType: '', // 是否已分配标识，0：未分配，1：已分配
    tenantId: '', // 租户id
    assignLoading: false,
    delLoading: false,
    deliveryId: null, // 装车订单ID
    deliveryNumber: '', // 运单号
    carNumber: '', // 车牌号
    mode: 'delivery', // 分配模式：'delivery' 或 'tenant'
});
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});
const handleClick = (tab, event) => {

    data.activeName = tab.props.name;
    data.allotType = data.activeName === 'first' ? '0' : '1';
    form.pageNum = 1;
    form.pageSize = 10;
    
    // 重新获取数据并过滤
    getDataList();
};
// 列表
const getDataList = () => {

    data.dataListLoading = true;
    
    let params;
    if (data.mode === 'tenant') {
        // 租户分配模式：传递 mode='tenant' 参数，让后端根据 tenant_id 判断
        params = {
            ...form,
            deviceType: data.deviceType,
            allotType: data.allotType,
            mode: 'tenant', // ✅ 关键：明确告诉后端这是租户模式
        };
        
        // 如果是"已分配"标签页，才传递 tenantId（用于过滤该租户的设备）
        if (data.allotType === '1') {
            params.tenantId = data.tenantId;
        }
        

    } else {
        // 装车订单分配模式：传递 mode='delivery' 参数（或不传，默认为 delivery）
        params = {
            ...form,
            deviceType: data.deviceType,
            allotType: data.allotType,
            mode: 'delivery', // ✅ 明确告诉后端这是装车订单模式
            tenantId: data.tenantId,
        };

    }
    

    // 使用新的IoT设备API

    const apiCall = iotDeviceAssignableList(params);
    
    apiCall
        .then((res) => {
            data.dataListLoading = false;
            if (res.code == 200) {
                let rawData = [];
                let total = 0;
                
                // 处理不同的数据结构
                if (res.data.list) {
                    // device.js 中的API返回 { list, total }
                    rawData = res.data.list || [];
                    total = res.data.total || 0;

                } else {
                    // sys.js 中的API返回 { rows, total }
                    rawData = res.data?.rows || [];
                    total = res.data?.total || 0;
                }
                
                // 处理数据：添加设备类型和分配状态
                data.rows = rawData.map(item => {
                    const processedItem = { ...item };
                    
                    // 根据设备类型自动添加设备类型名称
                    switch (data.deviceType) {
                        case '1': // 主机
                            processedItem.deviceTypeName = '智能主机';
                            break;
                        case '2': // 耳标
                            processedItem.deviceTypeName = '智能耳标';
                            break;
                        case '4': // 项圈
                            processedItem.deviceTypeName = '智能项圈';
                            break;
                        default:
                            processedItem.deviceTypeName = '未知设备';
                            break;
                    }
                    
                    // ✅ 根据模式判断分配状态
                    // ⚠️ 关键：租户模式和装车订单模式是完全独立的！
                    if (data.mode === 'tenant') {
                        // 租户模式：仅根据 tenantId 判断分配状态（忽略 deliveryId）
                        processedItem.isAssigned = !!(item.tenantId && item.tenantId !== null);
                    } else {
                        // 装车订单模式：仅根据 deliveryId 判断分配状态（忽略 tenantId）
                        // 注意：这里应该用 deliveryId，而不是 deliveryNumber
                        processedItem.isAssigned = !!(item.deliveryId && item.deliveryId !== null);
                    }
                    

                    return processedItem;
                });
                

                // 根据当前标签页过滤数据
                if (data.activeName === 'first') {
                    // 未分配标签页：显示未分配的设备
                    const beforeFilter = data.rows.length;
                    data.rows = data.rows.filter(item => !item.isAssigned);

                } else if (data.activeName === 'second') {
                    // 已分配标签页：显示已分配的设备
                    const beforeFilter = data.rows.length;
                    data.rows = data.rows.filter(item => item.isAssigned);

                }
                
                data.total = data.rows.length;
            } else {
                console.error('=== API 返回错误 ===', res);
                ElMessage.error(res.msg || '获取数据失败');
            }
        })
        .catch((error) => {
            console.error('=== API 调用失败 ===', error);
            data.dataListLoading = false;
            console.error('获取设备列表失败:', error);
            data.rows = [];
            data.total = 0;
        });
};
// 未分配选中
const unassignedSelected = (val) => {
    data.unassignedSelect = val.map((item) => item.deviceId);
};
// 批量绑定
const batchAssign = () => {
    if (data.unassignedSelect.length === 0) {
        ElMessage.error('请选择设备编号');
        return;
    }
    data.assignLoading = true;
    
    let params;
    let apiCall;
    
    if (data.mode === 'tenant') {
        // 租户分配模式
        params = {
            deviceIds: data.unassignedSelect,
            tenantId: data.tenantId,
        };
        apiCall = iotDeviceAssignToTenant(params);
    } else {
        // 装车订单分配模式
        params = {
            deviceIds: data.unassignedSelect,
            deliveryId: data.deliveryId,
            carNumber: data.carNumber,
        };
        apiCall = iotDeviceAssign(params);
    }
    
    apiCall
        .then((res) => {
            data.assignLoading = false;
            if (res.code === 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                });
                getDataList();
                emits('success'); // 通知父组件刷新
            } else {
                ElMessage.error(res.msg);
            }
        })
        .catch((err) => {
            data.assignLoading = false;
            ElMessage.error('设备分配失败');
        });
};
//
// 已分配选中
const assignedSelected = (val) => {
    data.assignedSelect = val.map((item) => item.deviceId);
};
// 单个分配
const assignClick = (deviceId) => {
    let apiCall;
    if (data.mode === 'tenant') {
        // 租户模式：分配设备到租户
        const params = {
            deviceIds: [deviceId],
            tenantId: data.tenantId,
        };
        apiCall = iotDeviceAssignToTenant(params);
    } else {
        // 装车订单模式：分配设备到装车订单
        const params = {
            deviceIds: [deviceId],
            deviceType: data.deviceType,
            tenantId: data.tenantId,
        };
        apiCall = deviceAssign(params);
    }
    
    apiCall
        .then((res) => {
            if (res.code === 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                });
                getDataList();
                emits('success'); // 通知父组件刷新
            } else {
                ElMessage.error(res.msg);
            }
        })
        .catch(() => {});
};
// 批量删除（解绑）
const batchDel = () => {
    if (data.assignedSelect.length === 0) {
        ElMessage.error('请选择设备编号');
        return;
    }
    ElMessageBox.confirm('请确认是否批量解绑', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
    }).then(() => {
        data.delLoading = true;
        
        let apiCall;
        if (data.mode === 'tenant') {
            // 租户模式：解绑设备（将tenant_id设置为空）
            const params = {
                deviceIds: data.assignedSelect,
            };
            apiCall = iotDeviceUnassignFromTenant(params);
        } else {
            // 装车订单模式：取消分配设备
            const unassignParams = {
                deviceIds: data.assignedSelect,
                deliveryId: null, // 设置为null表示取消分配
                carNumber: null,
            };
            apiCall = iotDeviceAssign(unassignParams);
        }
        
        apiCall.then((res) => {
            data.delLoading = false;
            if (res.code === 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                });
                getDataList();
            } else {
                ElMessage.error(res.msg);
            }
        });
    });
};
// 单个删除
const delClick = (id) => {
    ElMessageBox.confirm('请确认是否删除', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
    }).then(() => {
        let apiCall;
        if (data.mode === 'tenant') {
            // 租户模式：解绑设备（将tenant_id设置为空）
            const params = {
                deviceIds: [id],
            };
            apiCall = iotDeviceUnassignFromTenant(params);
        } else {
            // 装车订单模式：取消分配设备
            const unassignParams = {
                deviceIds: [id],
                deliveryId: null, // 设置为null表示取消分配
                carNumber: null,
            };
            apiCall = iotDeviceAssign(unassignParams);
        }
        
        apiCall.then((res) => {
            if (res.code === 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                });
                getDataList();
                emits('success'); // 通知父组件刷新
            } else {
                ElMessage.error(res.msg);
            }
        });
    });
};
const getRowKey = (row) => {
    return row.id;
};
const onShowDialog = (tenantId, deviceType, deliveryId, deliveryNumber, carNumber, mode = 'delivery') => {

    data.dialogVisible = true;
    data.activeName = 'first';
    data.deviceType = deviceType;
    data.allotType = '0';
    data.tenantId = tenantId;
    data.deliveryId = deliveryId;
    data.deliveryNumber = deliveryNumber;
    data.carNumber = carNumber;
    data.mode = mode; // 新增：分配模式 'delivery' 或 'tenant'
    
    // 根据模式设置标题
    if (mode === 'tenant') {
        data.title = '租户设备分配';
    } else {
        data.title = '设备分配';
    }
    

    getDataList();
    if (multipleTableUnRef.value) {
        multipleTableUnRef.value.clearSelection();
    }
    if (multipleTableRef.value) {
        multipleTableRef.value.clearSelection();
    }
};
const handleClose = () => {
    data.dialogVisible = false;
    emits('success');
};

defineExpose({
    onShowDialog,
});
</script>

<style lang="less" scoped></style>
