<template>
    <div class="table-page">
        <div class="table-page-content">
            <div class="right-table">
                <div class="full-page">
                    <div class="main-table-container">
                        <div
                            :class="[
                                'search-wrapper',
                                { hide: !isShowSearch },
                                { show: isShowSearchAll }
                            ]"
                        >
                            <CustomSearch
                                :firstLineColumnCount="4"
                                :fixedOptionList="fixedOptionList"
                                @clearQuery="handleClearQuery"
                                @reset="handleReset"
                                @search="handleSearch"
                                :showShowAll="false"
                                :showCustomSearch="false"
                            />
                        </div>
                        <div class="table-container">
                            <div ref="tableRef" class="table-content">
                                <div ref="btnGroupPanel" class="btn-box">
                                    <div class="left-btn-group">
                                        <el-button
                                            icon="Checked"
                                            type="success"
                                            @click="handleRead()"
                                            :disabled="!currentDataDel.length"
                                            >标记为已读
                                        </el-button>
                                        <el-button
                                            icon="Delete"
                                            type="danger"
                                            @click="handleDelete()"
                                            :disabled="!currentDataDel.length"
                                            >删除
                                        </el-button>
                                    </div>
                                    <div class="right-btn-group">
                                        <div
                                            :class="{ active: isShowSearch }"
                                            :title="isShowSearch ? '折叠搜索' : '展开搜索'"
                                            class="btn-group-item"
                                            @click="toggleSearch"
                                        >
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </div>
                                        <div
                                            class="btn-group-item"
                                            title="刷新列表"
                                            @click="refresh"
                                        >
                                            <el-icon>
                                                <Refresh />
                                            </el-icon>
                                        </div>
                                        <div
                                            ref="tableHeaderSettingBtn"
                                            class="btn-group-item"
                                            title="设置表头"
                                            @click="toggleSetting"
                                        >
                                            <el-icon>
                                                <Grid />
                                            </el-icon>
                                        </div>
                                        <div
                                            v-show="isShowSetting"
                                            ref="tableHeaderSettingRef"
                                            class="table-header-setting"
                                            tabindex="0"
                                            @focusout="handleSettingFocusOut"
                                        >
                                            <el-scrollbar>
                                                <el-checkbox
                                                    v-model="checkAll"
                                                    :indeterminate="isIndeterminate"
                                                    @change="handleCheckAllChange"
                                                    >全选
                                                </el-checkbox>
                                                <el-checkbox-group
                                                    v-model="currentColumnsKeys"
                                                    @change="handleCheckedChange"
                                                >
                                                    <el-checkbox
                                                        v-for="opt in columnsList"
                                                        :key="opt.prop"
                                                        :title="opt.title"
                                                        :value="opt.prop"
                                                        >{{ opt.title }}
                                                    </el-checkbox>
                                                </el-checkbox-group>
                                            </el-scrollbar>
                                        </div>
                                    </div>
                                </div>
                                <el-table
                                    border
                                    stripe
                                    height="100%"
                                    row-key="id"
                                    :data="tableData"
                                    class="table-list"
                                    id="fixRowIndexTable"
                                    ref="multipleSelection"
                                    v-loading="tableLoading"
                                    @selection-change="handleSelectionChange"
                                    element-loading-background="rgba(10 ,38 ,61, 0.9)"
                                >
                                    <el-table-column align="center" type="selection" width="55" />
                                    <el-table-column
                                        :index="
                                            (index) =>
                                                index +
                                                1 +
                                                (params.pageBean.page - 1) *
                                                    params.pageBean.pageSize
                                        "
                                        align="center"
                                        label="序号"
                                        type="index"
                                        width="80"
                                    />
                                    <template v-if="currentColumns.length">
                                        <el-table-column
                                            v-for="col in currentColumns"
                                            :key="col.prop"
                                            :formatter="
                                                col.formatter
                                                    ? col.formatter
                                                    : col.formatter === false
                                                      ? null
                                                      : (row) => row[col.prop] || '-'
                                            "
                                            :label="col.title"
                                            :min-width="col.minWidth"
                                            :prop="col.prop"
                                            :show-overflow-tooltip="
                                                col.showOverflowTooltip
                                                    ? col.showOverflowTooltip
                                                    : true
                                            "
                                            :sortable="col.sortable"
                                            align="center"
                                        >
                                            <template
                                                v-if="col.prop === 'subject'"
                                                v-slot="{ row }"
                                            >
                                                <div class="name-style">{{ row.subject }}</div>
                                            </template>
                                            <template v-if="col.prop === 'read'" v-slot="{ row }">
                                                <div class="flex-center">
                                                    <span
                                                        :class="{
                                                            read: row.read,
                                                            unread: !row.read
                                                        }"
                                                        >{{ row.read ? '已读' : '未读' }}</span
                                                    >
                                                </div>
                                            </template>
                                        </el-table-column>
                                    </template>
                                    <el-table-column
                                        show-overflow-tooltip
                                        min-width="120"
                                        align="center"
                                        label="操作"
                                    >
                                        <template v-slot="{ row }">
                                            <div class="operation-buttons">
                                                <el-link
                                                    v-if="type && type === '1'"
                                                    type="success"
                                                    underline="never"
                                                    @click="handleRead(row)"
                                                >
                                                    标为已读
                                                </el-link>
                                                <el-link
                                                    type="primary"
                                                    underline="never"
                                                    @click="handleDetail(row)"
                                                >
                                                    详情
                                                </el-link>
                                                <el-link
                                                    type="danger"
                                                    underline="never"
                                                    @click="handleDelete(row)"
                                                >
                                                    删除
                                                </el-link>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <pagination
                                    ref="paginationPanel"
                                    :pageResult="params.pageBean"
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <MessageDetail v-model:is-show="showDetail" :messageId="messageId" @read="handleReadOver" />
    </div>
</template>

<script lang="ts" setup name="Message">
import { computed, onMounted, ref } from 'vue'
import { messageReceiver, removeMessage, markMessage } from '@/api/system/message'
import { ElMessage } from 'element-plus'
import { refineRequestBody } from '@/utils/requestWrappers'
import CustomSearch from '@/components/CustomSearch/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { ElMessageBox } from 'element-plus'
import messageDetail from '@/components/Message/MessageDetail.vue'
// 响应式数据
const showDetail = ref(false)
const messageId = ref('')
const tableData = ref<any[]>([])
const tableLoading = ref(false)
const type = ref('') // 消息类型

const currentColumnsKeys = ref(['subject', 'read', 'owner', 'createTime', 'receiveTime'])

const currentColumns = computed(() => {
    return columnsList.filter((col) => currentColumnsKeys.value.includes(col.prop))
})

onMounted(() => {
    loadData()
})

/**
 * table列表
 */

import { useTableOptionConfig } from './hooks/useTableOptionConfig'
const { fixedOptionList, columnsList } = useTableOptionConfig()

const params = ref({
    pageBean: { page: 1, pageSize: 20, total: 0 },
    querys: [
        {
            operation: 'EQUAL',
            property: 'receiveTime',
            relation: 'AND',
            group: 'filterTime',
            value: '1'
        },
        { operation: 'LIKE', property: 'subject', relation: 'OR', group: 'quick' }
    ],
    sorter: [{ property: 'createTime', direction: 'DESC' }]
})

const handleReadOver = () => {
    if (type.value === '1') {
        loadData()
    }
}

// 加载数据
async function loadData() {
    try {
        tableLoading.value = true
        tableData.value = []
        const query = refineRequestBody(params.value)
        const { rows = [], total = 0 } = (await messageReceiver(query)) as any
        type.value = query.querys
            ? query.querys.find((item: any) => item.property === 'receiveTime')?.value
            : undefined
        tableData.value = rows.map((item: any) => ({
            ...item,
            read: type.value === '1' ? false : true
        }))
        params.value.pageBean.total = total
    } catch (error) {
        ElMessage.error('数据加载失败')
    } finally {
        tableLoading.value = false
    }
}

/**
 * 查询相关
 */
import { useSearch } from '@/hooks/useSearch'
const {
    tableHeaderSettingRef,
    isShowSearch,
    isShowSearchAll,
    isShowSetting,
    toggleSearch,
    isIndeterminate,
    checkAll,
    toggleSetting,
    handleSettingFocusOut,
    handleSelectionChange,
    refresh,
    handleClearQuery,
    handleReset,
    handleSearch,
    handleCheckedChange,
    handleCheckAllChange,
    currentDataDel
} = useSearch({
    params: params.value,
    loadData,
    columnsList,
    currentColumnsKeys
})

/**
 * 分页相关
 */
import { usePagination } from '@/hooks/usePagination'
const { handleSizeChange, handleCurrentChange } = usePagination({
    params: params.value,
    loadData
})

function handleDelete(row?: { id: String }) {
    let ids = row ? row.id : currentDataDel.value.join()
    if (ids === undefined || ids === null || ids === '') {
        {
            ElMessage.error('请选择要删除的消息')
            return
        }
    }
    ElMessageBox.confirm('确定删除选中的消息吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const { state } = (await removeMessage(ids)) as any
            if (state) {
                ElMessage.success(`消息删除成功`)
                const { page, pageSize, total } = params.value.pageBean
                const totalPages = Math.ceil(total / pageSize) // 计算总页数
                if (totalPages > 1 && page === totalPages) {
                    if (tableData.value.length === 1) {
                        // 当前页只有一条数据
                        params.value.pageBean.page -= 1 // 返回前一页
                    }
                }
                await loadData()
            }
        } catch (error) {
            ElMessage.error(error || '删除失败')
        }
    })
}

const handleRead = (row?: { id: String }) => {
    let ids = row ? row.id : currentDataDel.value.join()
    if (ids === undefined || ids === null || ids === '') {
        {
            ElMessage.error('请选择要标记为已读的消息')
            return
        }
    }
    ElMessageBox.confirm('确定标记选中的消息为已读状态吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const { state } = (await markMessage(ids)) as any
            if (state) {
                ElMessage.success(`消息标记为已读成功`)
                const { page, pageSize, total } = params.value.pageBean
                const totalPages = Math.ceil(total / pageSize) // 计算总页数
                if (totalPages > 1 && page === totalPages) {
                    if (tableData.value.length === 1) {
                        // 当前页只有一条数据
                        params.value.pageBean.page -= 1 // 返回前一页
                    }
                }
                await loadData()
            }
        } catch (error) {
            ElMessage.error(error || '标记失败')
        }
    })
}

const handleDetail = (row: any) => {
    showDetail.value = true
    messageId.value = row.id
}
</script>

<style lang="scss" scoped>
.read {
    color: #67c23a;
    background: #4e8e2f20;
    display: inline-block;
    padding: 2px 10px;
}
.unread {
    color: #ffaa00;
    background: rgba(255, 136, 51, 0.2);
    display: inline-block;
    padding: 2px 10px;
}
</style>
