<template>
    <view class="station-profile-page">
        <div class="page-header">
            <div class="header-title">
                <div class="title-main">旅检部综合信息展示</div>
                <div class="header-right">
                    <div class="current-time">{{ currentTime }}</div>
                    <!-- <div class="menu-icon">
            <uni-icons type="bars" size="20" color="#A78BFA"></uni-icons>
          </div> -->
                </div>
            </div>

            <div class="time-filter">
                <scroll-view scroll-x class="time-scroll">
                    <div class="time-tags">
                        <div v-for="(tag, index) in timeTags" :key="index"
                            :class="['time-tag', { active: selectedTimeTag === index }]" @click="onTimeTagClick(index)">
                            {{ tag }}
                        </div>
                    </div>
                </scroll-view>
                <div v-if="selectedTimeTag === 4" class="date-range-picker">
                    <picker mode="date" :value="startDate" @change="onStartDateChange">
                        <div class="date-input" :class="{ filled: startDate }">
                            {{ startDate || '开始日期' }}
                        </div>
                    </picker>
                    <span class="date-separator">至</span>
                    <picker mode="date" :value="endDate" @change="onEndDateChange">
                        <div class="date-input" :class="{ filled: endDate }">
                            {{ endDate || '结束日期' }}
                        </div>
                    </picker>
                </div>
            </div>

            <div class="tab-nav">
                <div class="tab-item" :class="{ active: activeTab === 'profile' }" @click="activeTab = 'profile'">
                    站点画像
                </div>
                <div class="tab-item" :class="{ active: activeTab === 'data' }" @click="activeTab = 'data'">
                    运行数据
                </div>
            </div>
        </div>

        <div class="page-content">
            <SectionTitle title="值班信息">
                <template #header-right>
                    <div class="date-text">{{ currentDate }}</div>
                </template>
                <DutyInfo :dutyData="dutyData" />
            </SectionTitle>

            <SectionTitle title="人员在岗情况">
                <AttendanceStatus :attendanceData="attendanceData" />
            </SectionTitle>

            <div v-if="activeTab === 'profile'">
                <SectionTitle title="团队成员">
                    <TeamMemberTable :chartsData="teamMemberData" />
                </SectionTitle>

                <SectionTitle title="成员基本情况分布">
                    <MemberBasicDistribution :chartsData="memberBasicData" />
                </SectionTitle>

                <SectionTitle title="成员职位情况分布">
                    <MemberPositionDistribution :chartsData="memberPositionData" />
                </SectionTitle>
            </div>

            <div v-if="activeTab === 'data'">
                <SectionTitle title="当天开航每小时各区过检人数组合图">
                    <PassengerChart :chartsData="passengerData" />
                </SectionTitle>


                <SectionTitle title="查获信息展示">
                    <SeizureInfo :chartsData="seizureInfoData" />
                </SectionTitle>

                <SectionTitle title="查获物品分布">
                    <ItemDistribution :chartsData="itemDistributionData" />
                </SectionTitle>


                <SectionTitle title="每日查获数量">
                    <DailySeizureChart :chartsData="dailySeizureData" />
                </SectionTitle>

                <SectionTitle title="查获工作区域分布">
                    <AreaDistribution :chartsData="areaDistributionData" />
                </SectionTitle>


                <SectionTitle title="不安全事件物品分布">
                    <UnsafeItemsChart :chartsData="unsafeItemsData" />
                </SectionTitle>

                <SectionTitle title="不安全事件类型分布">
                    <UnsafeTypesChart :chartsData="unsafeTypesData" />
                </SectionTitle>


                <SectionTitle title="不安全事件查获岗位分布">
                    <UnsafePositionChart :chartsData="unsafePositionData" />
                </SectionTitle>

                <SecurityTestCharts :chartsData="securityTestData" />
            </div>
        </div>
    </view>
</template>

<script>
import SectionTitle from '@/components/SectionTitle.vue'
import TeamMemberTable from '../components/TeamMemberTable.vue'
import MemberBasicDistribution from '../components/MemberBasicDistribution.vue'
import MemberPositionDistribution from '../components/MemberPositionDistribution.vue'
import PassengerChart from '../components/PassengerChart.vue'
import SeizureInfo from '../components/SeizureInfo.vue'
import ItemDistribution from '../components/ItemDistribution.vue'
import DailySeizureChart from '../components/DailySeizureChart.vue'
import AreaDistribution from '../components/AreaDistribution.vue'
import UnsafeItemsChart from '../components/UnsafeItemsChart.vue'
import UnsafeTypesChart from '../components/UnsafeTypesChart.vue'
import UnsafePositionChart from '../components/UnsafePositionChart.vue'
import SecurityTestCharts from '../components/SecurityTestCharts.vue'
import DutyInfo from '../components/DutyInfo.vue'
import AttendanceStatus from '../components/AttendanceStatus.vue'
import {
    countStationTeamStats,
    getDeptMemberDistribution,
    getDeptPositionDistribution,
    countStationHourlyThroughput,
    countSeizureInfoItem,
    countSeizeSubjectCategoryQuantity,
    countSeizureTotalQuantity,
    countSeizureSingleQuantity,
    countSeizeAreaQuantity,
    countSeizureStatsItem,
    countSeizureStatsType,
    countSeizureStatsPost,
    securityTestItemClassification,
    securityTestPassingStatus,
    securityTestRegion
} from '@/api/portraitManagement/portraitManagement'

const itemColors = ['#60A5FA', '#34D399', '#FBBF24', '#EF4444', '#9CA3AF', '#A78BFA', '#F472B6', '#6EE7B7']

export default {
    components: {
        SectionTitle,
        TeamMemberTable,
        MemberBasicDistribution,
        MemberPositionDistribution,
        PassengerChart,
        SeizureInfo,
        ItemDistribution,
        DailySeizureChart,
        AreaDistribution,
        UnsafeItemsChart,
        UnsafeTypesChart,
        UnsafePositionChart,
        SecurityTestCharts,
        DutyInfo,
        AttendanceStatus
    },
    data() {
        return {
            activeTab: 'profile',
            selectedTimeTag: 3,
            timeTags: ['近一周', '近一月', '近三月', '近一年', '自定义时间范围'],
            currentTime: '',
            timer: null,
            startDate: '',
            endDate: '',
            dutyData: [
                { label: '值班领导', value: '李凯' },
                { label: '安全板块', value: '李凯' },
                { label: '服务板块', value: '李凯' },
                { label: '运行板块', value: '李凯' },
                { label: '备勤值班', value: '李凯' }
            ],
            attendanceData: [
                { number: '120', label: '主班在岗 | 旅检一部' },
                { number: '130', label: '主班在岗 | 旅检二部' },
                { number: '150', label: '主班在岗 | 旅检三部' },
                { number: '80', label: '备勤在岗 | 旅检一部' },
                { number: '70', label: '备勤在岗 | 旅检二部' },
                { number: '65', label: '备勤在岗 | 旅检三部' }
            ],
            teamMemberData: [],
            memberBasicData: {
                gender: { labels: [], data: [] },
                ethnicity: { labels: [], data: [] },
                political: { labels: [], data: [] }
            },
            memberPositionData: {
                qualification: { labels: [], data: [] },
                experience: { labels: [], data: [] },
                position: { labels: [], data: [] }
            },
            passengerData: {
                labels: [],
                areas: {}
            },
            seizureInfoData: {
                total: 0,
                depts: {
                    labels: [],
                    data: []
                }
            },
            itemDistributionData: {
                items: []
            },
            dailySeizureData: {
                total: {
                    labels: [],
                    data: []
                },
                dept: {
                    labels: [],
                    data: {}
                }
            },
            areaDistributionData: {
                labels: [],
                data: []
            },
            unsafeItemsData: {
                items: []
            },
            unsafeTypesData: {
                types: []
            },
            unsafePositionData: {
                total: 0,
                positions: {
                    labels: [],
                    data: []
                }
            },
            securityTestData: {
                items: {
                    labels: [],
                    data: []
                },
                results: {
                    labels: [],
                    data: []
                },
                areas: {
                    labels: [],
                    data: []
                }
            }
        }
    },
    computed: {
        currentDate() {
            const now = new Date()
            const year = now.getFullYear()
            const month = String(now.getMonth() + 1).padStart(2, '0')
            const day = String(now.getDate()).padStart(2, '0')
            const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
            const weekDay = weekDays[now.getDay()]
            return `${year}年${month}月${day}日 ${weekDay}`
        }
    },
    mounted() {
        this.updateTime()
        this.timer = setInterval(() => {
            this.updateTime()
        }, 1000)
        this.onTimeTagClick(3)
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer)
        }
    },
    methods: {
        updateTime() {
            const now = new Date()
            const hours = String(now.getHours()).padStart(2, '0')
            const minutes = String(now.getMinutes()).padStart(2, '0')
            const seconds = String(now.getSeconds()).padStart(2, '0')
            this.currentTime = `${hours}:${minutes}:${seconds}`
        },
        fetchAllData(params) {
            this.fetchTeamData(params)
            this.fetchMemberDistribution(params)
            this.fetchPositionDistribution(params)
            const copyParams = { startDate:params.startDate, endDate:params.endDate }
            this.fetchPassengerData(copyParams)
            this.fetchSeizureInfo(copyParams)
            this.fetchItemDistribution(copyParams)
            this.fetchDailySeizure(copyParams)
            this.fetchAreaDistribution(copyParams)
            this.fetchUnsafeItems(copyParams)
            this.fetchUnsafeTypes(copyParams)
            this.fetchUnsafePosition(copyParams)
            this.fetchSecurityTestData(copyParams)
        },
        buildTimeParams() {
            const now = new Date()
            const today = this.formatDate(now)
            if (this.selectedTimeTag === 4) {
                if (this.startDate && this.endDate) {
                    return { startDate: this.startDate, endDate: this.endDate, deptId: '100' }
                }
                return { deptId: '100' }
            }
            let startDate
            switch (this.selectedTimeTag) {
                case 0:
                    startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
                    break
                case 1:
                    startDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate())
                    break
                case 2:
                    startDate = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate())
                    break
                case 3:
                    startDate = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate())
                    break
                default:
                    return { deptId: '100' }
            }
            return { startDate: this.formatDate(startDate), endDate: today, deptId: '100' }
        },
        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}`
        },
        onTimeTagClick(index) {
            this.selectedTimeTag = index
            if (index === 4) {
                this.startDate = ''
                this.endDate = ''
                return
            }
            const params = this.buildTimeParams()
            this.fetchAllData(params)
        },
        onStartDateChange(e) {
            this.startDate = e.detail.value
            if (this.startDate && this.endDate) {
                this.fetchAllData(this.buildTimeParams())
            }
        },
        onEndDateChange(e) {
            this.endDate = e.detail.value
            if (this.startDate && this.endDate) {
                this.fetchAllData(this.buildTimeParams())
            }
        },
        fetchTeamData(params) {
            countStationTeamStats(params).then(res => {
                if (res.code === 200 && res.data) {
                    this.teamMemberData = (res.data || []).map(item => ({
                        department: item.deptName,
                        employeeCount: item.employeeCount,
                        partyMemberCount: item.partyMemberCount,
                        avgAge: item.avgAge,
                        avgTenure: item.avgWorkYears,
                        certificateCount: item.qualificationLevel,
                        machineYears: item.avgXrayOperatorYears,
                        comprehensiveScore: item.totalScore
                    }))
                }
            }).catch(() => { })
        },
        fetchMemberDistribution(params) {
            getDeptMemberDistribution(params).then(res => {
                if (res.code === 200 && res.data) {
                    this.memberBasicData = {
                        gender: {
                            labels: (res.data.sexDistribution || []).map(item => item.name),
                            data: (res.data.sexDistribution || []).map(item => item.count)
                        },
                        ethnicity: {
                            labels: (res.data.nationDistribution || []).map(item => item.name),
                            data: (res.data.nationDistribution || []).map(item => item.count)
                        },
                        political: {
                            labels: (res.data.politicalDistribution || []).map(item => item.name),
                            data: (res.data.politicalDistribution || []).map(item => item.count)
                        }
                    }
                }

            }).catch(() => { })
        },
        fetchPositionDistribution(params) {
            getDeptPositionDistribution(params).then(res => {
                if (res.code === 200 && res.data) {
                    this.memberPositionData = {
                        qualification: {
                            labels: (res.data.qualificationDistribution || []).map(item => item.name),
                            data: (res.data.qualificationDistribution || []).map(item => item.count)
                        },
                        experience: {
                            labels: (res.data.xrayYearDistribution || []).map(item => item.name),
                            data: (res.data.xrayYearDistribution || []).map(item => item.count)
                        },
                        position: {
                            labels: (res.data.positionDistribution || []).map(item => item.name),
                            data: (res.data.positionDistribution || []).map(item => item.count)
                        }
                    }
                }
            }).catch(() => { })
        },
        fetchPassengerData(params) {
            countStationHourlyThroughput(params).then(res => {
                if (res.code === 200 && res.data) {
                    const rawData = res.data || []
                    const hours = rawData.map(item => item.hour)
                    const areaMap = {}
                    rawData.forEach(item => {
                        (item.areaList || []).forEach(area => {
                            if (!areaMap[area.areaName]) {
                                areaMap[area.areaName] = []
                            }
                            areaMap[area.areaName].push(area.areaFlow)
                        })
                    })
                    this.passengerData = {
                        labels: hours,
                        areas: areaMap,
                        totalFlow: rawData.map(item => item.totalHourFlow)
                    }
                }
            }).catch(() => { })
        },
        fetchSeizureInfo(params) {
            countSeizureInfoItem(params).then(res => {
                if (res.code === 200 && res.data) {
                    const itemList = res.data.itemList || []
                    this.seizureInfoData = {
                        total: res.data.totalSeizeNum || 0,
                        depts: {
                            labels: itemList.map(item => item.name),
                            data: itemList.map(item => item.seizeNum)
                        }
                    }
                }
            }).catch(() => { })
        },
        fetchItemDistribution(params) {
            countSeizeSubjectCategoryQuantity(params).then(res => {
                if (res.code === 200 && res.data) {
                    const items = (res.data || []).map((item, index) => ({
                        name: item.itemName,
                        value: item.itemNum,
                        color: itemColors[index % itemColors.length]
                    }))
                    this.itemDistributionData = { items }
                }
            }).catch(() => { })
        },
        fetchDailySeizure(params) {
            countSeizureTotalQuantity(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.dailySeizureData.total = {
                        labels: data.map(item => item.recordDate),
                        data: data.map(item => item.seizeQuantity)
                    }
                }
            }).catch(() => { })
            countSeizureSingleQuantity(params).then(res => {
                if (res.code === 200 && res.data) {
                    const rawData = res.data || []
                    const dates = rawData.map(item => item.recordDate)
                    const deptMap = {}
                    rawData.forEach(dayItem => {
                        (dayItem.items || []).forEach(subItem => {
                            if (!deptMap[subItem.groupName]) {
                                deptMap[subItem.groupName] = []
                            }
                            deptMap[subItem.groupName].push(subItem.seizeQuantity)
                        })
                    })
                    this.dailySeizureData.dept = {
                        labels: dates,
                        deptData: Object.keys(deptMap).map(name => ({
                            name,
                            data: deptMap[name]
                        }))
                    }
                }
            }).catch(() => { })
        },
        fetchAreaDistribution(params) {
            countSeizeAreaQuantity(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.areaDistributionData = {
                        labels: data.map(item => item.workArea),
                        data: data.map(item => item.areaSeizeNum)
                    }
                }
            }).catch(() => { })
        },
        fetchUnsafeItems(params) {
            countSeizureStatsItem(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.unsafeItemsData = {
                        items: data.map(item => ({
                            name: item.itemName,
                            value: item.itemNum
                        }))
                    }
                }
            }).catch(() => { })
        },
        fetchUnsafeTypes(params) {
            countSeizureStatsType(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.unsafeTypesData = {
                        types: data.map(item => ({
                            name: item.eventType,
                            value: item.eventTypeNum
                        }))
                    }
                }
            }).catch(() => { })
        },
        fetchUnsafePosition(params) {
            countSeizureStatsPost(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    const total = data.reduce((sum, item) => sum + (item.count || 0), 0)
                    this.unsafePositionData = {
                        total: total,
                        positions: {
                            labels: data.map(item => item.positionName),
                            data: data.map(item => item.positionNum)
                        }
                    }
                }
            }).catch(() => { })
        },
        fetchSecurityTestData(params) {
            securityTestItemClassification(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.securityTestData.items = {
                        labels: data.map(item => item.name),
                        data: data.map(item => item.total)
                    }
                }
            }).catch(() => { })
            securityTestPassingStatus(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.securityTestData.results = {
                        labels: data.map(item => item.name),
                        data: data.map(item => item.total)
                    }
                }
            }).catch(() => { })
            securityTestRegion(params).then(res => {
                if (res.code === 200 && res.data) {
                    const data = res.data || []
                    this.securityTestData.areas = {
                        labels: data.map(item => item.name),
                        data: data.map(item => item.total)
                    }
                }
            }).catch(() => { })
        }
    }
}
</script>

<style lang="scss" scoped>
.station-profile-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #1E1B4B 0%, #312E81 100%);
    padding-bottom: 40rpx;
}

.page-header {
    position: sticky;
    top: 0;
    z-index: 100;
    background: rgba(30, 27, 75, 0.9);
    backdrop-filter: blur(10px);
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
}

.header-title {
    padding: 24rpx 32rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-main {
        font-size: 36rpx;
        font-weight: bold;
        background: linear-gradient(90deg, #A78BFA, #60A5FA);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .current-time {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.6);
    }

    .menu-icon {
        display: flex;
        align-items: center;
    }
}

.time-filter {
    padding: 16rpx 32rpx;
    background: rgba(30, 27, 75, 0.8);
}

.time-scroll {
    width: 100%;
}

.time-tags {
    display: flex;
    gap: 16rpx;
    white-space: nowrap;
}

.time-tag {
    padding: 8rpx 10rpx;
    border-radius: 50rpx;
    background: rgba(45, 42, 85, 0.8);
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
    transition: all 0.3s;

    &.active {
        background: #A78BFA;
        color: #1E1B4B;
        font-weight: 500;
    }
}

.date-range-picker {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-top: 16rpx;
    padding-top: 16rpx;
    border-top: 1rpx solid rgba(255, 255, 255, 0.1);
}

.date-input {
    flex: 1;
    padding: 12rpx 24rpx;
    border-radius: 12rpx;
    background: rgba(45, 42, 85, 0.8);
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.4);
    text-align: center;

    &.filled {
        color: rgba(255, 255, 255, 0.9);
    }
}

.date-separator {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.5);
    flex-shrink: 0;
}

.tab-nav {
    padding: 16rpx 32rpx;
    display: flex;
    justify-content: center;
    gap: 64rpx;
}

.tab-item {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.5);
    padding-bottom: 8rpx;
    border-bottom: 2rpx solid transparent;
    transition: all 0.3s;

    &.active {
        color: #A78BFA;
        border-bottom-color: #A78BFA;
    }
}

.page-content {
    padding: 32rpx;
    display: flex;
    flex-direction: column;
    /* gap: 32rpx; */
}

.two-col-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
}

.date-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.5);
}
</style>
