<template>
    <home-container :customStyle="{ background: 'none' }">
        <div class="inspection-list-container">
            <h-search v-model="taskName" placeholder="搜索任务" @search="handleSearch" @custom="handleSearch"
                @clear="handleClear" />
            <h-tabs v-model="currentTab" :tabs="tabList" value-key="type" label-key="title" @change="handleTabChange"
                style="margin-top: 60rpx;" />

            <div class="inspection-list">
                <scroll-view scroll-y="true" @refresherrefresh="onRefresh" refresher-enabled
                    :refresher-triggered="refresherTriggered" @scrolltolower="loadMore" :style="{ height: '100%' }">
                    <list-card v-for="(item, index) in list" :key="`${item.id}_${index}`"
                        @click="navigateToDetail(item.id)">
                        <template #title>
                            <div class="list-title">
                                {{ item.taskName }}
                                <view v-if="item.read == false" class="unread-dot"></view>
                            </div>
                        </template>
                        <template #icon v-if="item.checkRecordStatus === 'DRAFT'">
                            <list-icon
                                :divStyle="{ backgroundColor: item.checkRecordStatus === 'DRAFT' ? '#03B847' : '#FF9900' }"
                                :text="item.checkRecordStatus === 'DRAFT' ? '草稿' : '正式'" />
                        </template>
                        <template v-if="currentTab === 'task'">
                            <view class="list-row">
                                <view class="list-label">开始时间：</view>
                                <view class="list-value">{{ item.checkStartTime }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">结束时间：</view>
                                <view class="list-value">{{ item.checkEndTime }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">执行频率：</view>
                                <view class="list-value">{{ item.ruleTypeDesc }}{{ item.ruleTypeNum }}次</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">任务描述：</view>

                            </view>
                            <view class="list-row" style="height: auto;line-height: normal !important;">
                                <view class="list-value-truncate">{{ item.description }}</view>
                            </view>
                        </template>
                        <template v-if="currentTab === 'document'">
                            <view class="list-row">
                                <view class="list-label">检查人：</view>
                                <view class="list-value">{{ item.checkerName }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">任务编号：</view>
                                <view class="list-value">{{ item.taskCode }}</view>
                            </view>
                            <view class="list-row">
                                <view class="list-label">巡检编号：</view>
                                <view class="list-value">{{ item.documentCode }}</view>
                            </view>
                        </template>
                    </list-card>

                    <!-- 加载状态提示 -->
                    <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>
            </div>
        </div>
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import HTabs from "@/components/h-tabs/h-tabs.vue";
import { listCheckTask } from "@/api/check/checkTask";
import { getInspectionList } from "@/api/check/checkReward";
import useDictMixin from '@/utils/dict';

export default {
    components: { HomeContainer, HTabs },
    mixins: [useDictMixin],
    data() {
        return {
            taskName: '',
            list: [],
            currentTab: 'task',
            // 分页参数
            pageNum: 1,
            pageSize: 10,
            total: 0,
            loading: false,
            hasMore: true,
            // scroll-view下拉刷新状态控制
            refresherTriggered: false,
            // 字典数据
            checkTaskStatusOptions: [],
            checkLevelOptions: [],
            taskUnreadCount: 0,//任务未读
        }
    },
    computed: {
        currentUser() {
            return this.$store.state.user;
        },
        tabList() {
            return [
                {
                    type: 'task',
                    title: '任务入口',
                    unreadCount: this.taskUnreadCount
                },
                {
                    type: 'document',
                    title: '我的单据'
                }
            ]
        },
    },
    onShow: async function () {
        await this.init();
    },
    methods: {
        async init() {
            await this.loadDictData();
            this.loadData();
            console.log(this.currentUser, "this.currentUser")
        },
        // 加载字典数据
        async loadDictData() {
            try {
                const dict = await this.useDict('check_task_status', 'check_level');
                this.checkTaskStatusOptions = dict.check_task_status || [];
                this.checkLevelOptions = dict.check_level || [];
            } catch (error) {
                console.error('加载字典数据失败:', error);
                uni.showToast({
                    title: '字典加载失败',
                    icon: 'none'
                });
            }
        },
        navigateToDetail(id) {
            uni.navigateTo({
                url: `/pages/checklist/index?id=${id}&type=${this.currentTab}`
            });
        },
        async loadData() {
            if (this.loading) return;

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

                // 根据tab添加不同参数
                if (this.currentTab === 'task') {
                    let levelObj = {
                        'banzuzhang': "TEAM_LEVEL",
                        'kezhang': "DEPARTMENT_LEVEL",
                        'zhanzhang': "STATION_LEVEL",
                    }
                    query.status = this.checkTaskStatusOptions.find(item => item.label === '进行中')?.value;
                    query.checkLevel = levelObj[this.currentUser.roles[0]];
                } else if (this.currentTab === 'document') {
                    // console.log(this.currentUser,"this.currentUser")
                    query.checkerId = this.currentUser.id; // 使用登录人ID
                }

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

                // 根据不同的tab调用不同的API接口
                let res;
                if (this.currentTab === 'task') {
                    res = await listCheckTask(query);
                    let res1 = await listCheckTask({
                        ...query,
                        pageNum: 1,
                        pageSize: 9999
                    });;
                    this.taskUnreadCount = res1.rows.filter(item => item.read == false).length;
                } else if (this.currentTab === 'document') {
                    res = await getInspectionList(query);
                }

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

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

            } 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();
        },
        handleSearch(val) {
            this.pageNum = 1;
            this.taskName = val || '';
            this.loadData();
        },
        handleClear() {
            this.pageNum = 1;
            this.taskName = '';
            this.loadData();
        },
        handleTabChange(newValue) {
            this.pageNum = 1;
            this.currentTab = newValue;
            this.loadData();
        },
        onRefresh() {
            this.pageNum = 1;
            this.refresherTriggered = true;
            this.loadData();
        }
    }
}
</script>

<style lang="scss" scoped>
.inspection-list-container {
    // padding: 200rpx 0 0;
    background: none !important;



    .inspection-list {
        height: calc(100vh - 400rpx);
        overflow-y: auto;

        .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;
        }

        .load-more {
            flex-direction: column;
            gap: 20rpx;
        }
    }
}

.list-title {
    position: relative;
}

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



/* 三行文字截断样式 */
.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行高 */
}
</style>