<template>
    <el-dialog v-model="data.dialogVisible" title="分配设备" style="width: 800px; padding-bottom: 20px">
        <div class="top-box">
            <div class="top-item">
                <div class="label">装车数量</div>
                <el-input v-model="data.ratedQuantity" style="max-width: 300px" disabled> <template #append>个</template></el-input>
            </div>
            <div class="top-item">
                <div class="label1">本次已选择装车设备</div>
                <el-input v-model="data.selectTotal" style="max-width: 300px" disabled> <template #append>个</template></el-input>
            </div>
        </div>
        <div class="search-box">
            <el-select v-model="data.deviceType" placeholder="选择设备类型" style="width: 150px; margin-right: 10px;" @change="onDeviceTypeChange">
                <el-option label="全部设备" value="" />
                <el-option label="智能耳标" value="2" />
                <el-option label="智能项圈" value="4" />
                <el-option label="智能主机" value="1" />
            </el-select>
            <el-input v-model="data.deviceId" placeholder="请输入设备编号" style="width: 200px" />
            <div class="search-right">
                <el-button @click="resetClick">重置</el-button>
                <el-button type="primary" @click="searchClick">搜索</el-button>
            </div>
        </div>
        <el-table
            ref="multipleTableRef"
            v-loading="data.dataListLoading"
            :data="data.rows"
            border
            element-loading-text="数据加载中..."
            @selection-change="handleSelectionChange"
            row-key="deviceId"
        >
            <el-table-column type="selection" width="55" reserve-selection />
            <el-table-column label="设备编号" prop="deviceId"></el-table-column>
            <el-table-column label="设备类型" prop="deviceType">
                <template #default="scope">
                    <el-tag v-if="scope.row.deviceType === 1" type="info">智能主机</el-tag>
                    <el-tag v-else-if="scope.row.deviceType === 2" type="success">智能耳标</el-tag>
                    <el-tag v-else-if="scope.row.deviceType === 4" type="primary">智能项圈</el-tag>
                    <el-tag v-else type="warning">未知类型</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="设备状态" prop="status">
                <template #default>
                    <el-tag type="warning">未分配</el-tag>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-model:limit="form.pageSize" v-model:page="form.pageNum" :total="data.total" @pagination="getDataList" />
        <template #footer>
            <span class="dialog-footer">
                <el-button :loading="data.saveLoading" type="primary" @click="onClickSave">保存</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { iotDeviceAssignableList, iotDeviceAssign } from '@/api/hardware.js';
import request from '@/utils/request.js';

const emits = defineEmits();
const multipleTableRef = ref(null);
const data = reactive({
    dialogVisible: false,
    deliveryId: '',
    dataListLoading: false,
    rows: [],
    total: 0,
    ratedQuantity: 0, // 装车数量
    selectTotal: 0,
    deviceId: '',
    deviceType: '', // 设备类型：1=智能主机，2=智能耳标，4=智能项圈
    deviceIds: [],
    licensePlate: '', // 车牌号
});
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});
// 设备类型变化
const onDeviceTypeChange = () => {
    form.pageNum = 1;
    getDataList();
};

// 重置
const resetClick = () => {
    data.deviceId = '';
    data.deviceType = '';
    form.pageNum = 1;
    getDataList();
};

// 搜索
const searchClick = () => {
    form.pageNum = 1;
    getDataList();
};
const getDataList = async () => {
    data.dataListLoading = true;
    
    try {

        const params = {
            pageNum: form.pageNum,
            pageSize: form.pageSize,
            deviceId: data.deviceId || '',
            deviceType: data.deviceType ? parseInt(data.deviceType) : null,
        };
        

        const res = await iotDeviceAssignableList(params);

        if (res.code === 200) {
            const rawData = res.data?.rows || [];
            const total = res.data?.total || 0;
            
            // 处理数据：添加设备类型名称
            data.rows = rawData.map(item => {
                const processedItem = { ...item };
                
                // 根据设备类型自动添加设备类型名称
                switch (item.deviceType) {
                    case 1: // 主机
                        processedItem.deviceTypeName = '智能主机';
                        break;
                    case 2: // 耳标
                        processedItem.deviceTypeName = '智能耳标';
                        break;
                    case 4: // 项圈
                        processedItem.deviceTypeName = '智能项圈';
                        break;
                    default:
                        processedItem.deviceTypeName = '未知设备';
                        break;
                }
                

                return processedItem;
            });
            
            data.total = total;
            data.dataListLoading = false;
            

        } else {
            console.error('API返回错误:', res);
            data.dataListLoading = false;
            data.rows = [];
            data.total = 0;
        }
        
    } catch (error) {
        console.error('查询设备列表失败:', error);
        data.dataListLoading = false;
        data.rows = [];
        data.total = 0;
    }
};
// 勾选
const handleSelectionChange = (val) => {
    data.selectTotal = val.length;
    data.deviceIds = val.map((item) => {
        return {
            deviceId: item.deviceId,
            deviceTypeId: item.deviceType, // 使用deviceType字段
        };
    });
};
// 保存按钮
const onClickSave = () => {
    if (data.deviceIds.length == 0) {
        ElMessage.error('请选择设备编号');
        return;
    }
    
    // 提取设备ID列表
    const deviceIdList = data.deviceIds.map(item => item.deviceId);
    
    const params = {
        deviceIds: deviceIdList,
        deliveryId: parseInt(data.deliveryId), // 装车订单ID
        carNumber: data.licensePlate, // 车牌号
    };
    

    data.saveLoading = true;
    iotDeviceAssign(params)
        .then((res) => {
            data.saveLoading = false;

            if (res.code === 200) {
                ElMessage({
                    message: res.msg,
                    type: 'success',
                });
                emits('success');
                data.dialogVisible = false;
                if (multipleTableRef.value) {
                    multipleTableRef.value.clearSelection();
                }
                data.deviceIds = [];
                data.deliveryId = '';
                data.ratedQuantity = '';
                data.licensePlate = '';
            } else {
                ElMessage.error(res.msg);
            }
        })
        .catch((err) => {
            console.error('设备分配失败:', err);
            data.saveLoading = false;
            ElMessage.error('设备分配失败');
        });
};
const handleClose = () => {
    data.dialogVisible = false;
};
const onShowAssignDialog = (row) => {
    data.dialogVisible = true;

    if (row) {
        data.deliveryId = row.id;
        data.ratedQuantity = row.ratedQuantity ? row.ratedQuantity : 0;
        data.licensePlate = row.licensePlate || ''; // 获取车牌号
        getDataList();
        if (multipleTableRef.value) {
            multipleTableRef.value.clearSelection();
        }
    }
};
defineExpose({
    onShowAssignDialog,
});
</script>

<style lang="less" scoped>
.top-box {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .top-item {
        display: flex;
        align-items: center;
        .label {
            width: 75px;
            margin-right: 10px;
        }
        .label1 {
            width: 140px;
            margin-right: 10px;
        }
    }
}
.search-box {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
}
</style>
