<template>
    <div class="hc-tasks-message">
        <div class="menu">
            <hc-card scrollbar>
                <hc-menu-simple :datas="menuOptions" :keys="menuKey" @change="handleMenuValue" />
            </hc-card>
        </div>
        <div class="content">
            <hc-card>
                <template #header>
                    <div class="w-32">
                        <el-select v-model="searchForm.taskType" clearable block placeholder="任务类型">
                            <el-option v-for="item in tasksType" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
                        </el-select>
                    </div>
                    <div class="ml-2 w-32">
                        <el-select v-model="searchForm.messageType" clearable block placeholder="消息类型">
                            <el-option label="未读" :value="1" />
                            <el-option label="已读" :value="2" />
                        </el-select>
                    </div>
                    <div class="ml-2 w-64">
                        <hc-date-picker :dates="betweenTime" clearable @change="betweenTimeUpdate" />
                    </div>
                    <div class="ml-2 w-64">
                        <hc-search-input v-model="searchForm.searchValue" @search="searchClick" />
                    </div>
                </template>
                <template #extra>
                    <el-button hc-btn type="danger" @click="delClick">
                        <hc-icon name="delete-bin-3" />
                        <span>删除</span>
                    </el-button>
                    <el-button hc-btn type="primary" @click="batchReadClick">
                        <hc-icon name="check" />
                        <span>标记已读</span>
                    </el-button>
                </template>
                <hc-table
                    ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
                    :index-style="{ width: 60 }" is-check :check-style="{ width: 29 }"
                    @selection-change="tableSelection"
                >
                    <template #messageStatusName="{ row }">
                        <span v-if="row.messageStatusName === '未读'" class="text-red-5">未读</span>
                        <span v-else-if="row.messageStatusName === '已读'" class="text-green-5">已读</span>
                        <span v-else>未知</span>
                    </template>
                    <template #action="{ row }">
                        <el-link v-if="row.messageStatusName === '未读'" type="primary" @click="rowReadClick(row)">确认</el-link>
                        <el-link v-else type="info" disabled>已确认</el-link>
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" :sizes="[20, 50, 100, 150, 200, 300]" @change="pageChange" />
                </template>
            </hc-card>
        </div>
    </div>
</template>

<script setup>
import { HcDelMsg } from 'hc-vue3-ui'
import { onActivated, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { arrToId, getArrValue } from 'js-fast-way'
import taskApi from '~api/tasks/hc-data'
import mainApi from '~api/tasks/message'

const props = defineProps({
    msgCount: {
        type: [Number, String],
        default: 0,
    },
})

//渲染完成
onActivated(() => {
    queryTaskType()
    searchClick()
})

//获取项目合同段ID
const store = useAppStore()
const projectId = ref(store.getProjectId)
const contractId = ref(store.getContractId)

//监听菜单数据
const taskCount = ref(props.msgCount)
watch(() => props.msgCount, (val) => {
    taskCount.value = val ?? 0
    menuOptions.value[0].badge = taskCount.value
}, { deep: true })

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

//左侧菜单
const menuKey = ref('3')
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: taskCount.value },
    //{ key: '4', label: '工单反馈', icon: 'question-answer', badge: 0 },
    //{ key: '5', label: '系统消息', icon: 'chat-settings', badge: 0 },
])
const handleMenuValue = (item) => {
    searchForm.value.type = item.key
    menuKey.value = item.key
    searchClick()
}

//获取任务类型
const tasksType = ref([])
const queryTaskType = async () => {
    const { data } = await taskApi.queryTaskType()
    tasksType.value = getArrValue(data)
}

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

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

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

//表格
const tableRef = ref(null)
const tableColumn = [
    { key: 'meterTaskTypeName', name: '任务类型' },
    { key: 'taskName', name: '任务名称' },
    { key: 'startDate', name: '开始时间' },
    { key: 'repealDate', name: '废除时间' },
    { key: 'taskFlowName', name: '任务流程' },
    { key: 'rejectPersonName', name: '驳回人' },
    { key: 'rejectReason', name: '驳回原因' },
    { key: 'messageStatusName', name: '消息状态', width: 80, align: 'center' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
]
const tableData = ref([])

//获取消息数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    //清空数据
    tableData.value = []
    tableRef.value?.clearSelection()
    tableCheckedKeys.value = []
    //发起请求
    const { data } = await mainApi.repealPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    tableLoading.value = false
    tableData.value = getArrValue(data?.records)
    searchForm.value.total = data.total || 0
}

//多选
const tableCheckedKeys = ref([])
const tableSelection = (rows) => {
    tableCheckedKeys.value = rows
}

//单个查看
const rowReadClick = ({ id }) => {
    batchReadApi(id)
}

//批量查看
const batchReadClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要已读的数据')
        return
    }
    const ids = arrToId(rows, 'id')
    batchReadApi(ids)
}

//统一查看
const batchReadApi = async (id) => {
    const { isRes } = await mainApi.batchRead(id)
    if (!isRes) return
    window.$message.success('操作成功')
    getTableData().then()
}

//批量删除
const delClick = () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选要删除的已读消息')
        return
    }
    //判断是否满足条件
    const result = rows.every(({ messageStatusName }) => {
        console.log(messageStatusName)
        return messageStatusName === '已读'
    })
    if (!result) {
        window.$message.warning('只能删除已读的消息')
        return
    }
    HcDelMsg(async (resolve) => {
        const ids = arrToId(rows, 'id')
        const { isRes } = await mainApi.batchDelete(ids)
        if (!isRes) return
        window.$message.success('删除成功')
        getTableData().then()
        resolve() //关闭弹窗的回调
    })
}
</script>

<style lang="scss" scoped>
.hc-tasks-message {
    position: relative;
    display: flex;
    height: 100%;
    .menu {
        position: relative;
        margin-right: 20px;
        width: 220px;
        height: 100%;

    }
    .menu :deep(.el-card__body) {
        padding: 0;
    }
    .menu :deep(.hc-menu-simple-box) {
        padding: 10px;
    }
    .content {
        position: relative;
        height: 100%;
        flex: 1;
    }
}
</style>
