<template>
    <HomeContainer :customStyle="{ background: 'none', padding: '0' }">
        <div class="title">
            <view class="depart-name">{{ departmentName }}</view>

            <!-- 排名区块 -->
            <view class="rank-container" v-if="!role.includes('test') && !role.includes('zhijianke')">
                <view v-for="(item, index) in rankItems" :key="index" class="rank-item">
                    <view class="rank-content">
                        <view class="rank-label">{{ item.label }}</view>
                        <view class="rank-value">{{ item.value }}</view>
                        <image :src="item.iconSrc" class="rank-image" />
                    </view>
                </view>
            </view>

            <!-- 选择区块 -->
            <view class="time-selector-container">
                <view class="time-selector-item" @click="toggleTimeDisplay">
                    <view class="time-label">{{ selectedTimeDisplay || '选择时间' }}</view>
                    <view class="time-arrow">▼</view>
                </view>
                <view class="time-selector-item" @click="openOrganizationPopup1">
                    <view class="time-label">{{ selectedOrganization1Display || '选择组织架构1' }}</view>
                    <view class="time-arrow">▼</view>
                </view>
                <view class="time-selector-item" @click="openOrganizationPopup2">
                    <view class="time-label">{{ selectedOrganization2Display || '选择组织架构2' }}</view>
                    <view class="time-arrow">▼</view>
                </view>
            </view>

            <!-- 时间标签显示区域 -->
            <view v-if="showTimeDisplay" class="time-range-display">
                <view class="time-tags">
                    <view v-for="tag in timeTags" :key="tag.value" class="time-tag"
                        :class="{ active: selectedTimeRange === tag.value }" @click="handleTimeTagClick(tag.value)">
                        <text v-if="selectedTimeRange === tag.value" class="checkmark">✓</text>
                        {{ tag.label }}
                    </view>
                </view>

                <!-- 自定义时间选择器 -->
                <view v-if="selectedTimeRange=='custom'" class="time-picker-container">
                    <view class="time-picker">
                        <view class="date-range">
                            <uni-datetime-picker type="date" v-model="startDate" class="date-input-field"
                                placeholder="开始时间" />
                            <span class="speret">~</span>
                            <uni-datetime-picker type="date" v-model="endDate" class="date-input-field"
                                placeholder="结束时间" />
                        </view>
                        <view class="picker-buttons">
                            <button class="btn-cancel" @click="cancelTimePicker">重置</button>
                            <button class="btn-confirm" @click="confirmTimePicker">确定</button>
                        </view>
                    </view>
                </view>
            </view>
        </div>

        <!-- 雷达图区域 -->
        <div class="capability-content">
            <div class="chart-section">
                <div class="chart-container">
                    <div id="radar-chart" class="radar-chart"></div>
                </div>
            </div>

            <!-- 数据展示区域 -->
            <div class="data-section">
                <div v-for="(item, index) in dataItems" :key="index" class="data-item">
                    <div class="item-title">{{ item.title }}</div>
                    <div class="data-content-section">
                        <div class="data-content" v-for="ele in item.list">
                            <div class="data-value">{{ ele.value }}</div>
                            <div class="data-label">{{ ele.label }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>



        <!-- 组织架构选择弹窗1 -->
        <uni-popup ref="organizationPopup1" type="center" :mask-click="false">
            <view class="popup-container">
                <view class="popup-header">
                    <text class="popup-title">选择组织架构1</text>
                    <view class="popup-close" @click="closeOrganizationPopup1">×</view>
                </view>

                <!-- 搜索框 -->
                <view class="search-section">
                    <uni-easyinput v-model="searchKeyword1" placeholder="请输入部门或人员名称搜索" :clearable="true" />
                </view>

                <!-- 组织架构树 -->
                <view class="tree-section">
                    <scroll-view scroll-y="true" class="tree-scroll">
                        <mix-tree :list="filteredTreeData1" :expandAll="!!searchKeyword1"
                            @treeItemClick="handleOrganizationSelect1" />
                    </scroll-view>
                </view>

                <!-- 按钮区域 -->
                <view class="button-section">
                    <view class="btn-cancel" @click="closeOrganizationPopup1">取消</view>
                    <view class="btn-confirm" @click="confirmOrganizationSelection1">确定</view>
                </view>
            </view>
        </uni-popup>

        <!-- 组织架构选择弹窗2 -->
        <uni-popup ref="organizationPopup2" type="center" :mask-click="false">
            <view class="popup-container">
                <view class="popup-header">
                    <text class="popup-title">选择组织架构</text>
                    <view class="popup-close" @click="closeOrganizationPopup2">×</view>
                </view>

                <!-- 搜索框 -->
                <view class="search-section">
                    <uni-easyinput v-model="searchKeyword2" placeholder="请输入部门或人员名称搜索" :clearable="true" />
                </view>

                <!-- 组织架构树 -->
                <view class="tree-section">
                    <scroll-view scroll-y="true" class="tree-scroll">
                        <mix-tree :list="filteredTreeData2" :expandAll="!!searchKeyword2"
                            @treeItemClick="handleOrganizationSelect2" />
                    </scroll-view>
                </view>

                <!-- 按钮区域 -->
                <view class="button-section">
                    <view class="btn-cancel" @click="closeOrganizationPopup2">取消</view>
                    <view class="btn-confirm" @click="confirmOrganizationSelection2">确定</view>
                </view>
            </view>
        </uni-popup>
    </HomeContainer>
</template>

<script>
import HomeContainer from '@/components/HomeContainer.vue'
import * as echarts from 'echarts'
import mixTree from '@/uni_modules/mix-tree/components/mix-tree/mix-tree.vue'
import { getDeptUserTree } from '@/api/system/user'
import uniDatetimePicker from '@/uni_modules/uni-datetime-picker/components/uni-datetime-picker/uni-datetime-picker.vue'
import { getUserProfile } from "@/api/system/user";
import { getSeizureRanking, getCheckRanking, getAccuracyStatistics, getHomePageDetail } from "@/api/home-new/home-new";

export default {
    components: {
        HomeContainer,
        mixTree,
        uniDatetimePicker
    },
    data() {
        return {
            chart: null,
            departmentName: '班组名称/旅检一科', // 部门名称，用于动态显示
            dataItems: [

            ],
            // 排名数据
            rankData: {
                seizeRank: 0,
                seizeModalType: 0,
                answerRank: 0,
                answerModalType: 0,
                checkRank: 0,
                checkModalType: 0
            },
            // 时间选择相关数据
            showTimeDisplay: false,
            showTimePicker: false,
            startDate: '',
            endDate: '',
            selectedTimeRange: 'week',
            timeTags: [
                { label: '近一周', value: 'week' },
                { label: '近一月', value: 'month' },
                { label: '近三月', value: 'quarter' },
                { label: '近半年', value: 'halfYear' },
                { label: '近一年', value: 'year' },
                { label: '自定义时间', value: 'custom' }
            ],
            // 组织架构选择相关数据

            showOrganizationPopup2: false,
            organizationTree1: [],
            organizationTree2: [],
            selectedOrganization1: null,
            selectedOrganization2: null,
            searchKeyword1: '',
            searchKeyword2: '',
            // 回显显示文本
            selectedTimeDisplay: '',
            selectedOrganization1Display: '',
            selectedOrganization1Id: '',
            selectedOrganization2Display: ''
        }
    },
    computed: {
        currentUser() {
            return this.$store.state.user.userInfo
        },
        role() {
            return this.$store?.state?.user?.roles
        },
        // 排名项数组
        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)
                }
            ];
        },
        // 过滤后的组织架构树数据1
        filteredTreeData1() {
            if (!this.searchKeyword1) {
                return this.organizationTree1.map(node => ({
                    ...node,
                    showChild: true
                }));
            }
            const filterTree = (nodes) => {
                if (!nodes || !Array.isArray(nodes)) {
                    return [];
                }
                return nodes.filter(node => {
                    const matches = node.label && node.label.toLowerCase().includes(this.searchKeyword1.toLowerCase());
                    if (node.children && node.children.length > 0) {
                        const filteredChildren = filterTree(node.children);
                        return matches || filteredChildren.length > 0;
                    }
                    return matches;
                }).map(node => ({
                    ...node,
                    children: node.children && node.children.length > 0 ? filterTree(node.children) : undefined
                }));
            };
            return filterTree(this.organizationTree1);
        },

        // 过滤后的组织架构树数据2
        filteredTreeData2() {
            console.log('this.organizationTree2', this.currentUser)
            if (!this.searchKeyword2) {
                return this.organizationTree2.map(node => ({
                    ...node,
                    showChild: true
                }));
            }
            const filterTree = (nodes) => {
                if (!nodes || !Array.isArray(nodes)) {
                    return [];
                }
                return nodes.filter(node => {
                    const matches = node.label && node.label.toLowerCase().includes(this.searchKeyword2.toLowerCase());
                    if (node.children && node.children.length > 0) {
                        const filteredChildren = filterTree(node.children);
                        return matches || filteredChildren.length > 0;
                    }
                    return matches;
                }).map(node => ({
                    ...node,
                    children: node.children && node.children.length > 0 ? filterTree(node.children) : undefined
                }));
            };
            return filterTree(this.organizationTree2);
        }
    },

    onShow() {
        this.getUser();
        this.checkUrlParams(); // 先处理URL参数
        this.loadRankData();
        this.loadOrganizationTree1();
        this.loadOrganizationTree2();
        this.getHomePageDetailData(); // 然后加载数据
    },

    mounted() {
        // 数据加载移到onShow中，确保URL参数先被处理
    },

    beforeDestroy() {
        if (this.chart) {
            this.chart.dispose();
        }
    },

    methods: {
        //获取数据
        getHomePageDetailData() {


            // 如果使用预设时间范围，计算日期
            const dateRange = this.calculateDateRange(this.selectedTimeRange);
            let startDate = dateRange.startDate;
            let endDate = dateRange.endDate;
            

            // 构建参数数组
            let params = [
                {
                    startDate: startDate,
                    endDate: endDate,
                    type: this.selectedOrganization1Type,
                    id: this.selectedOrganization1Id,
                    name: this.selectedOrganization1Display
                }
            ];

            // 如果选择了组织架构2，添加第二个参数
            if (this.selectedOrganization2) {
                params.push({
                    startDate: startDate,
                    endDate: endDate,
                    type: this.selectedOrganization2.nodeType == 'dept' ? 'DEPT' : 'USER',
                    id: this.selectedOrganization2.id,
                    name: this.selectedOrganization2.name
                });
            }

            console.log('请求参数:', params);

            getHomePageDetail(params).then(res => {
                console.log("接口响应:", res);
                // 处理响应数据，更新图表和数据显示
                this.handleHomePageDetailResponse(res);
            }).catch(error => {
                console.error("获取首页详情数据失败:", error);
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none'
                });
            });
        },

        handleResize() {
            if (this.chart) {
                this.chart.resize();
            }
        },
        // 获取用户信息
        async getUser() {
            try {
                const res = await getUserProfile();
                this.userInfo = res.data;
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        },
        // 获取排名数据
        getRank() {
            return new Promise((resolve, reject) => {
                let params = {};
                // 优先使用URL参数中的时间，如果没有则根据时间范围计算
                let startDate = this.startDate;
                let endDate = this.endDate;

                if (!startDate || !endDate) {
                    const dateRange = this.calculateDateRange(this.selectedTimeRange);
                    startDate = dateRange.startDate;
                    endDate = dateRange.endDate;
                }

                params.startDate = startDate;
                params.endDate = endDate;


                let idObj = {}
                if (this.role.includes('SecurityCheck')) {
                    idObj = { userId: this.currentUser.userId }
                } else {
                    idObj = { deptId: this.currentUser.deptId }
                }

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

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

                // 使用Promise.all并行执行API请求
                Promise.all(apiRequests).then((results) => {
                    const [seizureRes] = results;
                    let checkRes = null;

                    // 处理查获排名数据
                    const { data: seizureData } = seizureRes || {};
                    this.rankData.seizeRank = seizureData[0]?.rank;
                    this.rankData.seizeModalType = seizureData[0]?.medalType;
                    // 如果有检查排名数据，处理检查排名数据
                    if (results.length > 1) {
                        const { data: checkData } = results[1];
                        const { checkLargeScreenHomePageRankingDto, dailyTaskAccuracyRankingDto } = checkData;

                        this.rankData.checkRank = checkLargeScreenHomePageRankingDto.rank;
                        this.rankData.checkModalType = checkLargeScreenHomePageRankingDto.medalType;
                        this.rankData.answerRank = dailyTaskAccuracyRankingDto.rank;
                        this.rankData.answerModalType = dailyTaskAccuracyRankingDto.medalType;

                    }

                    resolve({
                        seizureData: seizureRes.data,
                        checkData: checkRes ? checkRes.data : null
                    });
                }).catch(error => {
                    console.error("获取排名数据失败:", error);
                    reject(error);
                });
            });
        },

        // 获取准确率统计数据
        getAccuracy() {
            return new Promise((resolve, reject) => {
                let params = {}
                // 优先使用URL参数中的时间，如果没有则根据时间范围计算
                let startDate = this.startDate;
                let endDate = this.endDate;

                if (!startDate || !endDate) {
                    const dateRange = this.calculateDateRange(this.selectedTimeRange);
                    startDate = dateRange.startDate;
                    endDate = dateRange.endDate;
                }

                params.startDate = startDate;
                params.endDate = endDate;
                getAccuracyStatistics(params).then(res => {
                    console.log("准确率统计数据:", res)
                    const { data } = res;
                    const { deptInSiteRanking } = data;
                    this.rankData.answerRank = deptInSiteRanking?.rank || 0;
                    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)
            };
        },

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

        // 加载排名数据
        loadRankData() {
            // 使用真实的API数据
            Promise.all([
                this.getRank(),
                this.getAccuracy()
            ]).then(() => {
                console.log('排名数据加载完成');
            }).catch(error => {
                console.error('加载排名数据失败:', error);
            });
        },
        // 根据排名类型和排名值获取图片路径
        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';
            }
        },
        // 时间选择相关方法
        toggleTimeDisplay() {
            this.showTimeDisplay = !this.showTimeDisplay;
            if (!this.showTimeDisplay) {
                this.showTimePicker = false;
            }
        },
        handleTimeTagClick(value) {
            this.selectedTimeRange = value;
            // 设置时间选择回显
            const selectedTag = this.timeTags.find(tag => tag.value === value);
            this.selectedTimeDisplay = selectedTag ? selectedTag.label : '选择时间';

            if (value === 'custom') {
                this.showTimePicker = true;
            } else {
                this.showTimePicker = false;
                this.showTimeDisplay = false; // 选择预设时间后隐藏时间选择区域
                this.loadDataByTimeRange(value);
                // 选择时间后请求数据
                this.getHomePageDetailData();
            }
        },
        cancelTimePicker() {
            this.showTimePicker = false;
            this.startDate = '';
            this.endDate = '';
        },
        confirmTimePicker() {
            if (!this.startDate || !this.endDate) {
                uni.showToast({
                    title: '请选择完整的时间范围',
                    icon: 'none'
                });
                return;
            }
            this.showTimePicker = false;
            this.showTimeDisplay = false; // 选择完成后隐藏时间选择区域
            // 设置自定义时间回显
            this.selectedTimeDisplay = `${this.startDate} ~ ${this.endDate}`;
            this.loadDataByCustomTime(this.startDate, this.endDate);
            // 选择自定义时间后请求数据
            this.getHomePageDetailData();
        },
        loadDataByTimeRange(range) {
            console.log('加载时间范围数据:', range);
            // 根据时间范围加载数据
        },
        loadDataByCustomTime(startDate, endDate) {
            console.log('加载自定义时间数据:', startDate, endDate);
            // 根据自定义时间加载数据
        },


        openOrganizationPopup2() {
            this.$refs.organizationPopup2.open();
            this.searchKeyword2 = '';
            // this.selectedOrganization2 = null;
            this.loadOrganizationTree2();
        },


        closeOrganizationPopup2() {
            this.$refs.organizationPopup2.close();
            this.searchKeyword2 = '';
            // this.selectedOrganization2 = null;
        },



        handleOrganizationSelect2(item) {
            this.selectedOrganization2 = item;
        },



        confirmOrganizationSelection2() {
            if (this.selectedOrganization2) {
                console.log('选择的组织架构2:', this.selectedOrganization2);
                // 设置组织架构2回显

                this.selectedOrganization2Display = this.selectedOrganization2.label;
                this.loadDataByOrganization2(this.selectedOrganization2);
                // 选择组织架构2后请求数据
                this.getHomePageDetailData();
            } else {
                this.selectedOrganization2Display = '选择组织架构2';
            }
            this.closeOrganizationPopup2();
        },

        // 组织架构1相关方法
        openOrganizationPopup1() {
            this.$refs.organizationPopup1.open();
            this.searchKeyword1 = '';
            this.selectedOrganization1 = null;
            this.loadOrganizationTree1();
        },

        closeOrganizationPopup1() {
            this.$refs.organizationPopup1.close();
            this.searchKeyword1 = '';
            this.selectedOrganization1 = null;
        },

        handleOrganizationSelect1(item) {
            this.selectedOrganization1 = item;
        },

        confirmOrganizationSelection1() {
            if (this.selectedOrganization1) {
                console.log('选择的组织架构1:', this.selectedOrganization1);
                // 设置组织架构1回显
                this.selectedOrganization1Display = this.selectedOrganization1.label;
                this.selectedOrganization1Id = this.selectedOrganization1.id;
                this.selectedOrganization1Type = this.selectedOrganization1.nodeType === 'dept' ? 'DEPT' : 'USER';

                // 选择组织架构1后请求数据
                this.getHomePageDetailData();
            } else {
                this.selectedOrganization1Display = '选择组织架构1';
                this.selectedOrganization1Id = '';
                this.selectedOrganization1Type = '';
            }
            this.closeOrganizationPopup1();
        },


        // 加载组织架构树数据1
        async loadOrganizationTree1() {
            try {
                const res = await getDeptUserTree({});
                // 根据currentUser中的stationId、departmentId、teamsId筛选树状图数据
                this.organizationTree1 = this.filterTreeByUserIds(res.data);
            } catch (error) {
                console.error('加载组织架构树1失败:', error);
                uni.showToast({
                    title: '加载组织架构失败',
                    icon: 'none'
                });
            }
        },

        // 加载组织架构树数据2
        async loadOrganizationTree2() {
            try {
                const res = await getDeptUserTree({});
                this.organizationTree2 = this.filterTreeByUserIds(res.data);
            } catch (error) {
                console.error('加载组织架构树2失败:', error);
                uni.showToast({
                    title: '加载组织架构失败',
                    icon: 'none'
                });
            }
        },

        // 根据用户ID筛选树状图数据
        filterTreeByUserIds(treeData) {
            if (!treeData || !Array.isArray(treeData)) {
                return [];
            }
            console.log(this.currentUser, "this.currentUser")
            // 获取当前用户的stationId、departmentId、teamsId
            const stationId = this.currentUser?.stationId;
            const departmentId = this.currentUser?.departmentId;
            const teamsId = this.currentUser?.teamsId; // teamsId不可能是数组

            // 收集所有需要查找的ID，最后一个是最小一级
            const allowedIds = [stationId, departmentId, teamsId].filter(id => id != null && id !== '');

            // 如果没有需要查找的ID，返回空数组
            if (allowedIds.length === 0) {
                return [];
            }

            // 递归查找所有符合条件的节点
            const findMatchingNodes = (nodes, targetIds) => {
                if (!nodes || !Array.isArray(nodes)) {
                    return [];
                }

                const result = [];

                for (const node of nodes) {
                    const nodeId = node.id || node.value;

                    // 如果当前节点ID在目标ID列表中
                    if (targetIds.includes(nodeId)) {
                        // 判断是否是最小一级（最后一个ID）
                        const isMinLevel = targetIds.indexOf(nodeId) === targetIds.length - 1;

                        // 复制当前节点
                        const matchedNode = {
                            ...node,
                            children: undefined
                        };

                        // 如果是最小一级，保留所有children
                        if (isMinLevel) {

                            matchedNode.children = node.children;
                        } else {
                            // 如果不是最小一级，继续在children中查找
                            matchedNode.children = node.children && node.children.length > 0 ?
                                findMatchingNodes(node.children, targetIds) : undefined;
                        }

                        result.push(matchedNode);
                    } else {
                        // 如果当前节点不匹配，继续在children中查找
                        if (node.children && node.children.length > 0) {
                            const childMatches = findMatchingNodes(node.children, targetIds);
                            if (childMatches.length > 0) {
                                // 如果有子节点匹配，添加当前节点（但不标记为匹配）
                                result.push({
                                    ...node,
                                    children: childMatches
                                });
                            }
                        }
                    }
                }

                return result;
            };

            return findMatchingNodes(treeData, allowedIds);
        },



        loadDataByOrganization2(organization) {
            console.log('根据组织架构2加载数据:', organization);
            // 根据组织架构2加载数据，将selectedOrganization2传递给后端
        },

        // 检查URL参数
        checkUrlParams() {
            // 获取当前页面路径和参数
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            if (currentPage && currentPage.options) {
                const urlParams = currentPage.options;

                // 处理组织架构参数
                if (urlParams.name) {
                    this.selectedOrganization1Display = urlParams.name;
                    // 更新页面标题
                    this.departmentName = urlParams.name;
                }

                // 处理组织架构参数
                if (urlParams.id) {
                    this.selectedOrganization1Id = urlParams.id;
                }
                // 处理组织架构参数
                if (urlParams.type) {
                    this.selectedOrganization1Type = urlParams.type;
                }

                // 处理时间参数
                if (urlParams.timeRange) {
                    this.selectedTimeRange = urlParams.timeRange;
                    const selectedTag = this.timeTags.find(tag => tag.value === urlParams.timeRange);
                    this.selectedTimeDisplay = selectedTag ? selectedTag.label : '选择时间';
                }

                if (urlParams.startDate && urlParams.endDate) {
                    this.startDate = urlParams.startDate;
                    this.endDate = urlParams.endDate;
                    // 如果是自定义时间，设置回显
                    if (this.selectedTimeRange === 'custom') {
                        this.selectedTimeDisplay = `${this.startDate} ~ ${this.endDate}`;
                    }
                }

                console.log('URL参数:', urlParams);
            }
        },

        // 处理首页详情数据响应
        handleHomePageDetailResponse(res) {
            if (res && res.data && Array.isArray(res.data)) {
                // 更新数据项
                this.dataItems = res.data.map((item, index) => {
                    return {
                        title: item.name + "数据明细",
                        list: [
                            { label: '人均查获数量', value: item.seizureCount || 0 },
                            { label: '人均在岗时长', value: item.workingHours || 0 },
                            { label: '巡检合格率', value: `${((item.checkPassRate * 100) || 0).toFixed(2)}%` },
                            { label: '抽问抽答正确率', value: `${((item.answersAccuracy * 100) || 0).toFixed(2)}%` },
                            { label: '培训答题平均分', value: item.learningGrowthScore || 0 }
                        ]
                    };
                });

                // 更新雷达图
                this.updateRadarChart(res.data);
            } else {
                console.warn('响应数据格式不正确:', res);
            }
        },

        // 更新雷达图数据
        updateRadarChart(data) {
            const chartDom = document.getElementById('radar-chart');
            if (!chartDom) {
                console.warn('雷达图容器未找到');
                return;
            }
            this.chart = echarts.init(chartDom);
            if (!this.chart) {
                console.warn('雷达图未初始化');
                return;
            }

            // 构建雷达图数据
            const seriesData = data.map(item => ({
                name: item.name,
                value: [
                    item.seizureCountGraph || 0,
                    item.workingHoursGraph || 0,
                    item.checkPassRateGraph || 0,
                    item.answersAccuracyGraph || 0,
                    item.learningGrowthScoreGraph || 0
                ]
            }));
            // 计算每个指标的最大值，用于雷达图的max值
            const indicators = [
                { name: '查获数量', max: Math.max(...seriesData.map(d => d.value[0])) },
                { name: '在岗时长', max: Math.max(...seriesData.map(d => d.value[1])) },
                { name: '巡检合格率', max: Math.max(...seriesData.map(d => d.value[2])) },
                { name: '抽问抽答', max: Math.max(...seriesData.map(d => d.value[3])) },
                { name: '培训答题', max: Math.max(...seriesData.map(d => d.value[4])) }
            ];

            const option = {
                tooltip: {
                    show: false
                },
                legend: {
                    type: 'scroll',
                    orient: 'horizontal',
                    bottom: 10,
                    textStyle: {
                        fontSize: 12,
                        color: '#666'
                    },
                    itemWidth: 12,
                    itemHeight: 12,
                    data: seriesData.map(item => item.name)
                },
                radar: {
                    shape: 'circle',
                    indicator: indicators,
                    splitNumber: 4,
                    center: ['50%', '45%'],
                    radius: '55%',
                    axisName: {
                        color: '#666',
                        fontSize: 12
                    },
                    splitLine: {
                        lineStyle: {
                            color: ['#E6E6E6', '#E6E6E6', '#E6E6E6', '#E6E6E6']
                        }
                    },
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['#F8F8F8', '#FFFFFF']
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#E6E6E6'
                        }
                    }
                },
                series: [
                    {
                        name: '能力对比',
                        type: 'radar',

                        data: seriesData.map((item, index) => ({
                            value: item.value,
                            name: item.name,
                            areaStyle: {
                                color: this.getChartColor(index, 0.3)
                            },
                            lineStyle: {
                                color: this.getChartColor(index),
                                width: 2
                            },
                            itemStyle: {
                                color: this.getChartColor(index)
                            }
                        }))
                    }
                ]
            };

            this.chart.setOption(option);


        },




        // 获取图表颜色
        getChartColor(index, opacity = 1) {
            const colors = ['#8FA5EC', '#FF9F7F', '#6ECEB2', '#FFD700', '#BA55D3'];
            const color = colors[index % colors.length];
            if (opacity < 1) {
                // 转换为RGBA格式
                const r = parseInt(color.slice(1, 3), 16);
                const g = parseInt(color.slice(3, 5), 16);
                const b = parseInt(color.slice(5, 7), 16);
                return `rgba(${r}, ${g}, ${b}, ${opacity})`;
            }
            return color;
        }


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

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

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

.depart-name {
    font-size: 34rpx;
    color: #FFFFFF;
    margin-bottom: 34rpx;
}

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

/* 时间选择区块样式 */
.time-selector-container {
    display: flex;
    justify-content: flex-start;

}

.time-selector-item {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20rpx;
    padding: 15rpx 25rpx;
    margin-right: 13rpx;
    cursor: pointer;
    transition: all 0.3s ease;
}

.time-selector-item:active {
    background: rgba(255, 255, 255, 0.3);
}

.time-label {
    font-size: 24rpx;
    color: #FFFFFF;
    margin-right: 10rpx;
}

.time-arrow {
    color: #DBE0F9;
    font-size: 18rpx;
}

/* 时间标签显示区域 */
.time-range-display {
    margin-bottom: 20rpx;
    padding-top: 20rpx;
    border-top: 5rpx dashed rgba(255, 255, 255, 0.1);
}

.time-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
    justify-content: space-around;
}

.time-tag {
    flex: 0 0 calc(33.333% - 10rpx);


    padding: 8rpx 12rpx;
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
    cursor: pointer;
    transition: all 0.3s ease;
    text-align: center;
    position: relative;
}

.time-tag.active {

    color: #fff;
}

.time-tag .checkmark {
    margin-right: 8rpx;
    font-weight: bold;
    font-size: 20rpx;
}

.time-tag:active {
    background: rgba(255, 255, 255, 0.3);
}

/* 自定义时间选择器 */
::v-deep .time-picker-container {
    margin-top: 30rpx;


    border-radius: 20rpx;


    .time-picker {


        .date-range {
            display: flex;
            flex-direction: row;
            gap: 20rpx;
            margin-bottom: 30rpx;
            border-bottom: 5rpx dashed rgba(255, 255, 255, 0.1);
            padding-bottom: 30rpx;
            align-items: center;

            .speret {
                color: #fff;
            }
        }

        .date-input-field {
            flex: 1;
            background: #9EA0EE;
            border: 2rpx solid rgba(255, 255, 255, 0.2);
            border-radius: 7rpx;
            font-size: 24rpx;
            color: #FFFFFF;

            &::placeholder {
                background: #9EA0EE;

            }

            .uni-date-editor {
                background: #9EA0EE;

                .uni-date-editor--x {
                    background: #9EA0EE;

                    .uni-date-x {
                        background: #9EA0EE;

                        .uni-date__x-input {
                            color: #fff;
                        }

                        .uni-icons {
                            display: none;
                        }
                    }

                    .uni-icons::after {
                        display: none;
                    }
                }
            }
        }

        .picker-buttons {
            display: flex;
            justify-content: center;
            gap: 30rpx;

            button {
                flex: 1;
                height: 55rpx;
                line-height: 55rpx;
                border-radius: 10rpx;
                font-size: 26rpx;
                font-weight: bold;
                border: none;
                cursor: pointer;
                transition: all 0.3s ease;
            }

            .btn-cancel {
                background: rgba(255, 255, 255, 0.3);
                color: #FFFFFF;

                &:hover {
                    background: rgba(255, 255, 255, 0.4);
                }
            }

            .btn-confirm {
                background: #FFFFFF;
                color: #8FA5EC;

                &:hover {
                    background: rgba(255, 255, 255, 0.9);
                }
            }
        }
    }
}

.time-picker {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.date-range {
    display: flex;
    align-items: center;
    gap: 15rpx;
}

.date-input-field {
    flex: 1;
}

.picker-buttons {
    display: flex;
    gap: 15rpx;
    justify-content: flex-end;
}



.btn-cancel:active,
.btn-confirm:active {
    opacity: 0.8;
}

/* 弹窗样式 */
.popup-container {
    background: #FFFFFF;
    border-radius: 20rpx;
    width: 80vw;
    max-width: 600rpx;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #F0F0F0;
}

.popup-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
}

.popup-close {
    font-size: 40rpx;
    color: #999;
    cursor: pointer;
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 时间标签区域 */
.time-tags-section {
    padding: 30rpx;
    display: flex;
    flex-wrap: wrap;
    gap: 15rpx;
}

.popup-time-tag {
    background: #F5F5F5;
    border-radius: 20rpx;
    padding: 15rpx 25rpx;
    font-size: 24rpx;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
}

.popup-time-tag.active {
    background: #8FA5EC;
    color: #FFFFFF;
}

.popup-time-tag:active {
    opacity: 0.8;
}

/* 搜索区域 */
.search-section {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #F0F0F0;
}

/* 树形结构区域 */
.tree-section {
    flex: 1;
    min-height: 300rpx;
    max-height: 400rpx;
    padding: 20rpx 30rpx;
}

.tree-scroll {
    height: 100%;
    max-height: 360rpx;

}

/* 人员列表区域 */
.person-section {
    flex: 1;
    min-height: 300rpx;
    max-height: 400rpx;
    padding: 20rpx 30rpx;
}

.person-scroll {
    height: 100%;
}

.person-item {
    padding: 20rpx;
    border-bottom: 1rpx solid #F0F0F0;
    font-size: 24rpx;
    color: #333;
    cursor: pointer;
    transition: all 0.3s ease;
}

.person-item.active {
    background: #8FA5EC;
    color: #FFFFFF;
}

.person-item:active {
    background: #F0F0F0;
}

/* 按钮区域 */
.button-section {
    display: flex;
    gap: 15rpx;
    padding: 30rpx;
    border-top: 1rpx solid #F0F0F0;
}

.button-section .btn-cancel,
.button-section .btn-confirm {
    flex: 1;
    text-align: center;
    padding: 20rpx;
    border-radius: 10rpx;
    font-size: 28rpx;
}

.button-section .btn-cancel {
    background: #F0F0F0;
    color: #666;
}

.button-section .btn-confirm {
    background: #3c66ef;
    color: #FFFFFF;
}

/* 能力对比内容区域 */
.capability-content {
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 30rpx;
    margin: 20rpx 34rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.chart-section {
    margin-bottom: 30rpx;
}

.chart-container {
    width: 100%;
    height: 500rpx;

    margin-bottom: 20rpx;
}

.radar-chart {
    width: 100%;
    height: 100%;
}

.data-section {
    .data-item {
        background: #EFF2FE;
        border-radius: 15rpx;
        padding: 20rpx;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        margin-bottom: 30rpx;

        .item-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 20rpx;
            width: 100%;
            text-align: left;
        }

        .data-content-section {
            display: flex;
            width: 100%;

            .data-content {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;

                .data-value {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333333;
                    margin-bottom: 8rpx;
                }

                .data-label {
                    font-size: 24rpx;
                    color: #666;
                }
            }
        }
    }
}
</style>