<template>
    <view>
        <div class="title">
            <user-info :name="checkerName" :sub-title="subTitle" :hello="'欢迎您'" class="userInfo" />

            <!-- 排名区块 -->
            <div class="rank-container" v-if="!isZhanZhang && !this.userInfo.includes('设备维修中心')">
                <div v-for="(item, index) in rankItems" :key="index" class="rank-item">
                    <div class="rank-content">
                        <div class="rank-label">{{ item.label }}</div>
                        <div class="rank-value">{{ item.value }}</div>
                        <image :src="item.iconSrc" class="rank-image" />
                    </div>
                </div>
            </div>

            <!-- 出勤信息区块 -->
            <div class="attendance-container" v-if="!this.userInfo.includes('设备维修中心')">
                <div class="attendance-grid">
                    <div v-for="(item, index) in attendanceItems" :key="index" class="attendance-item"
                        @click="handleAttendanceClick(item)">
                        <div class="item-label">{{ item.label }}</div>
                        <div class="item-value">{{ item.value }}</div>
                    </div>
                </div>
            </div>

            <!-- 角色切换组件（班组长显示） -->
            <SelectTag v-if="role.includes('banzuzhang')" :tags="roleTags" :selected-value="selectedRole"
                @change="handleRoleChange" class="role-selector" />
        </div>

        <div class="content">
            <ReportCarousel v-if="!this.userInfo.includes('设备维修中心')"/>
            <Notice ref="notice" />
            <MessagePush v-if="!this.userInfo.includes('设备维修中心')" ref="messagePush" />

            <!-- 当 currentDepartment === '设备维修中心' 时显示 SelfCheck 组件 -->
            <SelfCheck v-if="this.userInfo.includes('设备维修中心')" />

            <!-- 当 currentDepartment !== '设备维修中心' 时显示原内容 -->
            <template v-else>
                <!-- 时间范围选择 -->
                <div class="time-range-section">
                    <div class="time-tags-container">
                        <div v-for="tag in timeTags" :key="tag.value"
                            :class="['time-tag', { 'active': selectedTimeRange === tag.value, 'time-range-label': tag.isLabel }]"
                            @click="tag.isLabel ? null : handleTimeTagClick(tag)">
                            {{ tag.label }}
                        </div>

                        <!-- 自定义时间显示 - 紧跟自定义时间标签 -->
                        <div v-if="selectedTimeRange === 'custom'" class="custom-time-inline">
                            <uni-datetime-picker v-model="dateRange" type="daterange" rangeSeparator="至"
                                @change="handleDateRangeChange" class="date-range-picker" :clear-icon="false" />
                            <div class="days-count">共 {{ totalDays }} 天</div>
                        </div>
                    </div>
                </div>

                <!-- TypeDetail组件 -->
                <TypeDetail :data-list="typeDetailData" @sort-change="handleSortChange" />

                <!-- TotalDetail组件 -->
                <TotalDetail :homePageWholeData="homePageWholeData" :start-date="startDate" :end-date="endDate"
                    :time-range="selectedTimeRange" :selectedRole="selectedRole" />


                <!-- QualityControlAnalysis组件 -->
                <QualityControlAnalysis v-if="role.includes('zhijianke') || role.includes('test')"
                    :checkProblemDistributionData="checkProblemDistributionData"
                    :accuracyAnalysisData="accuracyAnalysisData" :prohibitedTop3Data="prohibitedTop3Data"
                    :concealmentPositionTop1Data="concealmentPositionTop1Data" />

                <!-- PerformanceAnalysis组件 -->
                <PerformanceAnalysis v-if="role.includes('zhijianke') || role.includes('test')"
                    :performanceData="performanceData" />
            </template>
        </div>
    </view>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import UserInfo from "@/components/UserInfo.vue";
import QualityControlAnalysis from "@/pages/home-new/components/qualityControlAnalysis.vue";
import PerformanceAnalysis from "@/pages/home-new/components/performanceAnalysis.vue";
import HeadTitle from "@/components/HeadTitle.vue";
import ReportCarousel from "@/pages/home-new/components/reportCarousel.vue";
import MessagePush from "@/pages/home-new/components/messagePush.vue";
import Notice from "@/pages/home/components/notice.vue";
import SelectTag from "@/components/select-tag/select-tag.vue";
import TypeDetail from "@/pages/home-new/components/type-detail.vue";
import TotalDetail from "@/pages/home-new/components/total-detail.vue";
import SelfCheck from "@/pages/home-new/components/selfCheck.vue";
import { getUserProfile, getAppListByRoleId, getAppList } from "@/api/system/user";
import { getAttendanceList } from "@/api/attendance/attendance"
import { getUnreadCount } from "@/api/check/checkTask"
import { checkRolePermission } from "@/utils/common.js";
import { getHomePage, getSeizureReport, getAttendanceStats, getAccuracyStatistics, getSeizureRanking, getCheckRanking, getHomePageWhole, selectUserListByRoleKey, getMetrics, getCheckProblemDistribution, getAccuracyAnalysis, getProhibitedTop3, getConcealmentPositionTop1 } from "@/api/home-new/home-new";
// 导入uni-datetime-picker组件
import uniDatetimePicker from "@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue";

export default {
    components: {
        HeadTitle,
        UserInfo,
        HomeContainer,
        Notice,
        MessagePush,
        SelectTag,
        TypeDetail,
        TotalDetail,
        SelfCheck,
        QualityControlAnalysis,
        PerformanceAnalysis,
        uniDatetimePicker,
        ReportCarousel,
    },
    data() {
        return {
            currentDepartment: '设备维修中心', // 用于控制显示不同内容的变量
            checkerId: this.$store.state.user.id,
            userInfo: '',
            todayCheckInTime: '未打卡',
            unreadCount: 0,
            appList: [], // 存储接口返回的应用列表
            // 角色切换相关数据
            selectedRole: 'individual',
            roleTags: [
                { label: '个人', value: 'individual' },
                { label: '班组', value: 'team' }
            ],
            // 排序状态管理
            sortStates: {
                '查获数据': { teamSortType: 'asc', deptSortType: 'asc', brigadeSortType: 'asc' },
                '抽问抽答': { teamSortType: 'asc', deptSortType: 'asc', brigadeSortType: 'asc' },
                '巡视检查': { teamSortType: 'asc', deptSortType: 'asc', brigadeSortType: 'asc' }
            },
            // 排名数据
            rankData: {
                seizeRank: 0,
                seizeModalType: 0,
                answerRank: 0,
                answerModalType: 0,
                checkRank: 0,
                checkModalType: 0
            },
            // 出勤信息数据
            attendanceData: {},
            // 时间选择相关数据
            showTimePicker: false,
            startDate: '',
            endDate: '',
            dateRange: [],
            totalDays: 0,
            selectedTimeRange: 'year',
            timeTags: [
                { label: '时间范围：', value: 'label', isLabel: true },
                { label: '近一周', value: 'week' },
                { label: '近一月', value: 'month' },
                { label: '近三月', value: 'quarter' },
                { label: '近半年', value: 'halfYear' },
                { label: '近一年', value: 'year' },
                { label: '自定义时间', value: 'custom' }
            ],
            inspectionData: {},
            seizeData: {},
            attendanceStats: {},
            accuracyStatistics: {},
            homePageWholeData: [],
            subTitleText: '',
            // 绩效分析数据
            performanceData: [],
            // 检查问题分布数据
            checkProblemDistributionData: {},
            // 类型详情数据
            accuracyAnalysisData: {},
            // 违禁品TOP3数据
            prohibitedTop3Data: [],
            // 隐匿重点部位TOP1数据
            concealmentPositionTop1Data: [],
        }
    },
    computed: {
        subTitle() {
            return this.isZhanZhang ? `今日上岗大队长：${this.subTitleText}` : this.userInfo
        },
        checkerName() {
            if (this.$store.state.user) {
                if (this.$store.state.user.userInfo && this.$store.state.user.userInfo.nickName) {
                    return this.$store.state.user.userInfo.nickName
                }
            }
            return this.$store.state.user.name
        },
        role() {
            return this.$store?.state?.user?.roles
        },
        currentUser() {
            return this.$store.state.user.userInfo
        },
        // 是否为班组视图：角色是班组长或者selectedRole为team
        isTeamView() {
            return this.role.includes('banzuzhang') ? this.selectedRole === 'team' : this.role.includes('banzuzhang')
        },
        // 是否为个人视图：selectedRole为individual或者角色是SecurityCheck
        isIndividualView() {
            return this.role.includes('banzuzhang') ? this.selectedRole === 'individual' : this.role.includes('SecurityCheck')
        },
        isBrigade() {
            return this.role.includes('jingli') || this.role.includes('xingzheng')
        },
        // 是否为站长或质检科角色
        isZhanZhang() {
            return this.role.includes('test') || this.role.includes('zhijianke')
        },
        // TypeDetail组件数据
        typeDetailData() {
            console.log('this.seizeData', this.seizeData, this.seizeData.stationMasterData)
            return [
                {
                    title: '查获数据',
                    linkText: this.isZhanZhang ? "" : this.isIndividualView ? (this.seizePendingCount ? `${this.seizePendingCount}条草稿待处理` : '') : (this.seizePendingCount ? `${this.seizePendingCount}条数据待处理` : ''),
                    link: this.isIndividualView ? '/pages/voiceSubmissionDraft/index' : '/pages/myToDoList/index',
                    statTitle: '查获数量',
                    teamSortType: this.sortStates['查获数据'].teamSortType,
                    deptSortType: this.sortStates['查获数据'].deptSortType,
                    brigadeSortType: this.sortStates['查获数据'].brigadeSortType,
                    dividerIndex: this.isBrigade ? 1 : 0,
                    dataItems: this.getSeizeDataItems(),
                    rankList: this.getSeizeRankList(),
                    departmentRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.topThreeDepartmentRankings ? this.seizeData.stationMasterData.topThreeDepartmentRankings.map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.departmentName })) : [],
                    bottomDepartmentRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.botomThreeDepartmentRankings ? [...this.seizeData.stationMasterData.botomThreeDepartmentRankings].sort((a, b) => (a.seizureCount || 0) - (b.seizureCount || 0)).slice(0, 3).map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.departmentName })) : [],
                    teamRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.topThreeTeamRankings ? this.seizeData.stationMasterData.topThreeTeamRankings.map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.teamName })) : [],
                    bottomTeamRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.botomThreeTeamRankings ? this.seizeData.stationMasterData.botomThreeTeamRankings.map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.teamName })) : [],
                    brigadeRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.brigadeRankings ? [...this.seizeData.stationMasterData.brigadeRankings].sort((a, b) => (b.seizureCount || 0) - (a.seizureCount || 0)).slice(0, 5).map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.brigadeName })) : [],
                    bottomBrigadeRank: this.seizeData.stationMasterData && this.seizeData.stationMasterData.brigadeRankings ? [...this.seizeData.stationMasterData.brigadeRankings].sort((a, b) => (a.seizureCount || 0) - (b.seizureCount || 0)).slice(0, 5).map(item => ({ ...item, passRate: item.seizureCount.toFixed(2), name: item.brigadeName })) : [],
                },
                {
                    title: '抽问抽答',
                    linkText: this.isIndividualView || this.isTeamView ? this.accuracyStatistics.hasPendingTask ? '待答题' : '' : '',
                    link: '/pages/daily-exam/task-list/index',
                    statTitle: '正确率（%）',
                    teamSortType: this.sortStates['抽问抽答'].teamSortType,
                    deptSortType: this.sortStates['抽问抽答'].deptSortType,
                    brigadeSortType: this.sortStates['抽问抽答'].brigadeSortType,
                    dividerIndex: this.isBrigade ? 1 : 0,
                    dataItems: this.getQuestionDataItems(),
                    rankList: this.getQuestionRankList(),
                    departmentRank: this.accuracyStatistics.topDepts && this.accuracyStatistics.topDepts.map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                    bottomDepartmentRank: this.accuracyStatistics.bottomDepts && [...this.accuracyStatistics.topDepts].sort((a, b) => (a.accuracy || 0) - (b.accuracy || 0)).map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                    teamRank: this.accuracyStatistics.topTeamsInSite && this.accuracyStatistics.topTeamsInSite.map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                    bottomTeamRank: this.accuracyStatistics.bottomTeamsInSite && this.accuracyStatistics.bottomTeamsInSite.map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                    brigadeRank: this.accuracyStatistics.brigadeRankingList && [...this.accuracyStatistics.brigadeRankingList].sort((a, b) => (b.accuracy || 0) - (a.accuracy || 0)).slice(0, 5).map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                    bottomBrigadeRank: this.accuracyStatistics.brigadeRankingList && [...this.accuracyStatistics.brigadeRankingList].sort((a, b) => (a.accuracy || 0) - (b.accuracy || 0)).slice(0, 5).map(item => ({ ...item, passRate: item.accuracy.toFixed(2), name: item.name })),
                },
                {
                    title: '巡视检查',
                    linkText: this.isZhanZhang ? "" : this.inspectionData.toDoNumber ? `${this.inspectionData.toDoNumber}条待处理任务` : "",
                    link: '/pages/myToDoList/index',
                    statTitle: '合格率（%）',
                    teamSortType: this.sortStates['巡视检查'].teamSortType,
                    deptSortType: this.sortStates['巡视检查'].deptSortType,
                    brigadeSortType: this.sortStates['巡视检查'].brigadeSortType,
                    dividerIndex: this.isBrigade ? 1 : 0,
                    dataItems: this.getInspectionDataItems(),
                    completed: this.inspectionData.doneNumber,
                    pending: this.inspectionData.doingNumber,
                    rankList: this.getRankList(),
                    departmentRank: this.inspectionData.departmentRankingList && this.inspectionData.departmentRankingList.map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2) })),
                    bottomDepartmentRank: this.inspectionData.reverseDepartmentRankingList && [...this.inspectionData.reverseDepartmentRankingList].sort((a, b) => (a.passRate || 0) - (b.passRate || 0)).slice(0, 5).map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2) })),
                    teamRank: this.inspectionData.teamRankingList && this.inspectionData.teamRankingList.map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2) })),
                    bottomTeamRank: this.inspectionData.reverseTeamRankingList && this.inspectionData.reverseTeamRankingList.map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2) })),
                    brigadeRank: this.inspectionData.brigadeRankingList && [...this.inspectionData.brigadeRankingList].sort((a, b) => (a.rank || 0) - (b.rank || 0)).slice(0, 5).map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2), name: item.name })),
                    bottomBrigadeRank: this.inspectionData.brigadeRankingList && [...this.inspectionData.brigadeRankingList].sort((a, b) => (b.rank || 0) - (a.rank || 0)).slice(0, 5).map(item => ({ ...item, passRate: (item.passRate * 100).toFixed(2), name: item.name })),
                }
            ]
        },

        // 排名项数组
        rankItems() {
            return [
                {
                    label: '查获排名',
                    value: `${this.rankData.seizeRank}`,
                    iconSrc: this.getRankImage(this.rankData.seizeModalType)
                },
                {
                    label: '答题排名',
                    value: `${this.rankData.answerRank}`,
                    iconSrc: this.getRankImage(this.rankData.answerModalType)
                },
                {
                    label: '检查排名',
                    value: `${this.rankData.checkRank}`,
                    iconSrc: this.getRankImage(this.rankData.checkModalType)
                }
            ];
        },

        // 根据角色返回不同的出勤信息数组
        attendanceItems() {
            let res = {};

            if (this.role.includes('kezhang') || this.isZhanZhang || this.isBrigade) {
                // 班组长选择班组视图
                if (this.isZhanZhang) {
                    res = this.attendanceStats.stationLeaderStats
                }
                if (this.role.includes('kezhang')) {
                    res = this.attendanceStats.sectionLeaderStats
                }
                if (this.isBrigade) {
                    res = this.attendanceStats.brigadeLeaderStats
                }

                // 抽离复杂的判断逻辑
                const isZhanZhang = this.isZhanZhang;
                const firstLabel = isZhanZhang ? '在岗大队' : this.isBrigade ? '执勤大队' : '在岗班组';
                const firstValue = (isZhanZhang || this.isBrigade) ? (res?.dutyDeptName || '暂无') : res?.onDutyTeamCount;

                const secondLabel = isZhanZhang || this.isBrigade ? '在岗班组' : '在岗人员';
                const secondValue = isZhanZhang || this.isBrigade ? res?.onDutyTeamCount : res?.onDutyPersonnelCount;

                const thirdLabel = isZhanZhang || this.isBrigade ? '在岗人员' : '出勤时间';
                const thirdValue = (isZhanZhang || this.isBrigade) ? res?.onDutyPersonnelCount : (res?.attendanceTime || res?.attendanceTimeTips);
                const thirdLink = isZhanZhang ? '' : (res?.attendanceTime ? '' : '/pages/attendance/index');

                return [
                    { label: firstLabel, value: firstValue },
                    { label: secondLabel, value: secondValue },
                    { label: thirdLabel, value: thirdValue, link: thirdLink },
                    { label: '今日查获数量', value: res?.todaySeizureReportCount },
                    { label: '今日巡视检查问题', value: res?.todayCheckCorrectionCount },
                    { label: '今日抽问抽答', value: `${this.accuracyStatistics?.todayTaskCompletion?.completedCount || 0}/${this.accuracyStatistics?.todayTaskCompletion?.totalCount || 0}` }
                ];
            } else {
                res = this.attendanceStats.teamLeaderStats || this.attendanceStats.securityCheckStats

                // 个人视图或非班组长角色
                return [
                    { label: '出勤班组', value: res?.attendanceTeamName },
                    { label: '出勤通道', value: res?.attendanceChannel },
                    { label: '出勤时间', value: res?.attendanceTime || res?.attendanceTimeTips, link: res?.attendanceTime ? '' : '/pages/attendance/index' }
                ];
            }
        },
        seizePendingCount() {
            // 根据角色返回不同的排名数据
            if (this.isIndividualView) {
                const { securityCheckerData } = this.seizeData;
                const { pendingCount } = securityCheckerData || {};
                return pendingCount;
            } else if (this.role.includes('kezhang')) {
                const { sectionMasterData } = this.seizeData;
                const { pendingCount } = sectionMasterData || {};
                // 科长、SecurityCheck角色：显示班组、科级和站级排名
                return pendingCount;
            } else if (this.isTeamView) {
                const { teamLeaderData } = this.seizeData;
                const { pendingCount } = teamLeaderData || {}
                return pendingCount;
            } else {

            }
        }
    },

    async onShow() {
        // 使用统一的loadAllData方法并行加载所有数据
        await this.loadAllData();

        // 数据获取完成后执行其他函数
        this.updateCurrentDate();
        this.getUnreadCount();

        // 页面显示时，刷新子组件的数据 - 使用$nextTick确保DOM已渲染完成
        this.$nextTick(() => {
            console.log("notice====", this.$refs.notice)
            this.$refs.notice?.refreshData();
            this.$refs.announcement?.refreshData();
        });
    },
    onLoad() {
        this.getUser()
        this.loadTodayRecord();
        this.setDefaultDates();

    },
    methods: {
        // 设置默认日期
        setDefaultDates() {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);

            // 与calculateDateRange方法中的近一年计算方式保持一致：从365天前到昨天
            const startDate = new Date(yesterday);
            startDate.setDate(yesterday.getDate() - 364);

            // 使用本地时间格式化，避免UTC时间转换问题
            this.startDate = this.formatLocalDate(startDate)
            this.endDate = this.formatLocalDate(yesterday)

            // 初始化dateRange
            this.dateRange = [this.startDate, this.endDate]
            this.calculateDays()
        },

        // 格式化本地日期为YYYY-MM-DD格式
        formatLocalDate(date) {
            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}`;
        },

        // 计算天数
        calculateDays() {
            if (this.startDate && this.endDate) {
                const start = new Date(this.startDate)
                const end = new Date(this.endDate)
                const diffTime = Math.abs(end - start)
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
                this.totalDays = diffDays
            }
        },

        // 处理日期范围变化
        async handleDateRangeChange(e) {

            if (e && Array.isArray(e) && e.length === 2) {
                this.startDate = e[0]
                this.endDate = e[1]
                this.calculateDays()
                await this.loadAllData();
            }
        },

        // 统一加载所有数据的方法
        async loadAllData() {
            try {
                // 使用Promise.allSettled并行执行所有数据接口请求
                const results = await Promise.allSettled([
                    this.getInspectionData(),      // 巡检数据
                    this.getSeizeData(),           // 查获上报数据
                    this.getAttendanceStats(),     // 出勤统计数据
                    this.fetchAccuracyStatistics(), // 抽问抽答数据
                    this.getRank(),                // 排名数据
                    this.getHomePageWholeData(),   // 首页整体数据
                    this.getTodayOnDutyKeZhang(),   // 今日上岗科长信息
                    this.getPerformanceData(),     // 绩效分析数据
                    this.getCheckProblemDistributionData(), // 检查问题分布数据
                    this.getAccuracyAnalysis(),    // 正确率分析数据
                    this.getProhibitedTop3Data(),  // 违禁品TOP3数据
                    this.getConcealmentPositionTop1Data() // 隐匿重点部位TOP1数据
                ]);

                // 检查每个接口的请求结果
                results.forEach((result, index) => {
                    const apiNames = [
                        'getInspectionData',
                        'getSeizeData',
                        'getAttendanceStats',
                        'fetchAccuracyStatistics',
                        'getRank',
                        'getHomePageWholeData',
                        'getTodayOnDutyKeZhang',
                        'getPerformanceData',
                        'getCheckProblemDistribution',
                        'getAccuracyAnalysis',
                        'getProhibitedTop3Data',
                        'getConcealmentPositionTop1Data'
                    ];

                    if (result.status === 'rejected') {
                        console.warn(`${apiNames[index]} 接口请求失败:`, result.reason);
                    } else {
                        console.log(`${apiNames[index]} 接口请求成功`);
                    }
                });

                return results;
            } catch (error) {
                console.error('加载数据失败:', error);
                throw error;
            }
        },
        // 获取检查问题分布数据
        async getCheckProblemDistributionData() {
            return new Promise((resolve, reject) => {
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);

                const params = {
                    startDate: startDate,
                    endDate: endDate
                };

                getCheckProblemDistribution(params).then(res => {
                    if (res && res.data) {
                        console.log('检查问题分布数据:', res.data);
                        this.checkProblemDistributionData = res.data;
                        resolve(res.data);
                    } else {
                        this.checkProblemDistributionData = {};
                        resolve(null);
                    }
                }).catch(error => {
                    console.error('获取检查问题分布数据失败:', error);
                    this.checkProblemDistributionData = {};
                    reject(error);
                });
            });
        },

        // 获取正确率分析数据
        getAccuracyAnalysis() {
            return new Promise((resolve, reject) => {
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);

                const params = {
                    startDate: startDate,
                    endDate: endDate
                };

                getAccuracyAnalysis(params).then(res => {
                    if (res && res.data) {
                        console.log('正确率分析数据:', res.data);
                        this.accuracyAnalysisData = res.data;
                        resolve(res.data);
                    } else {
                        resolve(null);
                    }
                }).catch(error => {
                    console.error('获取正确率分析数据失败:', error);
                    reject(error);
                });
            });
        },
        // 获取绩效分析数据
        getPerformanceData() {
            return new Promise((resolve, reject) => {
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);

                const params = {
                    startTime: startDate,
                    endTime: endDate,
                    sortField: 'totalScore',
                    dimension: '4'
                };

                getMetrics(params).then(res => {

                    if (res && res.data) {
                        this.performanceData = res.data;

                        resolve(res.data);
                    } else {
                        resolve([]);
                    }
                }).catch(error => {
                    console.error('获取绩效数据失败:', error);
                    reject(error);
                });
            });
        },

        // 获取违禁品TOP3数据
        getProhibitedTop3Data() {
            return new Promise((resolve, reject) => {
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);

                const params = {
                    startDate: startDate,
                    endDate: endDate
                };

                getProhibitedTop3(params).then(res => {
                    if (res && res.data) {
                        console.log('违禁品TOP3数据:', res.data);
                        this.prohibitedTop3Data = res.data;
                        resolve(res.data);
                    } else {
                        this.prohibitedTop3Data = {};
                        resolve(null);
                    }
                }).catch(error => {
                    console.error('获取违禁品TOP3数据失败:', error);
                    this.prohibitedTop3Data = {};
                    reject(error);
                });
            });
        },

        // 获取隐匿重点部位TOP1数据
        getConcealmentPositionTop1Data() {
            return new Promise((resolve, reject) => {
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);

                const params = {
                    startDate: startDate,
                    endDate: endDate
                };

                getConcealmentPositionTop1(params).then(res => {
                    if (res && res.data) {
                        console.log('隐匿重点部位TOP1数据:', res.data);
                        this.concealmentPositionTop1Data = res.data;
                        resolve(res.data);
                    } else {
                        this.concealmentPositionTop1Data = [];
                        resolve(null);
                    }
                }).catch(error => {
                    console.error('获取隐匿重点部位TOP1数据失败:', error);
                    this.concealmentPositionTop1Data = [];
                    reject(error);
                });
            });
        },
        getRank() {
            return new Promise((resolve, reject) => {
                let params = {};
                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;
                params.dataSource = this.selectedRole;

                let idObj = {}
                if (this.isIndividualView) {
                    idObj = { userId: this.currentUser.userId }
                } else {
                    // 如果是班组视图，使用当前用户的部门ID
                    if (this.selectedRole === 'team') {
                        idObj = { deptId: this.currentUser.deptId }
                    } else {
                        // 个人视图，使用当前用户的部门ID
                        idObj = { deptId: this.currentUser.deptId }
                    }
                }

                // 构建API请求数组
                const apiRequests = [getSeizureRanking(params)];

                // 如果角色不是test，才请求getCheckRanking接口
                if (!this.role.includes('test')) {
                    apiRequests.push(getCheckRanking({ ...params, ...idObj }));
                }

                // 使用Promise.allSettled并行执行API请求，即使有接口失败也不影响其他接口
                Promise.allSettled(apiRequests).then((results) => {
                    // 处理每个接口的结果
                    results.forEach((result, index) => {
                        if (result.status === 'fulfilled') {
                            const res = result.value;
                            if (index === 0) {
                                // 处理查获排名数据
                                const { data: seizureData } = res || {};
                                this.rankData.seizeRank = seizureData[0]?.rank;
                                this.rankData.seizeModalType = seizureData[0]?.medalType;
                            } else if (index === 1) {
                                // 处理检查排名数据
                                const { data: checkData } = res;
                                const { checkLargeScreenHomePageRankingDto, dailyTaskAccuracyRankingDto } = checkData
                                this.rankData.checkRank = checkLargeScreenHomePageRankingDto.rank;
                                this.rankData.checkModalType = checkLargeScreenHomePageRankingDto.medalType;
                                this.rankData.answerRank = dailyTaskAccuracyRankingDto.rank;
                                this.rankData.answerModalType = dailyTaskAccuracyRankingDto.medalType;
                            }
                        } else {
                            console.warn(`第${index + 1}个接口请求失败:`, result.reason);
                        }
                    });

                    resolve({
                        seizureData: results[0]?.status === 'fulfilled' ? results[0].value.data : null,
                        checkData: results[1]?.status === 'fulfilled' ? results[1].value.data : null
                    });
                });
            });
        },
        getInspectionData() {
            return new Promise((resolve, reject) => {
                let params = {}

                // 根据角色和selectedRole设置参数
                if (this.isIndividualView) {
                    params = { userId: this.currentUser.userId }
                } else {
                    // 如果是班组视图，使用当前用户的部门ID
                    if (this.selectedRole === 'team') {
                        params = { deptId: this.currentUser.deptId }
                    } else {
                        // 个人视图，使用当前用户的部门ID
                        params = { deptId: this.currentUser.deptId }
                    }
                }

                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;

                getHomePage(params).then(res => {
                    // console.log("res", res)
                    this.inspectionData = res.data || {};
                    resolve(res.data);
                }).catch(error => {
                    console.error("获取巡检数据失败:", error);
                    reject(error);
                });
            });
        },

        getHomePageWholeData() {
            return new Promise((resolve, reject) => {
                let params = {}
                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;
                params.dataSource = this.selectedRole;

                getHomePageWhole(params).then(res => {

                    this.homePageWholeData = res.data || [];
                    // 这里可以处理getHomePageWhole接口返回的数据
                    resolve(res.data);
                }).catch(error => {
                    console.error("获取整体数据失败:", error);
                    reject(error);
                });
            });
        },
        getSeizeData() {
            return new Promise((resolve, reject) => {
                let params = {}
                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;
                if (!this.isZhanZhang && !this.role.includes('kezhang')) {
                    params.dataSource = this.selectedRole;
                }

                getSeizureReport(params).then(res => {
                    // console.log("res", res)
                    this.seizeData = res.data || {};
                    resolve(res.data);
                }).catch(error => {
                    console.error("获取查获数据失败:", error);
                    reject(error);
                });
            });
        },

        getAttendanceStats() {
            return new Promise((resolve, reject) => {
                let params = {}
                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;
                params.dataSource = this.selectedRole;
                getAttendanceStats(params).then(res => {
                    console.log("出勤统计数据:", res)
                    this.attendanceStats = res.data || {};
                    resolve(res.data);
                }).catch(error => {
                    console.error("获取出勤统计数据失败:", error);
                    reject(error);
                });
            });
        },

        fetchAccuracyStatistics() {
            return new Promise((resolve, reject) => {
                let params = {}
                // 根据时间范围计算开始时间和结束时间（不包括今天）
                const { startDate, endDate } = this.calculateDateRange(this.selectedTimeRange);
                params.startDate = startDate;
                params.endDate = endDate;
                params.dataSource = this.selectedRole;

                getAccuracyStatistics(params).then(res => {
                    console.log("准确率统计数据:", res)
                    this.accuracyStatistics = res.data || {};
                    // this.rankData.answerRank = this.accuracyStatistics.deptInSiteRanking.rank;
                    // this.rankData.answerRank = this.accuracyStatistics.deptInSiteRanking.rank;
                    resolve(res.data);
                }).catch(error => {
                    console.error("获取准确率统计数据失败:", error);
                    reject(error);
                });
            });
        },

        // 根据时间范围计算开始时间和结束时间（不包括今天）
        calculateDateRange(timeRange) {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);

            let startDate = new Date(yesterday);
            let endDate = new Date(yesterday);

            switch (timeRange) {
                case 'week':
                    // 近一周：从7天前到昨天
                    startDate.setDate(yesterday.getDate() - 6);
                    break;
                case 'month':
                    // 近一月：从30天前到昨天
                    startDate.setDate(yesterday.getDate() - 29);
                    break;
                case 'quarter':
                    // 近三月：从90天前到昨天
                    startDate.setDate(yesterday.getDate() - 89);
                    break;
                case 'halfYear':
                    // 近半年：从180天前到昨天
                    startDate.setDate(yesterday.getDate() - 179);
                    break;
                case 'year':
                    // 近一年：从365天前到昨天
                    startDate.setDate(yesterday.getDate() - 364);
                    break;
                case 'custom':
                    // 自定义时间：使用用户选择的日期
                    if (this.startDate && this.endDate) {
                        startDate = new Date(this.startDate);
                        endDate = new Date(this.endDate);

                    }
                    break;
                default:
                    // 默认近一周
                    startDate.setDate(yesterday.getDate() - 364);
            }

            return {
                startDate: this.formatDateForInput(startDate),
                endDate: this.formatDateForInput(endDate)
            };
        },
        // 处理角色切换
        async handleRoleChange(roleValue) {
            this.selectedRole = roleValue;

            // 根据角色切换重新加载所有数据
            try {
                // 使用Promise.allSettled并行执行所有接口请求，即使有接口失败也不影响其他接口
                const results = await Promise.allSettled([
                    this.getInspectionData(),
                    this.getSeizeData(),
                    this.getAttendanceStats(),
                    this.fetchAccuracyStatistics(),
                    this.getRank(),
                    this.getHomePageWholeData()
                ]);

                // 检查是否有接口失败
                results.forEach((result, index) => {
                    if (result.status === 'rejected') {
                        console.warn(`第${index + 1}个接口请求失败:`, result.reason);
                    }
                });

                console.log('角色切换后数据重新加载完成');
            } catch (error) {
                console.error('角色切换后数据加载失败:', error);
                uni.showToast({
                    title: '数据加载失败',
                    icon: 'none'
                });
            }
        },

        // 显示自定义时间选择器
        showCustomTimePicker(timeRange) {
            this.selectedTimeRange = timeRange;
            this.showTimePicker = true;
            // 优先回显自定义的时间，如果已有自定义时间则使用，否则设置默认日期
            if (!this.startDate || !this.endDate) {
                const today = new Date();
                const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
                this.startDate = this.formatDateForInput(oneWeekAgo);
                this.endDate = this.formatDateForInput(today);
            }
        },

        // 处理时间标签点击
        handleTimeTagClick(tag) {
            if (tag.value === 'custom') {
                // 自定义时间：显示时间选择器
                this.showCustomTimePicker(tag.value);
            } else {
                // 预设时间范围：直接切换
                this.selectedTimeRange = tag.value;
                this.showTimePicker = false;


                this.loadDataByTimeRange(tag.value);
            }
        },

        // 处理日期变化
        handleDateChange() {
            // 只有当两个时间都选择了才请求接口
            if (this.startDate && this.endDate) {
                const customRange = {
                    startDate: this.startDate,
                    endDate: this.endDate
                };
                this.loadDataByCustomRange(customRange);
            }
        },

        // 处理排序切换
        handleSortChange(title, type, sortType) {
            if (this.sortStates[title]) {
                if (type === 'team') {
                    this.sortStates[title].teamSortType = sortType;
                } else if (type === 'dept') {
                    this.sortStates[title].deptSortType = sortType;
                } else if (type === 'brigade') {
                    this.sortStates[title].brigadeSortType = sortType;
                }
            }
        },



        // 处理时间范围变化
        handleTimeRangeChange(timeRange) {
            this.selectedTimeRange = timeRange;
            this.showTimePicker = false;
            this.loadDataByTimeRange(timeRange);
        },

        // 取消时间选择
        cancelTimePicker() {
            this.showTimePicker = false;
        },



        // 格式化日期为输入框格式
        formatDateForInput(date) {
            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}`;
        },

        // 根据时间范围加载数据
        async loadDataByTimeRange(timeRange) {
            try {
                console.log('加载时间范围数据:', timeRange);
                // 使用统一的loadAllData方法加载所有数据
                await this.loadAllData();
                console.log('时间范围切换后数据重新加载完成');
            } catch (error) {
                console.error('加载时间范围数据失败:', error);
                uni.showToast({
                    title: '数据加载失败',
                    icon: 'none'
                });
            }
        },
        handleAttendanceClick(item) {

            if (item.link) {
                uni.navigateTo({
                    url: item.link
                });
            }


        },

        // 根据自定义时间范围加载数据
        async loadDataByCustomRange(customRange) {
            try {
                console.log('加载自定义时间范围数据:', customRange);
                // 使用统一的loadAllData方法加载所有数据
                await this.loadAllData();
                console.log('自定义时间范围切换后数据重新加载完成');
            } catch (error) {
                console.error('加载自定义时间范围数据失败:', error);
                uni.showToast({
                    title: '数据加载失败',
                    icon: 'none'
                });
            }
        },

        // 根据排名类型和排名值获取图片路径
        getRankImage(type) {
            console.log('获取排名图片:', type);
            switch (type) {
                case 1: return '/static/images/icon/gold.png';
                case 2: return '/static/images/icon/silver.png';
                case 3: return '/static/images/icon/bronze.png';
                case 4: return '/static/images/icon/red-face.png';
                case 5: return '/static/images/icon/orange-face.png';
                case 6: return '/static/images/icon/yellow-face.png';
            }
        },
        // 根据角色获取检查项标签文字
        getInspectionItemLabel() {
            if (this.isIndividualView) {
                return '本人';
            } else if (this.isTeamView) {
                return '班组';
            } else if (this.role.includes('kezhang')) {
                return '主管';
            } else if (this.isZhanZhang) {
                return '全站';
            } else {
                return '检查项'; // 默认值
            }
        },

        // 根据角色获取巡检数据项数组
        getInspectionDataItems() {
            const { personalPassRate, teamPassRate, departmentPassRate, stationPassRate, teamRankingList, departmentRankingList, brigadeRankingList, brigadePassRate } = this.inspectionData;
            if (this.isIndividualView) {
                // SecurityCheck角色：本人、班平均、主管平均、站平均
                return [
                    { label: '本人', value: ((personalPassRate || 0) * 100).toFixed(2), isImage: false },
                    { label: '班平均', value: ((teamPassRate || 0) * 100).toFixed(2), isImage: false, color: teamPassRate < personalPassRate ? '#00AE41' : '#F96060' },
                    { label: '主管平均', value: ((departmentPassRate || 0) * 100).toFixed(2), isImage: false, color: departmentPassRate < personalPassRate ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: ((brigadePassRate || 0) * 100).toFixed(2), isImage: false, color: brigadePassRate < personalPassRate ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: ((stationPassRate || 0) * 100).toFixed(2), isImage: false, color: stationPassRate < personalPassRate ? '#00AE41' : '#F96060' }
                ];
            } else if (this.isTeamView) {
                // banzuzhang角色：班组、主管平均、站平均
                return [
                    { label: '班组', value: ((teamPassRate || 0) * 100).toFixed(2), isImage: false },
                    { label: '主管平均', value: ((departmentPassRate || 0) * 100).toFixed(2), isImage: false, color: departmentPassRate < teamPassRate ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: ((brigadePassRate || 0) * 100).toFixed(2), isImage: false, color: brigadePassRate < personalPassRate ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: ((stationPassRate || 0) * 100).toFixed(2), isImage: false, color: stationPassRate < teamPassRate ? '#00AE41' : '#F96060' }
                ];
            } else if (this.role.includes('kezhang')) {
                // kezhang角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '主管', value: ((departmentPassRate || 0) * 100).toFixed(2), isImage: false },
                    { label: '大队平均', value: ((brigadePassRate || 0) * 100).toFixed(2), isImage: false, color: brigadePassRate < personalPassRate ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: ((stationPassRate || 0) * 100).toFixed(2), isImage: false, color: stationPassRate < departmentPassRate ? '#00AE41' : '#F96060' },

                ];
            } else if (this.isBrigade) {
                // brigade角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '大队', value: ((brigadePassRate || 0) * 100).toFixed(2), isImage: false },
                    { label: '站平均', value: ((stationPassRate || 0) * 100).toFixed(2), isImage: false, color: stationPassRate < brigadePassRate ? '#00AE41' : '#F96060' },
                    { label: this.getObjByRank(departmentRankingList, 1).name, value: '/static/images/icon/one.png', isImage: true },
                    { label: this.getObjByRank(departmentRankingList, 2).name, value: '/static/images/icon/two.png', isImage: true },
                    { label: this.getObjByRank(departmentRankingList, 3).name, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else if (this.isZhanZhang) {
                // test/zhijianke角色：全站、前三名的科室(isImage: true)
                return [
                    { label: '全站', value: ((stationPassRate || 0) * 100).toFixed(2), isImage: false },
                    { label: this.getObjByRank(brigadeRankingList, 1).name, value: '/static/images/icon/one.png', isImage: true },
                    { label: this.getObjByRank(brigadeRankingList, 2).name, value: '/static/images/icon/two.png', isImage: true },
                    { label: this.getObjByRank(brigadeRankingList, 3).name, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else {
                // 默认角色：检查项、完成率
                return [
                    { label: '检查项', value: '12', isImage: false },
                    { label: '完成率', value: '92%', isImage: false }
                ];
            }
        },
        //获取抽问抽答
        getQuestionDataItems() {
            const { personalAccuracy, teamAvgAccuracy, deptAvgAccuracy, siteAvgAccuracy, topDepts, topKezhangInBrigade, brigadeAvgAccuracy, brigadeRankingList } = this.accuracyStatistics;
            if (this.isIndividualView) {
                // SecurityCheck角色：本人、班平均、主管平均、站平均
                return [
                    { label: '本人', value: (personalAccuracy || 0), isImage: false },
                    { label: '班平均', value: (teamAvgAccuracy || 0), isImage: false, color: teamAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' },
                    { label: '主管平均', value: (deptAvgAccuracy || 0), isImage: false, color: deptAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: (brigadeAvgAccuracy || 0), isImage: false, color: deptAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (siteAvgAccuracy || 0), isImage: false, color: siteAvgAccuracy < personalAccuracy ? '#00AE41' : '#F96060' }
                ];
            } else if (this.isTeamView) {
                // banzuzhang角色：班组、主管平均、站平均
                return [
                    { label: '班组', value: (teamAvgAccuracy || 0), isImage: false },
                    { label: '主管平均', value: (deptAvgAccuracy || 0), isImage: false, color: deptAvgAccuracy < teamAvgAccuracy ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: (brigadeAvgAccuracy || 0), isImage: false, color: brigadeAvgAccuracy < teamAvgAccuracy ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (siteAvgAccuracy || 0), isImage: false, color: siteAvgAccuracy < teamAvgAccuracy ? '#00AE41' : '#F96060' }
                ];
            } else if (this.role.includes('kezhang')) {
                // kezhang角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '主管', value: (deptAvgAccuracy || 0), isImage: false, },
                    { label: '大队平均', value: (brigadeAvgAccuracy || 0), isImage: false, color: brigadeAvgAccuracy < deptAvgAccuracy ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (siteAvgAccuracy || 0), isImage: false, color: siteAvgAccuracy < deptAvgAccuracy ? '#00AE41' : '#F96060' },

                ];
            } else if (this.isBrigade) {
                // brigade角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '大队', value: (brigadeAvgAccuracy || 0), isImage: false, },
                    { label: '站平均', value: (siteAvgAccuracy || 0), isImage: false, color: siteAvgAccuracy < deptAvgAccuracy ? '#00AE41' : '#F96060' },
                    { label: this.getObjByRank(topKezhangInBrigade, 1).name, value: '/static/images/icon/one.png', isImage: true },
                    { label: this.getObjByRank(topKezhangInBrigade, 2).name, value: '/static/images/icon/two.png', isImage: true },
                    { label: this.getObjByRank(topKezhangInBrigade, 3).name, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else if (this.isZhanZhang) {

                // test/zhijianke角色：全站、前三名的科室(isImage: true)
                return [
                    { label: '全站', value: (siteAvgAccuracy || 0), isImage: false },
                    { label: this.getObjByRank(brigadeRankingList, 1).name, value: '/static/images/icon/one.png', isImage: true },
                    { label: this.getObjByRank(brigadeRankingList, 2).name, value: '/static/images/icon/two.png', isImage: true },
                    { label: this.getObjByRank(brigadeRankingList, 3).name, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else {
                // 默认角色：检查项、完成率
                return [
                    { label: '检查项', value: '12', isImage: false },
                    { label: '完成率', value: '92%', isImage: false }
                ];
            }
        },
        //根据角色获取查获数据项目组
        getSeizeDataItems() {
            if (this.isIndividualView) {
                // SecurityCheck角色：从securityCheckerData解构
                const { securityCheckerData } = this.seizeData;
                const { selfSeizureCount, teamAverage, departmentAverage, brigadeAverage, stationAverage } = securityCheckerData || {}

                // SecurityCheck角色：本人、班平均、主管平均、站平均
                return [
                    { label: '本人', value: selfSeizureCount || 0, isImage: false },
                    { label: '班平均', value: teamAverage || 0, isImage: false, color: teamAverage < selfSeizureCount ? '#00AE41' : '#F96060' },
                    { label: '主管平均', value: departmentAverage || 0, isImage: false, color: departmentAverage < selfSeizureCount ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: brigadeAverage || 0, isImage: false, color: brigadeAverage < selfSeizureCount ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < selfSeizureCount ? '#00AE41' : '#F96060' }
                ];
            } else if (this.isTeamView) {
                // banzuzhang角色：从teamLeaderData解构
                const { teamLeaderData } = this.seizeData;
                const { departmentAverage, brigadeAverage, stationAverage, teamAverage } = teamLeaderData || {};
                // banzuzhang角色：班组、主管平均、站平均
                return [
                    { label: '班组', value: teamAverage || 0, isImage: false },
                    { label: '主管平均', value: departmentAverage || 0, isImage: false, color: departmentAverage < teamAverage ? '#00AE41' : '#F96060' },
                    { label: '大队平均', value: brigadeAverage || 0, isImage: false, color: brigadeAverage < teamAverage ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < teamAverage ? '#00AE41' : '#F96060' }
                ];
            } else if (this.role.includes('kezhang')) {
                // kezhang角色：从securityCheckerData解构
                const { sectionMasterData } = this.seizeData;
                const { brigadeAverage, departmentAverage, stationAverage } = sectionMasterData || {}

                // kezhang角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '主管', value: departmentAverage || 0, isImage: false },
                    { label: '大队平均', value: brigadeAverage || 0, isImage: false, color: brigadeAverage < departmentAverage ? '#00AE41' : '#F96060' },
                    { label: '站平均', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < departmentAverage ? '#00AE41' : '#F96060' }
                    // { label: this.getObjByRank(topThreeTeams, 1).teamName, value: '/static/images/icon/one.png', isImage: true },
                    // { label: this.getObjByRank(topThreeTeams, 2).teamName, value: '/static/images/icon/two.png', isImage: true },
                    // { label: this.getObjByRank(topThreeTeams, 3).teamName, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else if (this.isBrigade) {
                // brigade角色：从securityCheckerData解构
                const { brigadeMasterData } = this.seizeData;
                const { stationAverage, topThreeDepartment, brigadeAverage } = brigadeMasterData || {}

                // brigade角色：主管、站平均、前三名班组(isImage: true)
                return [
                    { label: '大队', value: brigadeAverage || 0, isImage: false },
                    { label: '站平均', value: (stationAverage && stationAverage.toFixed(2)) || 0, isImage: false, color: stationAverage < brigadeAverage ? '#00AE41' : '#F96060' },
                    { label: this.getObjByRank(topThreeDepartment, 1).departmentName, value: '/static/images/icon/one.png', isImage: true },
                    { label: this.getObjByRank(topThreeDepartment, 2).departmentName, value: '/static/images/icon/two.png', isImage: true },
                    { label: this.getObjByRank(topThreeDepartment, 3).departmentName, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else if (this.isZhanZhang) {
                // test/zhijianke角色：从securityCheckerData解构
                const { stationMasterData } = this.seizeData;
                const { totalStationSeizure, brigadeRankings } = stationMasterData || {}

                // 对departmentRankings数组按照seizureCount由大到小排序
                const sortedBrigadeRankings = Array.isArray(brigadeRankings)
                    ? [...brigadeRankings].sort((a, b) => (b.seizureCount || 0) - (a.seizureCount || 0))
                    : [];

                if (sortedBrigadeRankings.length == 0) {
                    return []
                }
                // test/zhijianke角色：全站、前三名的科室(isImage: true)
                return [
                    { label: '全站', value: totalStationSeizure || 0, isImage: false },
                    { label: sortedBrigadeRankings[0].brigadeName, value: '/static/images/icon/one.png', isImage: true },
                    { label: sortedBrigadeRankings[1].brigadeName, value: '/static/images/icon/two.png', isImage: true },
                    { label: sortedBrigadeRankings[2].brigadeName, value: '/static/images/icon/three.png', isImage: true }
                ];
            } else {
                // 默认角色：检查项、完成率
                return [
                    { label: '检查项', value: '12', isImage: false },
                    { label: '完成率', value: '92%', isImage: false }
                ];
            }
        },
        getObjByRank(arr, rank) {
            if (!Array.isArray(arr)) return {}
            let res = arr.find(item => item.rank == rank)
            return res || {}
        },

        // 根据角色获取巡检排名列表
        getRankList() {
            const { teamRanking, teamTotal, departmentRanking, departmentTotal, stationRanking, stationTotal, brigadeTotal, brigadeRanking } = this.inspectionData;
            // 根据角色返回不同的排名数据
            if (this.isIndividualView) {
                // 科长、SecurityCheck角色：显示班组、科级和站级排名
                return [
                    { label: '班组排名', current: teamRanking || 0, total: teamTotal || 0, percentage: teamTotal ? ((teamRanking || 0) / teamTotal) * 100 : 0 },
                    { label: '主管排名', current: departmentRanking || 0, total: departmentTotal || 0, percentage: departmentTotal ? ((departmentRanking || 0) / departmentTotal) * 100 : 0 },
                    { label: '大队排名', current: brigadeRanking || 0, total: brigadeTotal || 0, percentage: brigadeTotal ? ((brigadeRanking || 0) / brigadeTotal) * 100 : 0 },
                    { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
                ];
            } else if (this.role.includes('kezhang')) {
                return [
                    { label: '大队排名', current: brigadeRanking || 0, total: brigadeTotal || 0, percentage: brigadeTotal ? ((brigadeRanking || 0) / brigadeTotal) * 100 : 0 },
                    { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
                ];
            } else if (this.isBrigade) {
                return [

                    { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
                ];
            } else if (this.isTeamView) {
                // 班组长角色：显示科级和站级排名
                return [
                    { label: '主管排名', current: departmentRanking || 0, total: departmentTotal || 0, percentage: departmentTotal ? ((departmentRanking || 0) / departmentTotal) * 100 : 0 },
                    { label: '大队排名', current: departmentRanking || 0, total: departmentTotal || 0, percentage: departmentTotal ? ((departmentRanking || 0) / departmentTotal) * 100 : 0 },
                    { label: '站级排名', current: stationRanking || 0, total: stationTotal || 0, percentage: stationTotal ? ((stationRanking || 0) / stationTotal) * 100 : 0, type: 'station' }
                ];
            } else {
                // 默认角色：显示个人排名
                return [];
            }
        },
        //获取抽问抽答排名
        getQuestionRankList() {
            // 根据角色返回不同的排名数据
            if (this.isIndividualView) {
                const { teamRanking, deptRanking, siteRanking } = this.accuracyStatistics;
                // 科长、SecurityCheck角色：显示班组、科级和站级排名
                return [
                    { label: '班组排名', current: teamRanking?.rank || 0, total: teamRanking?.total || 0, percentage: teamRanking?.total ? ((teamRanking.rank || 0) / teamRanking.total) * 100 : 0 },
                    { label: '主管排名', current: deptRanking?.rank || 0, total: deptRanking?.total || 0, percentage: deptRanking?.total ? ((deptRanking.rank || 0) / deptRanking.total) * 100 : 0 },
                    { label: '大队排名', current: deptRanking?.rank || 0, total: deptRanking?.total || 0, percentage: deptRanking?.total ? ((deptRanking.rank || 0) / deptRanking.total) * 100 : 0 },
                    { label: '站级排名', current: siteRanking?.rank || 0, total: siteRanking?.total || 0, percentage: siteRanking?.total ? ((siteRanking.rank || 0) / siteRanking.total) * 100 : 0, type: 'station' }
                ];
            } else if (this.role.includes('kezhang')) {
                const { deptInSiteRanking, deptInBrigadeRanking } = this.accuracyStatistics;
                return [
                    { label: '大队排名', current: deptInBrigadeRanking?.rank || 0, total: deptInBrigadeRanking?.total || 0, percentage: deptInBrigadeRanking?.total ? ((deptInBrigadeRanking.rank || 0) / deptInBrigadeRanking.total) * 100 : 0 },
                    { label: '站级排名', current: deptInSiteRanking?.rank || 0, total: deptInSiteRanking?.total || 0, percentage: deptInSiteRanking?.total ? ((deptInSiteRanking?.rank || 0) / deptInSiteRanking?.total) * 100 : 0, type: 'station' }
                ];
            } else if (this.isBrigade) {
                const { brigadeInSiteRanking } = this.accuracyStatistics;
                return [
                    { label: '站级排名', current: brigadeInSiteRanking?.rank || 0, total: brigadeInSiteRanking?.total || 0, percentage: brigadeInSiteRanking?.total ? ((brigadeInSiteRanking?.rank || 0) / brigadeInSiteRanking?.total) * 100 : 0, type: 'station' }
                ];
            } else if (this.isTeamView) {
                const { teamInDeptRanking, deptRanking, teamInSiteRanking, teamInBrigadeRanking } = this.accuracyStatistics;
                // 班组长角色：显示科级和站级排名
                return [
                    { label: '主管排名', current: teamInDeptRanking?.rank || 0, total: teamInDeptRanking?.total || 0, percentage: teamInDeptRanking?.total ? ((teamInDeptRanking.rank || 0) / teamInDeptRanking.total) * 100 : 0 },
                    { label: '大队排名', current: teamInBrigadeRanking?.rank || 0, total: teamInBrigadeRanking?.total || 0, percentage: teamInBrigadeRanking?.total ? ((teamInBrigadeRanking.rank || 0) / teamInBrigadeRanking.total) * 100 : 0 },
                    { label: '站级排名', current: teamInSiteRanking?.rank || 0, total: teamInSiteRanking?.total || 0, percentage: teamInSiteRanking?.total ? ((teamInSiteRanking.rank || 0) / teamInSiteRanking.total) * 100 : 0, type: 'station' }
                ];
            } else {
                // 默认角色：显示个人排名
                return [];
            }
        },
        // 根据角色获取巡检排名列表
        getSeizeRankList() {
            // 根据角色返回不同的排名数据
            if (this.isIndividualView) {
                const { securityCheckerData } = this.seizeData;
                const { teamRanking, departmentRanking, stationRanking, brigadeRanking } = securityCheckerData || {}
                // 科长、SecurityCheck角色：显示班组、科级和站级排名
                return [
                    { label: '班组排名', current: teamRanking?.currentRank || 0, total: teamRanking?.totalItems || 0, percentage: teamRanking?.totalItems ? ((teamRanking.currentRank || 0) / teamRanking.totalItems) * 100 : 0 },
                    { label: '主管排名', current: departmentRanking?.currentRank || 0, total: departmentRanking?.totalItems || 0, percentage: departmentRanking?.totalItems ? ((departmentRanking.currentRank || 0) / departmentRanking.totalItems) * 100 : 0 },
                    { label: '大队排名', current: brigadeRanking?.currentRank || 0, total: brigadeRanking?.totalItems || 0, percentage: brigadeRanking?.totalItems ? ((brigadeRanking.currentRank || 0) / brigadeRanking.totalItems) * 100 : 0 },
                    { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
                ];
            } else if (this.role.includes('kezhang')) {
                const { sectionMasterData } = this.seizeData;
                const { stationRanking, departmentRanking, brigadeRanking } = sectionMasterData || {};
                // 科长、SecurityCheck角色：显示班组、科级和站级排名
                return [
                    { label: '大队排名', current: brigadeRanking?.currentRank || 0, total: brigadeRanking?.totalItems || 0, percentage: brigadeRanking?.totalItems ? ((brigadeRanking.currentRank || 0) / brigadeRanking.totalItems) * 100 : 0 },
                    { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
                ];
            } else if (this.isBrigade) {
                const { brigadeMasterData } = this.seizeData;
                const { stationRanking } = brigadeMasterData || {};
                // brigade角色：显示站级排名
                return [

                    { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
                ];
            } else if (this.isTeamView) {
                const { teamLeaderData } = this.seizeData;
                const { departmentRanking, stationRanking, brigadeRanking } = teamLeaderData || {}
                // 班组长角色：显示科级和站级排名
                return [
                    { label: '主管排名', current: departmentRanking?.currentRank || 0, total: departmentRanking?.totalItems || 0, percentage: departmentRanking?.totalItems ? ((departmentRanking.currentRank || 0) / departmentRanking.totalItems) * 100 : 0 },
                    { label: '大队排名', current: brigadeRanking?.currentRank || 0, total: brigadeRanking?.totalItems || 0, percentage: brigadeRanking?.totalItems ? ((brigadeRanking.currentRank || 0) / brigadeRanking.totalItems) * 100 : 0 },
                    { label: '站级排名', current: stationRanking?.currentRank || 0, total: stationRanking?.totalItems || 0, percentage: stationRanking?.totalItems ? ((stationRanking.currentRank || 0) / stationRanking.totalItems) * 100 : 0, type: 'station' }
                ];
            } else {
                // 默认角色：显示个人排名
                return [];
            }
        },
        goworkDocu() {
            uni.navigateTo({
                url: '/pages/workDocu/index'
            });
        },
        async getUnreadCount() {
            const res = await getUnreadCount();
            this.unreadCount = res.data
        },
        async getUser() {
            const data = await getUserProfile();
            console.log("data====", data)
            //data.postGroup + "  " +
            this.userInfo = data.data.dept.deptName
            await this.loadAppList(data.data);
            // this.formData.securityLocationText = data.data.dept.deptName
            // this.formData.positionText = data.postGroup
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const week = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()];
            return `${year}年${month}月${day}日 星期${week}`;
        },
        updateCurrentDate() {
            this.currentDate = this.formatDate(new Date());
        },
        handleGridClick(item) {
            console.log('点击了宫格：', item);
            if (item.path) {
                uni.navigateTo({
                    url: item.path
                });
            } else {
                this.$modal.showToast('功能开发中，敬请期待');
            }
        },
        goToAttendance() {
            uni.navigateTo({
                url: '/pages/attendance/index'
            });
        },
        changeGrid(e) {
            const index = e.detail.index;
            const item = this.items[index];
            this.handleGridClick(item);
        },
        goToPage(path) {
            // if (checkRolePermission(this.role, path)) {
            uni.navigateTo({ url: path });
            // } else {
            //   this.$modal.showToast('此角色不需要查看该功能，无需操作～');
            // }
        },
        async loadAppList(userInfo) {
            // const roleId = userInfo.roles && userInfo.roles.length ? userInfo.roles[0].roleId : null;

            try {
                // if (roleId) {
                const res = await getAppList({ homePage: 1 });
                if (res.code === 200) {

                    this.appList = res.data;
                }
                // }
            } catch (error) {
                console.error('获取应用列表失败:', error);
                this.appList = [];
            }
        },



        async loadTodayRecord() {
            if (this.yesterday) {
                return;
            }
            const today = this.formatDate(new Date());
            const { data } = await getAttendanceList({
                type: 1,
                checkInDate: today,
                userId: this.$store.state.user.id
            });

            // 接口 data 可能是多条（按天），我们取第一条里的 items
            const todayData = data && data.length ? data[0] : null;
            const items = todayData ? todayData.items : [];
            const lastMorning = items.find(r => r.checkInType == 'CLOCK_IN');
            if (lastMorning) {
                console.log(lastMorning);
                this.todayCheckInTime = '已打卡  ' + lastMorning.checkInTime

            } else {

            }


        },
        // 日期格式化（昨天、今天查询用）
        formatDate(date) {
            const y = date.getFullYear();
            const m = String(date.getMonth() + 1).padStart(2, '0');
            const d = String(date.getDate()).padStart(2, '0');
            return `${y}-${m}-${d}`;
        },

        // 获取今日上岗科长信息
        async getTodayOnDutyKeZhang() {
            return new Promise((resolve, reject) => {
                // 只有当角色包含test时才调用此接口
                if (!this.isZhanZhang) {
                    resolve(null);
                    return;
                }

                // 调用接口获取今日上岗科长列表
                selectUserListByRoleKey(["kezhang"]).then(res => {
                    if (res.code === 200 && res.data && res.data.length > 0) {
                        this.subTitleText = res.data && res.data.map(user => user.nickName).join('、');
                        resolve(res.data);
                    } else {
                        this.subTitleText = '';
                        resolve(null);
                    }
                }).catch(error => {
                    console.error("获取今日上岗科长信息失败:", error);
                    this.subTitleText = '';
                    reject(error);
                });
            });
        },
    }
}
</script>

<style lang="scss" scoped>
img {
    display: inline-flex;
}

.title {
    padding: 34rpx 34rpx 34rpx;
    height: auto;
    border-radius: 0 0 20rpx 20rpx;
    background: linear-gradient(136deg, #8FA5EC 0%, #978CED 99.29%);
    transition: all 0.3s ease;
}



.content {
    padding: 34rpx 34rpx 34rpx;
}

::v-deep .userInfo {
    .user-info {
        font-size: 34rpx;
        background-size: auto 90%;
        padding: 4rpx 0 4rpx 100rpx;
        background-position: 0rpx 6rpx;
    }
}

/* 角色选择器样式 */
.role-selector {
    margin-bottom: 10rpx;
}





/* 排名容器样式 */
.rank-container {
    display: flex;
    justify-content: flex-start;
    margin: 0 0 34rpx 0;
}

.rank-item {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20rpx;
    padding: 10rpx 20rpx;
    margin-right: 13rpx;
}

.rank-content {
    text-align: center;
    display: flex;
    align-items: center;
    font-size: 22rpx;
    color: #fff;
}

.rank-value {
    margin: 0 10rpx;
    line-height: 24rpx;
}

.rank-label {
    line-height: 24rpx;
}

.rank-image {
    width: 24rpx;
    height: 24rpx;
    border-radius: 8rpx;
}

/* 出勤信息容器样式 */
.attendance-container {
    margin-top: 20rpx;
}

.attendance-grid {
    background: rgba(255, 255, 255, 0.15);
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0;
    border-radius: 20rpx;
    position: relative;
}

.attendance-item {
    padding: 24rpx 16rpx;
    text-align: center;
    position: relative;
}

/* 为每个attendance-item添加右侧竖线分隔线 */
.attendance-item:not(:nth-child(3n))::after {
    content: '';
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 1rpx;
    height: 50%;
    background: rgba(255, 255, 255, 0.5);
}

.item-value {
    line-height: 1;
    font-size: 32rpx;
    font-weight: bold;
    color: #FFFFFF;
    margin-top: 13rpx;
}

.item-label {
    font-size: 25rpx;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.6);
    opacity: 0.6;
}



/* 时间范围选择样式 */
.time-range-section {
    margin: 15rpx 0;
    padding: 0 0rpx;
}

.time-range-container {
    display: flex;
    align-items: flex-start;
    gap: 20rpx;
}

.time-range-label {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    line-height: 60rpx;
    flex-shrink: 0;
}

.time-tags-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    flex: 1;
}

.time-tag {
    margin-left: 4rpx;
    padding: 7rpx 15rpx;
    background: #fff;
    border-radius: 20rpx;
    font-size: 24rpx;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2rpx solid transparent;
    white-space: nowrap;
    flex-shrink: 0;
}

.time-tag.active {
    background: #8FA5EC;
    color: #fff;
    border-color: #8FA5EC;
}


/* 时间范围标签样式 - 作为普通文字显示 */
.time-tag.time-range-label {
    background: transparent !important;
    border: none !important;
    padding: 0 !important;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
    cursor: default !important;
    pointer-events: none;
    margin-right: 0;
}

.time-tag.time-range-label:hover {
    background: transparent !important;
    border: none !important;
}

/* 内联自定义时间显示样式 */
.custom-time-inline {
    position: relative;
    display: flex;
    align-items: center;
    gap: 12rpx;
    margin-left: 15rpx;
    flex-wrap: wrap;
    // width: 350rpx;
}

.date-range-picker {
    ::v-deep .icon-calendar {
        display: none !important;
    }

    ::v-deep .uni-date-range {
        font-size: 16rpx !important;
        background: transparent !important;
        color: black !important;
    }

    ::v-deep .uni-date-x {
        height: 25rpx !important;
        line-height: 25rpx !important;
        min-width: auto !important;

        .range-separator {
            font-size: 23rpx !important;
            padding: 0 8rpx !important;
            margin: 0 !important;
        }

        .uni-date__x-input {
            width: auto !important;
            min-width: auto !important;
            height: 25rpx !important;
            line-height: 25rpx !important;
            padding: 0 !important;
            margin: 0 !important;
        }
    }

    ::v-deep .uni-date-x--border {
        border: none !important;
        padding: 0 !important;
        margin: 0 !important;
    }
}

.days-count {
    // position: absolute;
    // right: -102rpx;
    // top: -8rpx;
    height: 25rpx;
    line-height: 25rpx;
    font-size: 27rpx;
    color: black;
    font-weight: 500;
    white-space: nowrap;
}



.speret {
    font-size: 26rpx;
    color: #999;
}
</style>
