<template>
    <section ref="mLeftRef" class='bottom-modules modules'>
        <section class="header">
            <section style="display: flex;align-items: center;justify-content: space-between;">
                <MOSTY.Assort :title="'工作日历'" />
                <!-- <article class="posi">
                    <MOSTY.Assort :title="'工作日历'" />
                </article> -->
                <!-- <section class="tabs">
                    <article v-for="(item, index) in listData" :key="index" :class="{ 'active': actives == item.id }"
                        @click="handleTabs(item.id)">
                        <el-badge :value="item.tips" class="item" :hidden="item.tips <= 0">
                            {{ item.title }}
                        </el-badge>
                    </article>
                </section> -->
            </section>
            <el-link @click="seeMore" style="width: 82px;" v-if="actives != '04'">查看全部 ></el-link>
        </section>
        <el-divider style="margin: 0 !important;border-color: #EFEFEF;" />

        <!-- 通知，公告 -->
        <section class="m-content" v-if="messageList.dataList.length && actives !== '03' && actives !== '04'">
            <el-divider style="margin: 0 !important;" />
            <el-scrollbar>
                <section class="m-list" v-for="(item, index) in messageList.dataList" :key="index"
                    @click="handleClickDetail(item)">
                    <section class="m-top">
                        <section class="m-left">
                            <el-tag type="success">{{ { '01': '通知', '02': '公告' }[item.type] }}</el-tag>
                            <h3 class="m-left-title" :style="{ width: `${mLeftWidth}px` }">{{ item.title }}</h3>
                        </section>
                        <section class="time">{{ item.time && item.time.slice(0, 11) }}</section>
                    </section>
                    <el-divider style="margin:12px 0 !important;" />
                    <el-badge v-if="item.status === '2'" class="badde-new-1" value="新" />
                </section>
            </el-scrollbar>
        </section>
        <!-- 日历-->
        <section class="m-content1" v-if="actives == '04'">
            <el-divider style="margin: 0 !important;" />
            <!-- <Calendar /> -->
            <Calendar ref="calendarRef" :markDate="calendarMarkDates" :markDateMore="calendarMarkDatesMore"
                @changeMonth="handleMonthChange" @choseDay="handleDaySelect" />
        </section>
        <!-- 工作待办 -->
        <section class="m-content1" v-if="workData.dataList.length && actives == '03'">
            <el-divider style="margin: 0 !important;" />
            <el-scrollbar>
                <section class="m-list1" v-for="(item, index) in workData.dataList" :key="index">
                    <section class="m-flex1" @click="handleClickList(item)">
                        <section class="title">{{ item.title }}</section>
                        <section class="time" :title="item.xtCjsj">{{ formatDistance(item.xtCjsj) }}</section>
                    </section>
                    <el-divider style="margin: 0 !important;" />
                </section>
            </el-scrollbar>
        </section>
    </section>
    <DetailsDialog :item="item" v-if="dialogVisibility" @close="dialogVisibility = false" />
    <el-dialog v-model="workData.dialogVisible" title="消息提醒查看" @close="workData.dialogVisible = false">
        <el-form :model="workData.details" ref="elform" :rules="rules" label-width="130px" class="demo-ruleForm.value"
            :inline="true">
            <div>
                <el-form-item label="消息发送时间" style="margin-right: 0;width: 45%;">
                    <el-input v-model="workData.details.addtime" clearable readonly></el-input>
                </el-form-item>
                <el-form-item label="接收人" style="margin-right: 0;width: 45%;">
                    <el-input v-model="workData.details.username" clearable readonly></el-input>
                </el-form-item>
                <el-form-item label="消息标题" style="width: 90%;margin-right: 0;">
                    {{ workData.details.title }}
                </el-form-item>
                <el-form-item v-if="workData.details.p3 == '0' || workData.details.clzt == '03'" label="消息内容"
                    style="width: 90%;">
                    <el-link type="primary">{{
                        workData.details.info
                        }}</el-link>
                </el-form-item>
                <el-form-item v-if="workData.details.p3 != '0' && workData.details.clzt != '03'" label="消息内容"
                    style="width: 90%;">
                    <el-link type="primary" @click="examine(workData.details)">{{
                        workData.details.info
                        }}</el-link>
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">

                <el-button v-if="workData.details.p3 != '0' && workData.details.clzt != '03'"
                    @click="examine(workData.details)">立即处理</el-button>
                <el-button @click="workData.dialogVisible = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="isShowNotifyDetail" width="1200px" :title="`${notifyTitle}详情`" :close-on-click-modal="false">
        <div style="display: flex;align-items: center;padding-bottom: 10px;">
            <el-input style="width: 200px;margin-right: 10px;" v-model="notifyListSearch.keywords" placeholder="请输入关键字"
                clearable></el-input>
            <el-button type="primary" @click="getNotifyListData">查询</el-button>
            <el-button type="primary" @click="resetNotifyListSearch">重置</el-button>
        </div>
        <div style="width: 100%;height: 500px;">
            <MOSTY.Table :table-columns="notifyTableColumns" :tableData="notifyListData" :tableloading="tableloading"
                :isSelect="false" :isSort="false" :actionsW="280">
                <!-- <el-table :data="notifyListData" :table-columns="notifyTableColumns" style="width: 100%;height: 600px;"> -->
                <template #state="{ row }">
                    <el-tag v-if="row.state == '00'" type="danger">不通过</el-tag>
                    <el-tag v-if="row.state == '01'" type="warning">待审核</el-tag>
                    <el-tag v-else-if="row.state == '02'" type="success">已发布</el-tag>
                </template>
                <template #type="{ row }">
                    <dict-tag :options="D_BZ_TZGGLX" :value="row.type" :tag="true" />
                </template>
                <template #actions="{ row }">
                    <el-button type="primary" @click="handleClickDetail(row)">详情</el-button>
                </template>
            </MOSTY.Table>

        </div>
        <el-pagination style="margin-top: 5px;" class="pagination" @size-change="notifySizeChange"
            @current-change="notifyCurrentChange" :current-page="notifyListQuery.pageCurrent"
            :page-sizes="[2, 5, 10, 20]" :page-size="notifyListQuery.pageSize"
            layout="total, prev, pager, next, sizes, jumper" :total="notifyListQuery.total"></el-pagination>
        <template #footer>
            <span style="display: flex;justify-content: flex-end;" class="dialog-footer">
                <el-button @click="isShowNotifyDetail = false">关闭</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import Calendar from "@/components/MyComponents/Calendar/calendar.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import DetailsDialog from "../../components/DetailsDialog.vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance();
const router = useRouter();
const store = useStore();
const { D_BZ_TZGGLX } = proxy.$dict("D_BZ_TZGGLX");

const dialogVisibility = ref(false)
const item = ref({})

// 通知公告数据
const notifyListData = ref([])
const notifyListQuery = ref({
    pageCurrent: 1,
    pageSize: 10,
    total: 0,
})
const notifyListSearch = ref({
    keywords: '',
    type: ''
})
const notifyTitle = ref('')
const isShowNotifyDetail = ref(false)

// tab 列表
const listData = ref([
    { title: '工作日历', id: '04', tips: 0 },
    // { title: '通知', id: '01', tips: 0 },
    // { title: '公告', id: '02', tips: 0 },
    // { title: '工作待办', id: '03', tips: 0 }, 
])

// 通知公告列表
const messageList = ref({
    query: {
        pageCurrent: 1,
        pageSize: 10,
    },
    dataList: [],
    details: {},
    dialogVisible: false
})

// 工作待办列表
const workData = ref({
    query: {
        pageCurrent: 1,
        pageSize: 20,
        zdlx: "02",
        clzt: '01'
    },
    dataList: [],
    details: {},
    dialogVisible: false
})

const actives = ref('04')
const mLeftRef = ref()
const rules = ref()
const mLeftWidth = ref(300)
const calendarRef = ref()


const calendarMarkDates = ref([])
const calendarMarkDatesMore = ref([])

// Tab 点击切换
const handleTabs = _index => {
    actives.value = _index
    if (_index == '03') {
        getWorkListData()
    } else if (_index == '04') {
        loadCalendarMarks(new Date())
    } else {
        getListData()
    }
}

// 通知公告详情跳转
const handleClickDetail = (val) => {
    item.value = val
    const { name, title, content, writer, issuedTime, file, deptName, issuedUserId } = val || {};
    let row = { name, title, content, writer, issuedTime, file, deptName, issuedUserId }
    router.push({
        name: 'dutyBook/tzgg/show',
        params: {
            id: val.id,
            row: JSON.stringify(row)
        }
    })
}

//获取通知公告列表
const getListData = () => {
    messageList.value.query.type = actives.value
    postApi(messageList.value.query, `/mosty-jcgl/noticeController/queryNotice`).then((res) => {
        if (res.records) {
            messageList.value.dataList = res.records;
        }
    });
}

//获取工作待办列表
const getWorkListData = async () => {
    workData.value.dataList = []
    const res = await getApi(workData.value.query, `/mosty-jcgl/rw/getRwPage`)
    const records = res?.data?.records || res?.records || []
    workData.value.dataList = records
}

// 日历红点加载逻辑
const loadCalendarMarks = async (month) => {
    try {
        const year = new Date(month).getFullYear()
        const mon = new Date(month).getMonth() + 1
        const params = {
            pageCurrent: 1,
            pageSize: 100,
            zdlx: "02",
            clzt: "01" // 未处理
        }
        const res = await getApi(params, `/mosty-jcgl/rw/getRwPage`)
        const records = res?.data?.records || res?.records || []

        // 统计每一天的任务完成情况
        const statusMap = {}
        records.forEach(v => {
            if (!v.addtime) return
            const date = v.addtime.split(' ')[0]
            if (!statusMap[date]) statusMap[date] = { done: 0, total: 0 }
            statusMap[date].total++
            if (v.clzt === '03') statusMap[date].done++ // 假设03=已完成
        })

        // 根据任务完成情况打标
        const pointList = []
        Object.entries(statusMap).forEach(([date, obj]) => {
            if (obj.done === obj.total) {
                pointList.push({ date, type: 'done' })
            } else {
                pointList.push({ date, type: 'todo' })
            }
        })

        // 更新 markDateMore
        calendarMarkDatesMore.value = pointList.map(p => ({
            date: p.date,
            className: p.type === 'done' ? 'calendar-done' : 'calendar-todo'
        }))

        // 更新 markDate（必要）
        calendarMarkDates.value = pointList.map(p => p.date)

        // 调用日历组件方法
        if (calendarRef.value) {
            // 我们只用日期数组触发刷新
            // calendarRef.value.setPoint(pointList.map(p => p.date))
        }

    } catch (err) {
        console.error('加载日历标记失败:', err)
    }
}

//日历事件
const handleMonthChange = (month) => {
    console.log('月份切换:', month)
    loadCalendarMarks(month)
}

const handleDaySelect = (dateStr, date) => {
    console.log('选中日期:', dateStr, date)
}

// 查看全部
const seeMore = () => {
    const isTodoWork = actives.value == '99'
    if (isTodoWork) {
        handleMore('/dutyBook/tzgg/index', '通知公告')
    } else {
        isShowNotifyDetail.value = true
        let titleObj = {
            '01': '通知',
            '02': '公告',
            '03': '工作待办',
            '04': '日历',
        }
        notifyTitle.value = titleObj[actives.value] || '通知/公告'
        getNotifyListData()
    }
}

// 通知分页 
const resetNotifyListSearch = () => {
    notifyListSearch.value.keywords = ''
    getNotifyListData()
}
const notifySizeChange = (size) => {
    notifyListQuery.value.pageSize = size
    getNotifyListData()
}
const notifyCurrentChange = (current) => {
    notifyListQuery.value.pageCurrent = current
    getNotifyListData()
}
const getNotifyListData = () => {
    let params = {
        ...notifyListQuery.value,
        ...notifyListSearch.value,
        type: actives.value
    }
    postApi(params, `/mosty-jcgl/noticeController/queryNotice`).then((res) => {
        if (res) {
            notifyListData.value = Array.isArray(res.records) ? res.records : [];
            notifyListQuery.value.total = res.total || 0
        } else {
            notifyListData.value = []
        }
    });
}

// 工具函数
const formatDistance = (dateTimeStamp) => {
    if (dateTimeStamp) {
        let timestamp = new Date(dateTimeStamp).getTime();
        let minute = 1000 * 60;
        let hour = minute * 60;
        let day = hour * 24;
        let now = new Date().getTime();
        let diffValue = now - timestamp;
        let result;
        if (diffValue < 0) return;
        let dayC = diffValue / day;
        let hourC = diffValue / hour;
        let minC = diffValue / minute;
        if (dayC >= 2) {
            result = dateTimeStamp
        } else if (dayC < 2 && dayC > 1) {
            result = "昨天";
        } else if (hourC >= 1) {
            result = "" + parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            result = "" + parseInt(minC) + "分钟前";
        } else result = "刚刚";
        return result;
    } else return ''
}

const handleClickList = (_data) => {
    workData.value.details = _data
    workData.value.dialogVisible = true;
    let params = {
        id: _data.id,
        sfyd: "1",
        clzt: "01"
    };
    postApi(params, "/mosty-jcgl/rw/updateRw")
}

const handleMore = (_url, _title) => {
    if (_url) {
        store.commit("app/addTagsViewList", {
            fullPath: _url,
            meta: { title: _title },
            name: _url,
            params: {},
            path: _url,
            query: {},
            title: _title
        }, { immediate: true });
        router.push(_url)
    }
}

const initContentWidth = () => {
    const resizeObserver = new ResizeObserver(entries => {
        let width = entries?.[0]?.contentRect?.width;
        if (width > 0) mLeftWidth.value = width - 160;
    });
    let ele = mLeftRef.value;
    if (ele) resizeObserver.observe(ele);
}


onMounted(() => {
    getListData()
    getWorkListData()
    initContentWidth()
    loadCalendarMarks(new Date())
})
</script>

<style scoped lang="scss">
@import '../style/index.scss';

.bottom-modules {
    position: relative !important;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .posi {
            margin-left: 16px;
            width: 10px;
        }

        .tabs {
            display: flex;
            align-items: center;
            color: #666666;
            font-size: 14px;

            >article {
                margin-right: 23px;
                cursor: pointer;

                &:hover {
                    color: var(--el-color-primary);
                }
            }

            .active {
                color: #000000;
                font-size: 16px;
            }
        }
    }

    .m-content {
        height: calc(328px - 50px);

        .m-list {
            position: relative;
            cursor: pointer;
            padding: 12px 10px 0 10px;
            box-sizing: border-box;

            &:hover {
                background-color: #F5F7FA;
                border-radius: 6px;
            }

            .badde-new-1 {
                position: absolute;
                top: 3px;
                left: 3px;

                :deep(.el-badge__content) {
                    line-height: 15px;
                }
            }

            .m-top {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .m-left {
                    display: flex;
                    align-items: center;

                    >h3 {
                        width: calc(100vh - 790px);
                        color: #000000;
                        font-size: 14px;
                        margin: 0;
                        margin-left: 8px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }

            }

            .m-flex {
                display: flex;
                align-items: center;
                font-size: 12px;
                margin-top: 10px;
                justify-content: space-between;

                .title {
                    color: #909399;
                    width: 60%;

                    >p {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }

                .time {
                    color: #909399;
                    text-align: right;
                }
            }

        }
    }
}

.m-content1 {
    height: calc(328px - 50px);

    .current-date-section {
        padding: 16px 20px;
        // background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
        // color: white;
        text-align: center;

        .current-date {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 4px;
        }
    }

    .m-list1 {
        .m-flex1 {
            height: 48px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 12px;
            cursor: pointer;

            &:hover .title {
                color: var(--el-color-primary);
            }

            &:hover .time {
                color: var(--el-color-primary);
            }

            .title {
                color: #000000;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 65%;
            }

            .time {
                color: #999999;
            }
        }

    }
}
</style>
