<script lang="ts" setup>
import { h, onMounted, ref, watch } from 'vue';
import type { DataTableColumns, DataTableRowKey, RowData } from 'naive-ui';
import {
    NButton,
    NCard,
    NDataTable,
    NInput,
    NTag,
    NSpace,
    NSpin,
    useDialog,
    useMessage
} from 'naive-ui';
import { posRules } from '@/rules/rules';
import { delFenceLogApi, getFenceeExportApi, getFencePageApi, putFenceeLogApi } from '@/api';

const message = useMessage();

// 常量和响应式数据
const tableData = ref([]);

const ids = ref<DataTableRowKey[]>([]);
const pageSizes = ref([10, 20, 50, 100]);
const show = ref(false);
const range = ref<any>();
let tagElement;
const pageData = ref({
    pageNum: 1,
    pageSize: 10,
    total: 10
});
const serarchData = ref({
    pageNum: pageData.value.pageNum,
    pageSize: pageData.value.pageSize,
    username: '', //用户姓名//车牌号
    carNumber: '', // 车辆编号
    startTime: null,
    endTime: null
});

// 表格列配置
const tableColumn = [
    {
        type: 'selection' as const,
        width: 50
    },
    {
        title: '排序',
        key: 'id',
        align: 'center',
        width: 80
    },
    {
        title: '用户姓名/车牌号',
        key: 'carName',
        align: 'center',
        minWidth: 200,
        treeConfig: {
            indent: 20,
            expandable: (row: any) => Boolean(row.children) && row.children.length > 0
        },
        render(row: any) {
            return h('span', null, row.carName);
        }
    },
    {
        title: '越界区域',
        key: 'rangeName',
        align: 'center',
        minWidth: 180
    },
    {
        title: '报警时间',
        key: 'createTime',
        align: 'center',
        minWidth: 180
    },
    {
        title: '报警处理状态',
        key: 'status',
        align: 'center',
        minWidth: 180,
        render(row: any) {
            // 根据状态设置不同的颜色样式
            // let textColor = '#333';
            // if (row.status === 1) {
            //     text = '待处理';
            //     textColor = '#ffb900';
            // } else if (row.status === 2) {
            //     text = '正确报警';
            //     textColor = '#2196ed';
            // } else if (row.status === 3) {
            //     text = '错误报警';
            //     textColor = '#f36155';
            // }
            // return h('span', { style: { color: textColor, fontWeight: 'bold' } }, text);
                switch(row.status) {
                case 1:
                    tagElement = h(NButton, { type: "warning", quaternary:true, focusable:false }, ['待处理']);
                    break;
                case 2:
                    tagElement = h(NButton, { type: "info", quaternary:true, focusable:false }, ['正确报警']);
                    break;
                case 3:
                    tagElement = h(NButton, { type: "error", quaternary:true, focusable:false }, ['错误报警']);
                    break;
                default:
                    tagElement = h('span', {}, ['未知状态']);
                }
                
                return h(NSpace, { justify: 'center' }, [tagElement]);
        }
    },
    {
        title: '操作',
        key: 'actions',
        align: 'center',
        minWidth: 120,
        render(row: any) {
            return h(NSpace, { justify: 'center' }, [
                h(
                    NButton,
                    {
                        size: 'small',
                        style: {
                            color: '#eee',
                            backgroundColor: '#2196f3',
                            borderColor: '#2196f3',
                            borderRadius: '5px',
                            padding: '4px 12px'
                        },
                        onClick: () => modifyAlramStatus(row.id, '2')
                    },
                    ['正确报警']
                ),
                h(
                    NButton,
                    {
                        size: 'small',
                        style: {
                            color: '#eee',
                            backgroundColor: '#f16255',
                            borderColor: '#f16255',
                            borderRadius: '5px',
                            padding: '4px 12px',
                            margin: ' '
                        },
                        onClick: () => modifyAlramStatus(row.id, '3')
                    },
                    ['错误报警']
                ),
                h(
                    NButton,
                    {
                        size: 'small',
                        style: {
                            color: '#eee',
                            backgroundColor: '#f16255',
                            borderColor: '#f16255',
                            borderRadius: '5px',
                            padding: '4px 12px'
                        },
                        onClick: () => delAlarmLog(row.id)
                    },
                    [
                        h('img', {
                            src: '/src/assets/delete.png',
                            alt: '删除',
                            style: {
                                width: '10px',
                                height: '10px',
                                marginRight: '5px'
                            }
                        }),
                        '删除'
                    ]
                )
            ]);
        }
    }
];

function handleCheck(rowKeys: DataTableRowKey[]) {
    ids.value = rowKeys;
}

const dialog = useDialog();

// 头部删除
async function topDelete() {
    if (ids.value == null || ids.value.length == 0) {
        message.error('请选择要删除的用户');
    } else {
        let id = ids.value.join(',')
        let res = await delFenceLogApi(id);
        if(res.data.code == 200) {
            search();
            message.success('删除成功')
        } else {
            message.error(res.data.msg)
        }
    }
}
// 头部导出
async function topDerive() {
    if (ids.value == null || ids.value.length == 0) {
        message.error('请选择要导出的报警数据');
    } else {
        const id = ids.value.join(',');
        const res = await getFenceeExportApi(id);
        console.log(res);
        if (res.status == 200) {
            const blob = res.data;
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            document.body.appendChild(a);
            a.href = url;
            a.download = '报警数据.xlsx';
            a.click();
            window.URL.revokeObjectURL(url);
            message.success('导出成功，请到下载目录查看');
        } else {
            message.error(res.msg);
        }
    }
}

function handleSearch() { 
    search();
}

function watchTimeData(value: any) {
    serarchData.value.startTime = value[0];
    serarchData.value.endTime = value[1];
}

function handleReset() {
    serarchData.value = {
        pageNum: pageData.value.pageNum,
        pageSize: pageData.value.pageSize,
        username: '', //用户姓名/车牌号
        carNumber: '', // 车辆编号
        startTime: null,
        endTime: null
    };
    range.value = null;

    search();
}

async function search() {
    const res = await getFencePageApi(serarchData.value);
    tableData.value = res.data.data.records;
    pageData.value.total = Number(res.data.data.total);
}

function handlePage() {
    serarchData.value.pageNum = pageData.value.pageNum;
    search();
}

function handlePageSize() {
    serarchData.value.pageSize = pageData.value.pageSize;
    pageData.value.pageNum = 1;
    serarchData.value.pageNum = 1;
    search();
}

function handleclear() {
    serarchData.value.startTime = null;
    serarchData.value.endTime = null;
}

// 文字顏色变更状态
const modifyAlramStatus = async (id: string | number, status: string) => {
    let data = {
        id:id,
        status:status
    };
    let res = await putFenceeLogApi(data);
    if(res.data.code == 200) {
        message.success('修改成功');
        search();
    } else {
        message.error(res.data.msg)
    }
};

const delAlarmLog = async (id: string | number) => {
    dialog.create({
        title: '提示',
        content: '确定删除这条记录吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            let res = await delFenceLogApi(id);
            if(res.data.code == 200) {
                search();
                message.success('删除成功');
            } else {
                message.error(res.data.msg);
            }
        }
    });
};

onMounted(() => {
    search();
});
</script>

<template>
    <div id="DepartmentPage">
        <div>
            <NSpin :show="show">
                <NCard size="medium">
                    <div
                        style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center">
                        <NSpace>
                            <div>
                                用户姓名
                                <NInput v-model:value="serarchData.username" placeholder="请输入用户姓名"
                                    style="width: 250px; margin-left: 10px" clearable="true" />
                            </div>

                            <div style="margin-left: 30px">
                                车牌号
                                <NInput v-model:value="serarchData.username" placeholder="请输入车牌号"
                                    style="width: 250px; margin-left: 10px" clearable="true" />
                            </div>

                            <div style="display: flex; align-items: center; margin-left: 30px">
                                <div>日期范围</div>
                                <n-date-picker v-model:value="range" type="datetimerange" @update:value="watchTimeData"
                                    clearable @clear="handleclear" style="margin-left: 10px" />
                            </div>

                            <NButton color="#2198f2" style="padding: 0px 17px; border-radius: 5px; margin-left: 30px"
                                @click="handleSearch">
                                查询
                            </NButton>
                            <NButton style="padding: 0px 17px; border-radius: 5px" @click="handleReset">重置</NButton>
                        </NSpace>
                    </div>
                    <NSpace style="margin-bottom: 20px">
                        <NButton color="#ffbb01" style="padding: 0px 20px; border-radius: 5px" @click="topDerive">
                            <img src="@/assets/daochu.png" alt=""
                                style="width: 10px; height: 10px; margin-right: 5px" />
                            导出
                        </NButton>
                        <NButton color="#f36255" style="padding: 0px 20px; border-radius: 5px" @click="topDelete">
                            <img src="@/assets/delete.png" alt=""
                                style="width: 10px; height: 10px; margin-right: 5px" />
                            删除
                        </NButton>
                    </NSpace>

                    <NDataTable :row-key="row => row.id" :columns="tableColumn" :data="tableData" :bordered="true"
                        :pagination="false" tree-column-key="name" :row-class-name="(row: any) => {
                            switch(row.status) {
                                case 1: return 'warning-row';
                                case 2: return 'success-row';
                                case 3: return 'error-row';
                                default: return '';
                            }
                        }" @update:checked-row-keys="handleCheck" />

                    <div style="display: flex; justify-content: end; margin-top: 30px;">
                        <ElPagination v-model:current-page="pageData.pageNum" v-model:page-size="pageData.pageSize"
                            :page-sizes="[10, 20, 30, 40]" background="#2196f3" layout="sizes, prev, pager, next"
                            :total="pageData.total" @size-change="handlePageSize" @current-change="handlePage" />
                    </div>
                </NCard>
            </NSpin>
        </div>
    </div>
</template>

<style scoped>
:deep(.n-pagination .n-pagination-item.n-pagination-item--active) {
    background-color: #2196ed !important;
    color: white !important;
    border-color: #2196ed !important;
}

/* 行文字颜色样式 - 移除背景色，只保留文字颜色 */
:deep(.warning-row td) {
    color: #ffb900 !important;
}

:deep(.success-row td) {
    color: #2196ed !important;
}

:deep(.error-row td) {
    color: #f36155 !important;
}

/* 确保状态列的颜色显示正确 */
:deep(.n-data-table td) {
    color: inherit;
}
</style>
