<template>
    <div class="control-view">
        <!-- 主要内容 -->
        <div class="main-content">
            <!-- 顶部状态栏 -->
            <div class="header-status">
                <div class="time-info">
                    <span>{{ currentTime }} {{ week }}</span>
                </div>
                <div class="page-title">
                    <h1>报警预览</h1>
                </div>
                <div class="system-status">
                    <!-- <span>系统已运行：{{ systemRuntime }}</span> -->
                </div>
            </div>

            <!-- 主体区域 -->
            <div class="control-content">
                <div style="width: 100%;">
                    <el-button @click="handleDeal" class="handleBtn" type="success">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        批量处理
                    </el-button>
                    <el-button @click="handleDel" class="delBtn" type="danger">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        批量删除
                    </el-button>
                </div>
                <el-table :data="tableData" style="width: 100%" height="366" stripe v-loading="loading" @selection-change="handleSelectionChange" row-key="id" ref="multipleTableRef">
                    <el-table-column type="selection" :selectable="selectable" width="55" />
                    <el-table-column align="center" prop="id" label="序号" />
                    <el-table-column align="center" prop="loop_idx" label="回路地址" />
                    <el-table-column align="center" prop="fault_msg" label="故障信息" />
                    <el-table-column align="center" prop="fault_code" label="故障码" />
                    <el-table-column align="center" prop="voltage" label="电压">
                        <template #default="{ row }">
                            {{ row.voltage && row.voltage + 'V' }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="fault_time" label="故障时间" min-width="150">
                        <template #default="{ row }">
                            {{ row.fault_time ? dayjs(row.fault_time).format('YYYY-MM-DD HH:mm:ss') : '' }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="voltage" label="处理状态">
                        <template #default="{ row }">
                            {{ row.operate_status == 0 ? '未处理' : '已处理' }}
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination v-if="total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 30, 50, 100]" :total="total" :pager-count="5" v-model:page-size="pageSize" v-model:current-page="currentPage" background layout="prev, pager, next,jumper" />
            </div>
        </div>
        <!-- 底部信息 -->
        <div class="bottom-info">
            <div style="color:#fff">
                设备号：{{ commit_uid }}
            </div>
            <div class="bottom_item">
                <!-- <div class="time-item">
                    <span>日出时间：{{ sunriseTime }}</span>
                </div>
                <div class="time-item">
                    <span>日落时间：{{ sunsetTime }}</span>
                </div> -->
            </div>
            <div class="bottom_item">
                <el-button class="restart-button" @click="reflesh">
                    <el-icon>
                        <RefreshRight />
                    </el-icon>
                    刷新
                </el-button>
                <el-button class="back-button" @click="goBack">
                    <el-icon>
                        <HomeFilled />
                    </el-icon>
                    返回主界面
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import RPC from '@/utils/rpc';
import dayjs from 'dayjs';

const router = useRouter()
const currentTime = ref('')
const systemRuntime = ref('38分钟')
const commit_uid = localStorage.getItem('central_control_comm_uid')

const loading = ref(false)
const total = ref(0)
const pageSize = ref(8)
const currentPage = ref(1)
const handleSizeChange = () => {
    currentPage.value = 1
    getData()
}
const handleCurrentChange = () => {
    getData()
}

const tableData = ref([])

const multipleTableRef = ref(null)
const multipleSelection = ref([])
const selectable = (row) => true
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

const handleDel = () => {
    console.log(multipleSelection.value)
    if (multipleSelection.value.length === 0) {
        return ElMessage.warning('请至少选择一项！')
    }
    ElMessageBox.confirm(
        `此操作将删除报警信息，是否继续?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        RPC.post('/m9z/fault/batchExec', { ids: multipleSelection.value.map(item => item.id), operate: 1 }).then(res => {
            ElMessage.success('处理成功')
            multipleTableRef.value.clearSelection()
            currentPage.value = 1
            getData()
        })
    })
}
const handleDeal = () => {
    console.log(multipleSelection.value)
    if (multipleSelection.value.length === 0) {
        return ElMessage.warning('请至少选择一项！')
    }
    ElMessageBox.confirm(
        `此操作将处理报警信息，是否继续?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        RPC.post('/m9z/fault/batchExec', { ids: multipleSelection.value.map(item => item.id), operate: 0 }).then(res => {
            ElMessage.success('处理成功')
            multipleTableRef.value.clearSelection()
            getData()
        })
    })
}

const getData = () => {
    const params = {
        "limit": pageSize.value,
        "page": currentPage.value,
        "and": {
            "comm_uid": [
                commit_uid
            ]
        },
        "like": {},
        "orderby": [
            {
                "id": "desc",
                "fault_time": "desc"
            }
        ]
    }
    loading.value = true
    tableData.value = []
    RPC.post('/m9z/fault/list', params).then(res => {
        total.value = res.count || 0
        tableData.value = res.rows || []
    }).finally(() => {
        loading.value = false
    })
}
getData()

const reflesh = () => {
    currentPage.value = 1
    getData()
}


const week = ref('')
const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
// 更新时间
const updateTime = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')

    week.value = weekDays[now.getDay()]
    currentTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const restartSystem = () => {
    RPC.post('/m9z/setRestart', { comm_uid: commit_uid }).then(res => {
        ElMessage.success('重启成功')
    })
}




// 返回主界面
const goBack = () => {
    router.push('/')
}

let timeInterval = null

onMounted(() => {
    updateTime()
    timeInterval = setInterval(updateTime, 1000)
})

onUnmounted(() => {
    if (timeInterval) {
        clearInterval(timeInterval)
    }
})
</script>

<style scoped lang="scss">
.control-view {
    width: 100vw;
    height: 100vh;
    box-sizing: border-box;
    position: relative;
    overflow: auto;
    background: center / cover url('@/assets/images/handle_control_bg.png') no-repeat;
}

.main-content {
    position: relative;
    z-index: 2;
    width: 100%;
    height: 100%;
    padding: 10px 20px;
    box-sizing: border-box;
}

.header-status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    color: rgba(255, 255, 255, 0.9);
}

.time-info {
    font-size: 18px;
    font-weight: 300;
    width: 270px;
}

.page-title h1 {
    font-size: 30px;
    font-weight: bold;
    margin: 0;
    color: #ffffff;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.system-status {
    min-width: 200px;
    font-size: 18px;
    font-weight: 300;
    width: 270px;
}

.control-content {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;

    :deep(.el-table__header) {
        .el-table__cell {
            background-color: #0881FE;
            color: #fff;
        }
    }
}


.bottom-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #eee;
    width: 100vw;
    padding: 0 30px;
    height: 50px;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 999;
    box-sizing: border-box;

    .bottom_item {
        display: flex;
        align-items: center;
    }

    .time-item {
        color: rgba(255, 255, 255, 0.7);
        font-size: 16px;
        margin: 0 20px;
    }

    .back-button,
    .restart-button {
        width: 100%;
        height: 38px;
        border-radius: 19px;
        font-size: 16px;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .back-button {
        background-color: #000;
        color: #fff;
        border: #000;
    }
}

.el-input {
    background-color: #21232A;

    :deep(.el-input__wrapper) {
        background-color: #212329;
        box-shadow: none;
        border: 1px soild #3B3D45;

        input {
            color: #8088AA;
        }
    }
}

.delBtn {
    background-color: #f12323;
    border-color: #f12323;
}
</style>
