<template>
    <div class="alarms">
        <el-container class="mainContainer">
            <el-header class="mainHeader">
                <el-space class="mainHeaderCenter">
                    <div style="width: fit-content; min-width: 60px">{{ t('alarm.alarmTime') }}</div>
                    <el-date-picker
                        style="height: 40px"
                        v-model="timeRange"
                        type="datetimerange"
                        format="YYYY-MM-DD HH:mm:ss"
                        range-separator="-"
                        :start-placeholder="t('alarm.selectDate')"
                        :end-placeholder="t('alarm.selectDate')"
                        :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]"
                        :shortcuts="shortcuts"
                    />
                    <div style="width: 20px"></div>
                    <div style="width: fit-content; min-width: 60px">{{ t('airBlower.airBlowerNumber') }}</div>
                    <el-select v-model="airBlowerNumberValue" :placeholder="t('alarm.select') + t('airBlower.airBlowerNumber')" class="alarmSelect">
                        <el-option v-for="v in airBlowerList" :key="v.value" :label="v.label" :value="v.value"></el-option>
                    </el-select>
                    <div style="width: 20px"></div>
                    <div style="width: fit-content; min-width: 30px">{{ t('alarm.type') }}</div>
                    <el-select v-model="alarmTypeValue" :placeholder="t('alarm.select') + t('alarm.type')" class="alarmSelect">
                        <el-option v-for="v in alarmTypes" :key="v.value" :label="v.label" :value="v.value"></el-option>
                    </el-select>
                    <div style="width: 20px"></div>
                    <el-button :icon="Search" type="primary" @click="getalarmsList">查询</el-button>
                </el-space>
            </el-header>
            <el-main class="mainMain">
                <div class="tabsPart">
                    <el-table :data="alarmsTableData" class="tablePart" highlight-current-row>
                        <el-table-column prop="eventTimeFormate" :label="AlarmsFieldsEnums['alarmTime']" align="center"> </el-table-column>
                        <el-table-column prop="deviceCode" :label="AlarmsFieldsEnums['airBlowerNumber']" align="center"> </el-table-column>
                        <el-table-column prop="eventText" :label="AlarmsFieldsEnums['faultDescription']" align="center"> </el-table-column>
                        <el-table-column prop="eventType" :label="AlarmsFieldsEnums['alarmType']" align="center">
                            <template #default="scope">
                                <div class="fault" v-if="scope.row.eventType">故障</div>
                                <div class="alarm" v-else>告警</div>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="200" align="center">
                            <template #default="scope">
                                <div class="tableOperate comfirmed" v-if="scope.row.confirmed">已确认</div>
                                <div class="tableOperate" v-else>
                                    <a @click="open(scope.row)">确认</a>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="mainFooter">
                    <el-pagination
                        v-model:current-page="paginationOptions.current"
                        v-model:page-size="paginationOptions.pageSize"
                        :total="paginationOptions.total"
                        :page-sizes="paginationOptions.pageSizes"
                        background
                        :pager-count="7"
                        layout="prev, pager, next, jumper,sizes,total"
                        @change="getcurrentPage"
                    ></el-pagination>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { AlarmsFieldsEnums, AlarmsTableType, GetAlarmsTableParam } from './type'
import { getAlarmListReq, eventComfirm } from '/@/api/backend/alarms/request'
import { equipList } from '/@/api/backend/realData/request'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
import { useAdminInfo } from '/@/stores/adminInfo'
const adminInfo = useAdminInfo()

// 告警时间

const timeRange = ref([new Date().setHours(0, 0, 0, 0), new Date()])
const shortcuts = [
    {
        text: '今天',
        value: () => {
            const start = getFormattedDate(0) + ' 00:00:00'
            const end = new Date()
            return [start, end]
        },
    },
    {
        text: '昨天',
        value: () => {
            const start = getFormattedDate(-1) + ' 00:00:00'
            const end = getFormattedDate(-1) + ' 23:59:59'
            return [start, end]
        },
    },
    {
        text: '前3天',
        value: () => {
            const start = getFormattedDate(-3) + ' 00:00:00'
            const end = getFormattedDate(-1) + ' 23:59:59'
            return [start, end]
        },
    },
    {
        text: '本周',
        value: () => {
            return getDateRange('week')
        },
    },
    {
        text: '本月',
        value: () => {
            return getDateRange('month')
        },
    },
]
const getFormattedDate = (offset: number) => {
    const date = new Date()
    date.setDate(date.getDate() + offset)

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 风机编号
const airBlowerNumberValue = ref('')
const airBlowerList = ref([{ label: '', value: '' }])
// 类别
const alarmTypeValue = ref('')
const alarmTypes = ref([
    { label: '告警', value: 0 },
    { label: '故障', value: 1 },
])

const searchalarms = (): GetAlarmsTableParam => {
    const start = timeRange.value[0]
    const end = timeRange.value[1]
    const deviceCode: any = []
    if (airBlowerNumberValue.value.length) {
        deviceCode.push(airBlowerNumberValue.value)
    } else {
        airBlowerList.value.forEach((item: any) => {
            deviceCode.push(item.value)
        })
    }
    return {
        startTime: new Date(start).getTime() || new Date().setHours(0, 0, 0, 0).valueOf(),
        endTime: new Date(end).getTime() || new Date().valueOf(),
        eventLevel: alarmTypeValue.value || null,
        deviceCode: deviceCode,
        pageNum: paginationOptions.current,
        pageSize: paginationOptions.pageSize,
    }
}

const alarmsTableData = ref<AlarmsTableType[]>([])

// 告警列表
const paginationOptions = reactive({
    current: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [20, 50, 100],
})
const getcurrentPage = () => {
    getalarmsList()
}

const getalarmsList = () => {
    const transparams = searchalarms()
    getAlarmListReq(transparams)
        .then((res: any) => {
            if (res.code == 200) {
                paginationOptions.total = res.total
                alarmsTableData.value = res.rows.map((item: any) => {
                    return {
                        ...item,
                        eventTimeFormate: timestampToTime(item.eventTime),
                    }
                })
            } else {
                ElMessage.error(res.msg ?? '查询失败')
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}
const timestampToTime = (timestamp: any) => {
    timestamp = timestamp ? timestamp : null
    let date = new Date(timestamp)
    let Y = date.getFullYear() + '-'
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
    let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
    let m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    return Y + M + D + h + m
}

const open = (val: any) => {
    ElMessageBox.confirm('是否确认?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            okSubmit(val)
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消确认',
            })
        })
}

const okSubmit = (val: any) => {
    const reqData: any = [
        {
            eventTime: val.eventTime,
            eventId: val.eventId,
            confirmed: 1,
            deviceId: val.deviceId,
        },
    ]

    eventComfirm(reqData)
        .then((res: any) => {
            if (res.code == 200) {
                ElMessage.success(res.msg ?? '确认成功')
                getalarmsList()
            } else {
                ElMessage.error(res.msg ?? '查询失败')
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '查询失败')
        })
}
const getDateRange = (type: 'week' | 'month') => {
    const today = new Date()
    if (type === 'week') {
        const dayOfWeek = today.getDay()
        const startOfWeek = new Date(today)
        startOfWeek.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
        startOfWeek.setHours(0, 0, 0, 0)
        const endOfWeek = new Date(startOfWeek)
        endOfWeek.setDate(startOfWeek.getDate() + 6)
        endOfWeek.setHours(23, 59, 59, 999)
        return [startOfWeek, endOfWeek]
    }
    if (type === 'month') {
        const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1)
        startOfMonth.setHours(0, 0, 0, 0)
        const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0)
        endOfMonth.setHours(23, 59, 59, 999)
        return [startOfMonth, endOfMonth]
    }
}

onMounted(() => {
    equipList({
        // orgId: adminInfo.orgid,
        objectType: 10002,
    }).then((res) => {
        if (res.code == 200) {
            airBlowerList.value = res.data.map((item: any) => {
                return {
                    label: item.name,
                    value: item.code,
                }
            })
            getalarmsList()
        }
    })
})
</script>

<style lang="scss" scoped>
$headerHeight: 60px;
$defaultBackgroundColor: #fff;
$defaultAsideWidth: 260px;
$paginationHeight: 32px;
.alarms {
    position: relative;
    width: 100%;
    height: 100%;
    .mainContainer {
        width: 100%;
        height: 100%;
        .mainHeader {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: $headerHeight;
            padding: 0 20px;
            border-bottom: 1px solid #eaebed;
            .alarmsInput {
                height: 40px;
                width: 220px;
            }
            .mainHeaderCenter {
                width: 100%;
                display: flex;
                // overflow-x: auto;
                // justify-content: flex-start;
                align-items: center;
                // width: 320px;
                .alarmSelect {
                    width: 200px;
                    :deep(.el-select__wrapper) {
                        height: 40px;
                    }
                }
            }
        }
        .mainMain {
            height: calc(100% - $headerHeight);
            .tabsPart {
                height: calc(100% - $paginationHeight);
                padding-bottom: 5px;
                :deep(.el-tabs__content) {
                    height: calc(100% - 55px);
                    .el-tab-pane {
                        height: 100%;
                    }
                }
                .tablePart {
                    height: 100%;
                    .alarm {
                        border: 1px solid rgb(228, 161, 18);
                        width: fit-content;
                        margin: 0 auto;
                        padding: 5px;
                        border-radius: 6px;
                        color: rgb(228, 161, 18);
                    }
                    .fault {
                        border: 1px solid #a03b1d;
                        width: fit-content;
                        margin: 0 auto;
                        padding: 5px;
                        border-radius: 6px;
                        color: #a03b1d;
                    }
                }
                .tableOperate {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    a {
                        margin: 5px;
                        color: #0064aa;
                        font-weight: 600;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                    &.comfirmed {
                        font-weight: 600;
                        color: rgb(5, 174, 163);
                    }
                }
            }
            .mainFooter {
                display: flex;
                justify-content: right;
                background-color: #fff;
            }
        }
    }
    .modelOperate {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        align-items: center;
        width: 80px;
        height: 150px;
        .el-button {
            margin: 0;
        }
    }
}

// 状态
.status-container {
    display: flex;
    justify-content: center;
    align-items: center;
}
.status-dot-online,
.status-dot-offline {
    width: 10px;
    height: 10px;
    border-radius: 50%;
}

.status-dot-online {
    background-color: #06b429;
}

.status-dot-offline {
    background-color: red;
}
.highlight {
    background-color: yellow; /* 高亮背景颜色 */
    color: red; /* 字体颜色 */
    font-weight: bold; /* 加粗字体 */
}
</style>
