<template>
    <home-container :customStyle="{ background: 'none' }" :customHomeStyle="{ overflow: 'hidden' }">
        <!-- <view class="mytodo-container"> -->
        <!-- <u-search v-model="keyword" placeholder="搜索任务" @search="handleSearch" @custom="handleSearch"
                @clear="handleClear" /> -->
        <h-tabs :tabs="tabList" v-model="currentTab" @change="handleTabChange" />
        <view class="mytodo-list">
            <scroll-view scroll-y="true" @refresherrefresh="onRefresh" refresher-enabled
                :refresher-triggered="refresherTriggered" @scrolltolower="loadMore" :style="{ height: '100%' }"
                enable-back-to-top="true">
                <u-checkbox-group class="checkbox-group">
                    <list-card v-for="item in filteredList" :key="item.id" :showChecked="true"
                        @click="navigateToDetail(item)">
                        <template #checkbox v-if="canShowCheckbox(item)">
                            <u-checkbox style="margin-top: 6rpx;" :checked="item.checked" :key="item.id"
                                @change="itemChange(item)" />
                        </template>
                        <template #title>
                            <view v-if="item.instance && item.instance.businessType === 'SEIZURE_REPORT'"
                                class="list-title">
                                {{ getFormData(item, 'forbiddenTypeText') }}
                                <view v-if="item.isRead === '0'" class="unread-dot"></view>
                            </view>
                            <view v-else class="list-title">
                                {{ `${getFormData(item, 'taskName')}-${item.taskName || item.title}` }}
                                <view v-if="item.isRead === '0'" class="unread-dot"></view>
                            </view>
                        </template>
                        <template #icon>
                            <list-icon
                                v-if="item.instance && item.instance.businessType === 'SEIZURE_REPORT' && getFormData(item, 'handlingMethod') === 'TRANSFER_TO_AIRPORT_POLICE'"
                                :divStyle="{ backgroundColor: '#FEF8F8', color: '#F55B5D', border: '2rpx dashed #F55B5D' }"
                                :text="'移交公安'" />
                        </template>
                        <template v-if="item.instance && item.instance.businessType === 'SEIZURE_REPORT'">
                            <view class="list-row">
                                <view class="list-label">位置：</view>
                                <view class="list-value">{{ getFormData(item, 'securityLocationText') }}</view>
                            </view>
                            <view class="list-row" style="height: auto;align-items: flex-start;">
                                <view class="list-label">查获人：</view>
                                <view class="list-value list-value-clamp-2">{{ `${getFormData(item, 'reportTeamText')} /
                                    ${getFormData(item, 'inspectUserName')}` }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">查获时间：</view>
                                <view class="list-value">{{ getFormData(item, 'seizureTime') }}</view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="list-row" v-if="item.instance &&
                                item.instance.businessType">
                                <view class="list-label">{{ `被检查${getLabel(item.instance &&
                                    item.instance.businessType)}：` }}</view>
                                <view class="list-value">{{ getChecked(item) }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">整改要求：</view>
                                <!-- <view class="list-value list-value-clamp-1">{{ getFormData(item, 'rectificationSuggestions') }}</view> -->
                            </view>
                            <view class="list-row" style="height: auto;line-height: normal !important;">
                                <view class="list-value-truncate">{{ getFormData(item, 'rectificationSuggestions') }}
                                </view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">截止时间：</view>
                                <view class="list-value">{{ getFormData(item, 'rectificationDeadline') }}</view>
                            </view>
                        </template>
                        <template #footer>
                            <div
                                :class="['card-tag', item.instance && item.instance.businessType === 'SEIZURE_REPORT' ? 'seizure-tag' : 'rectification-tag']">
                                {{ item.instance && item.instance.businessType === 'SEIZURE_REPORT' ? '查获' : '整改' }}
                            </div>
                        </template>


                    </list-card>
                </u-checkbox-group>

                <!-- 加载状态提示 -->
                <view v-if="loading" class="load-more">
                    <text>加载中...</text>
                </view>
                <view v-else-if="!hasMore && list.length > 0" class="no-more">
                    <text>没有更多数据了</text>
                </view>
                <view v-else-if="list.length === 0" class="no-data">
                    <text>暂无数据</text>
                </view>
            </scroll-view>
        </view>
        <view class="fixed-actions" v-if="currentTab === 'todo'">
            <u-checkbox-group>
                <u-checkbox :value="'all'" class="select-all" @change="handleSelectAll">全选</u-checkbox>
            </u-checkbox-group>
            <view class="batch-btn-container">
                <view class="custom-btn-white batch-btn" :disabled="selectedItems.length === 0" @click="batchReject">
                    批量驳回</view>
                <view class="custom-btn-normal batch-btn" :disabled="selectedItems.length === 0" @click="batchApprove">
                    批量通过
                </view>
            </view>
        </view>
        <!-- </view> -->
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import HTabs from "@/components/h-tabs/h-tabs.vue";
import { listCheckApprovalCcDetails, listCheckPendingTasks, listCheckFinishedTasks, updateCheckApprovalCcDetails } from "@/api/myToDoList/myToDoList.js"
import { approvePassBatch, approveRejectBatch, rectifyApprovePass, rectifyApproveReject } from "@/api/approve/approve.js";
import { showMessageTabRedDot } from "@/utils/common.js"
export default {
    components: { HomeContainer, HTabs },
    data() {
        return {
            keyword: '',
            filteredList: [],
            selectedItems: [],
            currentTab: 'todo',
            list: [],
            // 分页参数
            pageNum: 1,
            pageSize: 10,
            total: 0,
            loading: false,
            hasMore: true,
            // scroll-view下拉刷新状态控制
            refresherTriggered: false,
            // 待办任务未读数量
            todoUnreadCount: 0,
            msgUnreadCount: 0
        }
    },
    computed: {
        userInfoRoles() {
            return this.$store.state.user && this.$store.state.user.roles
        },
        tabList() {
            return [
                {
                    type: 'msg',
                    title: '消息',
                    unreadCount: this.msgUnreadCount
                },
                {
                    type: 'todo',
                    title: '待办',
                    unreadCount: this.todoUnreadCount
                },
                {
                    type: 'done',
                    title: '已办'
                }
            ];
        },
        // 判断是否显示复选框的条件
        showCheckboxCondition(item) {
            return this.canShowCheckbox(item);
        }
    },
    watch: {

    },
    methods: {
        // 判断是否显示复选框的条件
        canShowCheckbox(item) {
            //    (item.instance && item.instance.businessType === 'DEPARTMENT_CHECK' && 
            //     this.userInfoRoles.includes('jingli'))
            return (item.instance && item.instance.businessType === 'SEIZURE_REPORT') &&
                this.currentTab === 'todo';
        },

        // 根据任务类型分组
        groupTasksByType(selectedItems) {
            const seizureTaskIds = [];
            const departmentTaskIds = [];

            selectedItems.forEach(item => {
                if (item.instance && item.instance.businessType === 'SEIZURE_REPORT') {
                    seizureTaskIds.push(item.id);
                } 
                // else if (item.instance && item.instance.businessType === 'DEPARTMENT_CHECK' &&
                //     this.userInfoRoles.includes('jingli')) {
                //     departmentTaskIds.push(item.id);
                // }
            });

            return { seizureTaskIds, departmentTaskIds };
        },
        async getUnreadCount() {
            try {
                const query = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                };

                // 添加搜索关键词
                if (this.keyword) {
                    query.keyword = this.keyword;
                }
                let response = await listCheckPendingTasks(query);
                this.todoUnreadCount = response.total;
                let response1 = await listCheckApprovalCcDetails(query);

                this.msgUnreadCount = response1.rows.filter(item => item.isRead == '0').length;
            } catch (error) {
                console.error('获取待办任务未读数量失败:', error);
            }
        },
        getFormData(row, key) {
            if (row.formData) {
                const formData = JSON.parse(row.formData);
                const value = formData[key] || '';

                // 如果是时间戳字段且值为数字，进行格式化
                if ((key.includes('Time') || key.includes('Deadline')) && typeof value === 'number' && value > 0) {
                    return this.formatTimestamp(value);
                }

                return value;
            }
        },

        // 格式化时间戳为年月日时分秒
        formatTimestamp(timestamp) {
            const date = new Date(timestamp);
            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}`;
        },
        getChecked(item) {
            if (this.getLabel(item.instance && item.instance.businessType) == '科室') {
                return this.getFormData(item, 'checkedDepartmentName');
            }
            if (this.getLabel(item.instance && item.instance.businessType) == '班组') {
                return this.getFormData(item, 'checkedTeamName');
            }
            if (this.getLabel(item.instance && item.instance.businessType) == '人') {
                return this.getFormData(item, 'checkedPersonnelName');
            }
            if (this.getLabel(item.instance && item.instance.businessType) == '大队') {
                return this.getFormData(item, 'checkedBrigadeName');
            }
            return '';
        },
        getLabel(key) {
            if (key === 'PERSONAL_CHECK') {
                return '人'
            }
            if (key === 'GROUP_CHECK') {
                return '班组'
            }
            if (key === 'SECTION_CHECK') {
                return '科室'
            }
            if (key === 'BRIGADE_CHECK') {
                return '大队'
            }
            return ''
        },
        navigateToDetail(row) {

            let type = 'view'; // 默认查看模式
            if (this.currentTab == 'msg') {
                const { businessType, businessId, instanceId } = row;
                let obj = {
                    instanceId,
                    businessId,
                    businessType,
                    id,
                    nodeCode,
                    type
                }
                updateCheckApprovalCcDetails([row.ccId]
                ).then(res => {

                })
                uni.navigateTo({
                    url: `/pages/problemRect/index?params=${encodeURIComponent(JSON.stringify(obj))}`
                });
                return;
            }

            const { instance, id, nodeDefinition } = row;
            const { businessId = "", businessType = "", id: instanceId } = instance || {};
            const { nodeCode = "" } = nodeDefinition || {};
            let url = '';


            if (this.currentTab === 'todo') {
                type = 'approve'; // 待办时是审批模式
            }

            let obj = {
                instanceId,
                businessId,
                businessType,
                id,
                nodeCode,
                type // 添加type参数
            }

            //查获
            if (businessType === 'SEIZURE_REPORT') {
                url = `/pages/seizedReported/index?params=${encodeURIComponent(JSON.stringify(obj))}`;
            }
            // 巡检对应个人 班组  科室
            if (['PERSONAL_CHECK', 'GROUP_CHECK', 'SECTION_CHECK', 'BRIGADE_CHECK', 'DEPARTMENT_CHECK'].includes(businessType) || this.currentTab == 'msg') {
                url = `/pages/problemRect/index?params=${encodeURIComponent(JSON.stringify(obj))}`;
            }
            if (url) {
                uni.navigateTo({
                    url: url
                });
            }
        },
        itemChange(item) {
            item.checked = !item.checked
            if (item.checked) {
                this.selectedItems.push(item);
            } else {
                this.selectedItems = this.selectedItems.filter(selectedItem => selectedItem.id !== item.id);
            }
        },
        handleSearch(val) {
            this.pageNum = 1;
            this.keyword = val || '';
            this.loadData();
        },
        handleClear() {
            this.pageNum = 1;
            this.keyword = '';
            this.loadData();
        },
        handleTabChange(tabValue, tabItem) {
            this.pageNum = 1;
            this.currentTab = tabValue;
            this.loadData();
        },
        handleSelectAll(e) {
            console.log(e, "e")
            this.$nextTick(() => {
                this.filteredList = this.filteredList.map(item => ({
                    ...item,
                    //查获和部门检查可以批量审批
                    ...(this.canShowCheckbox(item) ? { checked: e } : {}),
                }));
                this.selectedItems = this.filteredList.filter(item => item.checked);
            })
        },
        async batchReject() {
            // 批量驳回逻辑
            if (this.selectedItems.length === 0) {
                uni.showToast({
                    title: '请选择要驳回的任务',
                    icon: 'none'
                });
                return;
            }

            try {
                // 根据任务类型分组
                const { seizureTaskIds, departmentTaskIds } = this.groupTasksByType(this.selectedItems);

                // 分别调用不同的驳回接口
                const promises = [];

                if (seizureTaskIds.length > 0) {
                    promises.push(approveRejectBatch(seizureTaskIds));
                }

                if (departmentTaskIds.length > 0) {
                    promises.push(rectifyApproveReject({ taskIdList: departmentTaskIds, comment: '审批驳回' }));
                }

                // 等待所有接口调用完成
                await Promise.all(promises);

                uni.showToast({
                    title: '批量驳回成功',
                    icon: 'success'
                });

                // 清空选中项并刷新数据
                this.selectedItems = [];
                this.filteredList = this.filteredList.map(item => ({
                    ...item,
                    checked: false
                }));
                this.loadData();
                // 刷新未读消息数量
                this.getUnreadCount();
            } catch (error) {
                console.error('批量驳回失败:', error);
                uni.showToast({
                    title: '批量驳回失败',
                    icon: 'none'
                });
            }
        },
        async batchApprove() {
            // 批量通过逻辑
            if (this.selectedItems.length === 0) {
                uni.showToast({
                    title: '请选择要通过的任务',
                    icon: 'none'
                });
                return;
            }

            try {
                // 根据任务类型分组
                const { seizureTaskIds, departmentTaskIds } = this.groupTasksByType(this.selectedItems);

                // 分别调用不同的通过接口
                const promises = [];

                if (seizureTaskIds.length > 0) {
                    promises.push(approvePassBatch(seizureTaskIds));
                }

                if (departmentTaskIds.length > 0) {
                    promises.push(rectifyApprovePass({ taskIdList: departmentTaskIds, comment: '审批通过' }));
                }

                // 等待所有接口调用完成
                await Promise.all(promises);

                uni.showToast({
                    title: '批量通过成功',
                    icon: 'success'
                });

                // 清空选中项并刷新数据
                this.selectedItems = [];
                this.filteredList = this.filteredList.map(item => ({
                    ...item,
                    checked: false
                }));
                this.loadData();
                // 刷新未读消息数量
                this.getUnreadCount();
            } catch (error) {
                console.error('批量通过失败:', error);
                uni.showToast({
                    title: '批量通过失败',
                    icon: 'none'
                });
            }
        },
        onRefresh() {
            this.pageNum = 1;
            this.refresherTriggered = true;
            this.loadData()
        },
        // 加载数据方法
        async loadData() {
            if (this.loading) return;

            this.loading = true;
            try {
                const query = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize
                };

                // 添加搜索关键词
                if (this.keyword) {
                    query.keyword = this.keyword;
                }

                let response;
                // 根据当前tab调用不同的API
                if (this.currentTab === 'msg') {
                    response = await listCheckApprovalCcDetails(query);
                } else if (this.currentTab === 'todo') {
                    response = await listCheckPendingTasks(query);
                } else if (this.currentTab === 'done') {
                    response = await listCheckFinishedTasks(query);
                }

                // 处理响应数据
                const data = response.rows || response.list || [];

                if (this.pageNum === 1) {
                    this.list = data;
                } else {
                    this.list = [...this.list, ...data];
                }

                this.total = response.total || 0;
                this.hasMore = this.list.length < this.total;

                // 更新过滤列表
                this.filteredList = [...this.list];

            } catch (error) {
                console.error('加载数据失败:', error);
                uni.showToast({
                    title: '加载失败',
                    icon: 'none'
                });
            } finally {
                this.loading = false;
                // 重置下拉刷新状态
                this.refresherTriggered = false;
                uni.stopPullDownRefresh();
            }
        },
        // 加载更多数据
        loadMore() {
            if (this.loading || !this.hasMore) return;
            this.pageNum++;
            this.loadData();
        }
    },
    mounted() {
        this.loadData();
    },
    onShow() {
        // 页面再次展示时刷新数据
        this.pageNum = 1;
        this.selectedItems = [];
        this.loadData();
        this.getUnreadCount();
        showMessageTabRedDot();
    }
}
</script>

<style lang="scss" scoped>
// .mytodo-container {
//     min-height: 100vh;
//     background: none !important;
//     overflow: hidden;


.mytodo-list {
    height: calc(100vh - 260rpx);
    // overflow: hidden; /* 防止与scroll-view的滚动冲突 */
    margin-bottom: 100rpx;

    .checkbox-group {
        display: flex;
        flex-direction: column;
    }

    .inspection-item {
        display: flex;
        flex-flow: column;
        justify-content: space-between;
        padding: 40rpx;
        background: #FFFFFF;
        box-shadow: 0 8rpx 20rpx 0 rgba(0, 0, 0, 0.08);
        border-radius: 16rpx;
        border: 2rpx solid #F0F8FF;
        margin-top: 32rpx;
    }

    .inspection-item-title {
        font-size: 32rpx;
        color: #333333;
        line-height: 38rpx;
    }

    .inspection-item-desc {
        margin: 20rpx 0 0;
        font-size: 28rpx;
        color: #666666;
    }

    /* 加载状态样式 */
    .load-more,
    .no-more,
    .no-data {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 40rpx;
        font-size: 28rpx;
        color: #999;
    }

    /* 未读红点样式 */
    .list-title {
        position: relative;
    }

    .unread-dot {
        position: absolute;
        top: -4rpx;
        right: -20rpx;
        width: 16rpx;
        height: 16rpx;
        background-color: #FF4D4F;
        border-radius: 50%;
    }

    /* list-row和list-value样式 */
    .list-row {



        .list-value-clamp-1 {

            word-break: break-all;
            /* 文字截断样式 - 超过一行显示省略号 */
            display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 三行文字截断样式 */
        .list-value-truncate {
            flex: 1;
            color: #999999;
            word-break: break-all;
            /* 三行文字截断 - 超过三行显示省略号 */
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            max-height: 120rpx;
            /* 3行 * 40rpx行高 */
        }
    }


}

// }

.fixed-actions {
    position: fixed;
    bottom: 87rpx;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 32rpx;
    background: #fff;
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.1);
    z-index: 100;

    .select-all {
        flex: 1;
    }

    .batch-btn-container {
        display: flex;

        .batch-btn {
            width: 240rpx;
            margin-top: 0;
            margin-left: 20rpx;
        }
    }


}

/* 卡片标签样式 */
.card-tag {
    position: absolute;
    bottom: 0rpx;
    right: 0rpx;
    padding: 8rpx 16rpx;
    border-radius: 8rpx 0 8rpx 0;
    font-size: 24rpx;
    font-weight: 500;
    color: #FFFFFF;
    z-index: 10;
    white-space: nowrap;
    pointer-events: none;
}

.seizure-tag {
    background-color: #1890FF;
    /* 蓝色背景 */
}

.rectification-tag {
    background-color: #FA8C16;
    /* 橙色背景 */
}
</style>