<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef" @change="searchChange"> </base-search>

        <div class="main-container">
            <el-table v-loading="dataListLoading" :data="form1.tableData" style="width: 100%" border>
                <el-table-column prop="deliveryNumber" label="运单号" />
                <el-table-column prop="licensePlate" label="车牌号" />
                <el-table-column label="车身照片" prop="" width="160">
                    <template #default="scope">
                        <el-image
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carFrontPhoto ? scope.row.carFrontPhoto : ''"
                            fit="cover"
                            :preview-src-list="[scope.row.carFrontPhoto] ? [scope.row.carFrontPhoto] : []"
                            preview-teleported
                        >
                            <template #error>
                                <div
                                    style="width: 50px; height: 50px; display: flex; justify-content: center; align-items: center"
                                    class="image-slot"
                                >
                                    <el-icon style="font-size: 50px"><Picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                        <el-image
                            style="width: 50px; height: 50px; margin-right: 10px"
                            :src="scope.row.carBehindPhoto ? scope.row.carBehindPhoto : ''"
                            fit="cover"
                            :preview-src-list="[scope.row.carBehindPhoto] ? [scope.row.carBehindPhoto] : []"
                            preview-teleported
                        >
                            <template #error>
                                <div
                                    style="width: 50px; height: 50px; display: flex; justify-content: center; align-items: center"
                                    class="image-slot"
                                >
                                    <el-icon style="font-size: 50px"><Picture /></el-icon>
                                </div>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="startLocation" label="起始地" />
                <el-table-column prop="endLocation" label="送达目的地" />
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column prop="estimatedDeliveryTime" label="预计送达时间" />
                <el-table-column prop="driverName" label="司机姓名" />
                <el-table-column prop="createByName" label="创建人" />
                <el-table-column label="预警类型" prop="warningType">
                    <template #default="scope">
                        <el-tag type="warning" v-if="scope.row.warningType == 3">运输距离预警</el-tag>
                        <el-tag type="danger" v-if="scope.row.warningType == 2">数量盘单预警</el-tag>
                        <el-tag type="info" v-if="scope.row.warningType == 4">设备停留预警</el-tag>
                        <el-tag type="danger" v-if="scope.row.warningType == 5">高温预警</el-tag>
                        <el-tag type="info" v-if="scope.row.warningType == 6">低温预警</el-tag>
                        <el-tag type="warning" v-if="scope.row.warningType == 7">位置偏离预警</el-tag>
                        <el-tag type="danger" v-if="scope.row.warningType == 8">延误预警</el-tag>
                        <el-tag type="success" v-if="scope.row.warningType == 9">超前到达预警</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="warningTime" label="预警时间" />
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" link @click="viewDetail(scope.row)">查看详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-model:limit="form.pageSize" v-model:page="form.pageNum" :total="form1.total" @pagination="getList" />
        </div>
        
        <!-- 预警详情对话框 -->
        <warning-detail-dialog ref="detailDialogRef" />
    </div>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import warningDetailDialog from './warningDetailDialog.vue';
import { warningLogList, warningDetail } from '~/api/hardware.js';

const dataListLoading = ref(false);
const baseSearchRef = ref();
const detailDialogRef = ref();
const form = reactive({
    pageSize: 10,
    pageNum: 1,

    // deliveryNumber: '',
    // licensePlate: '',
    // warningType: '',
    // createTime: '',
});
const form1 = reactive({
    tableData: [],
    total: 0,
});
const searchFrom = () => {
    form.pageNum = 1;
    getList();
};

const searchChange = (val) => {

    // 在这里可以处理搜索条件变化的逻辑
};

const formItemList = reactive([
    {
        label: '运单号',
        type: 'input',
        param: 'deliveryNumber',
        labelWidth: 65,
        span: 7,
    },
    {
        label: '车牌号',
        type: 'input',
        param: 'licensePlate',
        labelWidth: 65,
        span: 7,
    },
    {
        label: '创建时间',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间',
        type: 'daterange',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        param: 'myTimes',
        span: 7,
    },
    {
        label: '预警类型',
        type: 'select',
        selectOptions: [
            { value: 2, text: '数量盘单预警' },
            { value: 3, text: '运输距离预警' },
            { value: 4, text: '设备停留预警' },
            { value: 5, text: '高温预警' },
            { value: 6, text: '低温预警' },
            { value: 7, text: '位置偏离预警' },
            { value: 8, text: '延误预警' },
            { value: 9, text: '超前到达预警' },
        ],
        param: 'warningType',
        span: 7,
    },
]);
const getList = () => {
    dataListLoading.value = true;
    const params = {
        ...form,
        ...baseSearchRef.value.penetrateParams(),
    };
    if (baseSearchRef.value.penetrateParams().myTimes) {
        if (baseSearchRef.value.penetrateParams().myTimes && baseSearchRef.value.penetrateParams().myTimes.length > 0) {
            params.startTime = baseSearchRef.value.penetrateParams().myTimes[0];
            params.endTime = baseSearchRef.value.penetrateParams().myTimes[1];
        }
    }
    warningLogList(params)
        .then((ret) => {
            form1.tableData = ret.data.rows;
            form1.total = ret.data.total;
            dataListLoading.value = false;
        })
        .catch(() => {
            dataListLoading.value = false;
        });
};

// 查看预警详情
const viewDetail = async (row) => {

    try {
        // ✅ 调用后端接口获取完整的预警详情（包括设备位置信息）
        const res = await warningDetail(row.id);
        
        if (res.code === 200 && res.data) {
            const detailData = res.data;
            
            // ✅ 修复：使用列表中的预警类型，而不是后端API返回的类型
            // 因为后端API可能返回的是旧数据，列表中的类型才是用户看到的
            if (row.warningType && row.warningType !== detailData.warningType) {
                console.warn('[WARNING-LIST] ⚠️ 预警类型不一致！列表中:', row.warningType, '后端返回:', detailData.warningType);
                console.warn('[WARNING-LIST] 使用列表中的预警类型:', row.warningType);
                detailData.warningType = row.warningType;
            }
            
            // 补充预警类型描述
            const warningTypeMap = {
                2: '数量盘单预警',
                3: '运输距离预警',
                4: '设备停留预警',
                5: '高温预警',
                6: '低温预警',
                7: '位置偏离预警',
                8: '延误预警',
                9: '超前到达预警'
            };
            detailData.warningTypeDesc = warningTypeMap[detailData.warningType] || detailData.warningReason || '未知预警';
            

            // 打开详情对话框
            detailDialogRef.value.open(detailData);
        } else {
            ElMessage.error(res.msg || '获取预警详情失败');
        }
    } catch (error) {
        console.error('[WARNING-LIST] 获取预警详情失败:', error);
        ElMessage.error('获取预警详情失败，请稍后重试');
    }
};

onMounted(() => {
    getList();
});
</script>
<style scoped lang="less">
.wrapper {
    .search-wrap {
        display: flex;
        justify-content: space-between;
        background-color: #fff;
        align-items: flex-end;
        padding: 12px 16px 0 16px;
    }

    .btn-group {
        background-color: #fff;
        margin: 10px 0;
        padding: 10px;
    }
}
</style>
