<template>
    <div class="hc-layout-box">
        <div class="hc-layout-left-box">
            <el-scrollbar>
                <HcMenuSimple :datas="menuOptions" :keys="menuKey" @change="handleMenuValue" />
            </el-scrollbar>
        </div>
        <div class="hc-layout-content-box">
            <HcCard action-size="lg">
                <template #header>
                    <div class="w-32 ml-2">
                        <el-select v-model="searchForm.smsType" clearable placeholder="消息类型" size="large">
                            <el-option v-for="item in smsTypeData" :label="item.label" :value="item.value" />
                        </el-select>
                    </div>
                    <div class="w-64 ml-2">
                        <HcDatePicker :dates="betweenTime" clearable size="large" @change="betweenTimeUpdate" />
                    </div>
                    <div class="ml-2">
                        <el-button size="large" type="primary" @click="searchClick">
                            <HcIcon name="search-2" />
                            <span>搜索</span>
                        </el-button>
                    </div>
                </template>
                <template #extra>
                    <el-button :disabled="tableCheckedKeys.length <= 0" :loading="delLoading" hc-btn @click="delClick">
                        <HcIcon name="delete-bin-3" />
                        <span>删除消息</span>
                    </el-button>
                    <el-button
                        :disabled="tableCheckedKeys.length <= 0" :loading="markReadLoading" hc-btn
                        @click="markReadClick"
                    >
                        <HcIcon name="bookmark" />
                        <span>标记已读</span>
                    </el-button>
                </template>
                <HcTable
                    ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading"
                    is-check @selection-change="tableSelectionChange"
                >
                    <template #content="{ row }">
                        <div class="text-link text-cut" @click="tableContent(row)">{{ row.content }}</div>
                    </template>
                </HcTable>
                <template #action>
                    <HcPages :pages="searchForm" @change="pageChange" />
                </template>
            </HcCard>
        </div>
        <!-- 日志内容 -->
        <el-dialog v-model="operationContentModal" class="hc-modal-border" title="消息内容" width="38rem">
            {{ operationContent }}
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute, useRouter } from 'vue-router'
import messageApi from '~api/tasks/message'
import { arrToId, getArrValue } from 'js-fast-way'
import website from '~src/config/index'
import { delMessageV2 } from '~com/message/index.js'

//消息数量
const props = defineProps(
    {
        msgCount: {
            type: Object,
            default: () => ({
                allCount: 0,
                taskCount: 0,
                messageCount: 0,
                messageCount_1: 0,
                messageCount_2: 0,
                messageCount_3: 0,
                messageCount_4: 0,
                messageCount_5: 0,
            }),
        },
    },
)
//变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()
const projectId = ref(useAppState.getProjectId)
const contractId = ref(useAppState.getContractId)
const userInfo = ref(useAppState.getUserInfo)

//路由参数数据
const routerQuery = useRoutes?.query
let MenuType = routerQuery?.MenuType || '1'
const menumsgCount = ref(props.msgCount)
//监听
//监听
watch(() => [
        props.msgCount,
    ], ([val]) => {
        menumsgCount.value = val
        if (val) {
            queryCurrentUserMessageCount()
        }

    },
)
//渲染完成
onMounted(() => {
    searchForm.value.type = MenuType
    searchForm.value.current = 1
    searchClick()
})

//左侧菜单
const menuKey = ref(MenuType)
const menuOptions = ref([
    { key: '1', label: '任务催办', icon: 'alarm-warning', badge: 0 },
    { key: '2', label: '监测预警', icon: 'eye', badge: 0 },
    { key: '3', label: '废除通知', icon: 'delete-bin-3', badge: 0 },
    { key: '4', label: '工单反馈', icon: 'question-answer', badge: 0 },
    { key: '5', label: '系统消息', icon: 'chat-settings', badge: 0 },
])

const handleMenuValue = (item) => {
    searchForm.value.type = item.key
    searchForm.value.current = 1
    menuKey.value = item.key
    searchClick()
    router.push({
        path: useRoutes.path,
        query: { MenuType: item.key },
    })
}

//获取消息数量
const queryCurrentUserMessageCount = async () => {
    const typeArr = ['messageCount_1', 'messageCount_2', 'messageCount_3', 'messageCount_4', 'messageCount_5']
    for (let i = 0; i < typeArr.length; i++) {
        menuOptions.value[i].badge = menumsgCount.value[typeArr[i]] ?? 0
    }
}
//消息类型
const smsTypeData = ref([{ label: '已读消息', value: '1' }, { label: '未读消息', value: '2' }])

//搜索和分页数据
const searchForm = ref({
    isRead: null, startTime: null, endTime: null, type: 1,
    current: 1, size: 20, total: 0,
})

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ val, arr }) => {
    betweenTime.value = arr
    if (val && val.length > 0) {
        searchForm.value.startTime = val['start']
        searchForm.value.endTime = val['end']
    } else {
        searchForm.value.startTime = null
        searchForm.value.endTime = null
    }
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//设置表头数据
const tableListRef = ref(null)
const tableListColumn = ref([
    { key: 'typeValue', name: '类型', width: '120' },
    { key: 'time', name: '日期时间', width: '180' },
    { key: 'content', name: '内容' },
])
const tableListData = ref([])

//获取数据
const tableLoading = ref(false)
const getTableData = async () => {
    //处理初始数据
    tableLoading.value = true
    tableListData.value = []
    tableListRef.value?.clearSelection()
    tableCheckedKeys.value = []
    //获取数据
    const { error, code, data } = await messageApi.getPageData({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    //处理返回数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableListData.value = getArrValue(data['records'])
        searchForm.value.total = data['total'] ?? 0
    } else {
        tableListData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//查看内容
const operationContentModal = ref(false)
const operationContent = ref('')
const tableContent = (row) => {
    operationContent.value = row['content'] ?? ''
    operationContentModal.value = true
    setMessageWarningReadApi(row['id'], false)
}

//删除消息
const delClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeData(rows)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
        })
    } else {
        window.$message?.warning('请先勾选要删除的消息')
    }
}

//确认删除消息
const delLoading = ref(false)
const removeData = async (rows) => {
    delLoading.value = true
    const ids = arrToId(rows)
    //请求数据
    const { error, code } = await messageApi.removeData({
        ids: ids,
    }, false)
    //处理返回数据
    delLoading.value = false
    if (!error && code === 200) {
        tableCheckedKeys.value = []
        window.$message?.success('消息删除成功')
        queryCurrentUserMessageCount()
        searchClick()
    } else {
        window.$message?.error('消息删除失败')
    }
}

//标记已读
const markReadClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length > 0) {
        const ids = arrToId(rows)
        window?.$messageBox?.alert('勾选的消息是否标记为已读？', '确认操作', {
            showCancelButton: true,
            confirmButtonText: '确定标记',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    setMessageWarningReadApi(ids)
                }
            },
        })
    } else {
        window.$message?.warning('请先勾选要标记的消息')
    }
}

//确认标记
const markReadLoading = ref(false)
const setMessageWarningReadApi = async (ids, getTable = true) => {
    markReadLoading.value = true
    //请求数据
    const { error, code } = await messageApi.setMessageWarningRead({
        ids: ids,
    }, false)
    //处理返回数据
    markReadLoading.value = false
    if (!error && code === 200) {
        if (getTable) {
            tableCheckedKeys.value = []
            window.$message?.success('消息标记为已读成功')
            queryCurrentUserMessageCount()
            getTableData()
        } else {
            queryCurrentUserMessageCount()
        }
    } else {
        window.$message?.error('消息标记为已读失败')
    }
}
</script>

<style lang="scss" scoped>
@import "../../styles/tasks/message.scss";
</style>
