<template>
    <home-container :customStyle="{ background: 'none' }">
        <view class="container">
            <!-- 顶部tabs -->
            <h-tabs v-if="roles.includes('kezhang')" v-model="currentTab" :tabs="tabList" value-key="type"
                label-key="title" @change="handleTabChange" />

            <!-- 通道开放情况 -->
            <view class="card" :style="{ paddingBottom: currentTab !== 'all' ? '100rpx' : '24rpx' }">
                <view class="card-header">通道开放情况</view>
                <view class="chart-container">
                    <view class="pie-chart" id="pieChart"></view>
                </view>

                <view v-if="currentTab === 'all'" style="margin-top: 120rpx;" class="bar-chart" id="barChart1"></view>
            </view>

            <!-- 人员情况 -->
            <view v-if="currentTab === 'all'" class="card">
                <view class="card-header">人员情况</view>
                <view class="bar-chart" id="barChart2"></view>
            </view>

            <!-- 明细情况 -->
            <view class="card-header" style="padding-left: 10rpx;">明细情况</view>
            <view class="card-detail">
                <uni-collapse v-if="isShowBarChart1">
                    <uni-collapse-item v-for="(item, index) in terminlDetail" :key="index" :title="item.terminlName"
                        :open="true">
                        <view class="detail-content">
                            <view v-if="item.region.length > 0">在岗班组</view>
                            <view class="detail-row" v-for="(regionItem, i) in item.region" :key="i">
                                <view class="detail-title">{{ regionItem.regionalName }}&nbsp;&nbsp;开放数量：{{
                                    regionItem.openChannelCount }}</view>
                                <TableList :data="regionItem.detailList" :columns="[{
                                    props: 'channelName',
                                    title: '通道名称'
                                }, {
                                    props: 'onDutyTeamName',
                                    title: '在岗班组'
                                }, {
                                    props: 'onDutyTime',
                                    title: '上岗时间'
                                }, {
                                    props: 'onDutyCount',
                                    title: '在岗人数'
                                }]" />
                            </view>
                            <view v-if="item.waitList.length > 0" style="margin-bottom: 10rpx;">空闲班组</view>
                            <TableList v-if="item.waitList.length > 0" :data="item.waitList" :columns="[{
                                props: 'waitTeamName',
                                title: '待岗班组'
                            }, {
                                props: 'waitCount',
                                title: '待岗人数'
                            }, {
                                props: 'checkOutTime',
                                title: '下通道时间'
                            }]" />
                        </view>
                    </uni-collapse-item>
                </uni-collapse>
                <view v-else="!isShowBarChart1">
                    <no-data text="暂无数据" icon-type="search" icon-size="60" icon-color="#C0C4CC" />
                </view>
            </view>
        </view>
    </home-container>
</template>

<script>
import HomeContainer from "@/components/HomeContainer.vue";
import TableList from "./components/TableList.vue";
import * as echarts from 'echarts';
import { getChannelStatistics } from '@/api/attendanceStatistics/attendanceStatistics';
import HTabs from "@/components/h-tabs/h-tabs.vue";

export default {
    components: { HomeContainer, TableList, HTabs },
    data() {
        return {
            currentTab: 'my', // 默认显示我的区域
            tabList: [
                {
                    type: 'my',
                    title: '我的区域'
                },
                {
                    type: 'all',
                    title: '全部区域'
                }
            ],
            terminlDetail: [],
            mainDetail: {},
            pieChart: null,
            barChart1: null,
            barChart2: null,
            roles: this.$store.state.user.roles
        }
    },
    computed: {
        isShowPieChart() {
            const values = Object.values(this.mainDetail || {});
            console.log('mainDetail values:', values, 'all empty check:', values.every(item => !item));
            return !values.every(item => !item);
        },
        isShowBarChart1() {
            return this.terminlDetail.length > 0;
        },
    },
    mounted() {
        this.fetchData("1");

        if (!this.roles.includes('kezhang')) {
            this.currentTab = 'all'
        }
    },
    methods: {
        handleTabChange(newValue, tab) {
            this.currentTab = newValue;

            this.fetchData(this.currentTab == 'my' ? "1" : "2")
        },
        async fetchData(status) {

            try {
                console.log('正在请求考勤统计数据，status:', status);
                const response = await getChannelStatistics(status);
                console.log('接口返回数据:', response);

                const { channelCount, maintainCount, onDutyCount, terminlDetail } = response;

                console.log('解析后的数据:', { channelCount, maintainCount, onDutyCount, terminlDetail });

                this.terminlDetail = terminlDetail || [];
                this.mainDetail = {
                    channelCount: channelCount || 0,
                    maintainCount: maintainCount || 0,
                    onDutyCount: onDutyCount || 0,

                }
                console.log(this.mainDetail, 22)
                this.$nextTick(() => {
                    this.initCharts();
                })

            } catch (e) {
                console.error('获取考勤数据失败', e);
            }
        },
        initCharts() {
            const pieDom = document.getElementById('pieChart');
            const barDom1 = document.getElementById('barChart1');
            const barDom2 = document.getElementById('barChart2');

            if (pieDom) {
                this.pieChart = echarts.init(pieDom);
            }
            if (barDom1) {
                this.barChart1 = echarts.init(barDom1);
            }
            if (barDom2) {
                this.barChart2 = echarts.init(barDom2);
            }
            this.$nextTick(() => {

                this.updateCharts();
            });
        },
        updateCharts() {
            // 在更新图表前先清空所有图表
            this.pieChart && this.pieChart.clear();
            this.barChart1 && this.barChart1.clear();
            this.barChart2 && this.barChart2.clear();

            let openRate = 0;
            let openData = 0;
            let closeData = 0;
            if (this.roles.includes('kezhang') && this.currentTab == 'my') {

                openData = this.terminlDetail.reduce((item, cur) => {
                    return item + cur.onDutyChannelCount;
                }, 0);
                let allData = this.terminlDetail.reduce((item, cur) => {
                    return item + cur.channelCount;
                }, 0);
                closeData = allData - openData;
                openRate = (openData / allData) * 100;
            } else {
                let allData = this.terminlDetail.reduce((item, cur) => {
                    return item + cur.channelCount;
                }, 0);

                // openData = this.mainDetail.onDutyCount;
                openData = this.terminlDetail.reduce((item, cur) => {
                    return item + cur.onDutyChannelCount;
                }, 0);
                openRate = (openData / allData) * 100;
                closeData = allData - openData;

            }

            // 检查数据是否有效
            const hasValidData = openData > 0 || closeData > 0;

            // 环形图配置
            this.pieChart && this.pieChart.setOption({
                series: [{
                    type: 'pie',
                    radius: ['55%', '70%'],
                    avoidLabelOverlap: false,
                    // label: { show: false },
                    data: hasValidData ? [
                        { value: openRate, name: '开放 ' + openData, itemStyle: { color: '#5972C0' } },
                        { value: 100 - openRate, name: '未开放 ' + closeData, itemStyle: { color: 'rgba(89, 114, 192, 0.5)' } }
                    ] : [],
                    silent: !hasValidData // 无数据时禁用交互
                }],
                graphic: hasValidData ? [{
                    type: 'text',
                    left: 'center',
                    top: '40%',
                    style: {
                        text: '开放率',
                        font: 'normal 16px sans-serif',
                        fill: '#333'
                    }
                }, {
                    type: 'text',
                    left: 'center',
                    top: '50%',
                    style: {
                        text: openRate.toFixed(2) + '%',
                        font: 'bold 24px sans-serif',
                        fill: '#333'
                    }
                }] : [{
                    // 无数据时显示提示
                    type: 'text',
                    left: 'center',
                    top: 'center',
                    style: {
                        text: '暂无数据',
                        font: '16px sans-serif',
                        fill: '#999'
                    }
                }]
            });

            let firstTerminal = 'T1航站楼';
            let secondTerminal = 'T2航站楼';
            let terminalName = [firstTerminal, secondTerminal]

            // 安全检查：确保 terminlDetail 存在且为数组
            let barT1 = this.terminlDetail && Array.isArray(this.terminlDetail)
                ? this.terminlDetail.filter(item => item.terminlName === firstTerminal)[0]
                : null;
            let barT2 = this.terminlDetail && Array.isArray(this.terminlDetail)
                ? this.terminlDetail.filter(item => item.terminlName === secondTerminal)[0]
                : null;

            let batT1Open = barT1?.onDutyChannelCount;//T1航站楼开放人数
            let batT2Open = barT2?.onDutyChannelCount;//T2航站楼开放人数
            let batT1Close = barT1 ? barT1.channelCount - barT1.onDutyChannelCount : 0;//T1航站楼未开放人数
            let batT2Close = barT2 ? barT2.channelCount - barT2.onDutyChannelCount : 0;//T2航站楼未开放人数
            console.log(batT1Open, batT2Open, "batT2Open")

            // 检查条形图数据是否有效
            const hasBarData = (batT1Open > 0 || batT1Close > 0 || batT2Open > 0 || batT2Close > 0);

            // 通道开放情况正负条形图
            if (this.currentTab === 'all') {
                this.barChart1 && this.barChart1.setOption({
                    tooltip: { 
                        trigger: 'axis', 
                        axisPointer: { type: 'shadow' },
                        formatter: function(params) {
                            let result = params[0].name + '<br/>';
                            params.forEach(function(item) {
                                result += item.marker + ' ' + item.seriesName + ': ' + Math.abs(item.value) + '<br/>';
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['开放', '未开放'],
                        top: '15%'
                    },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '4%',
                        containLabel: true,
                        backgroundColor: 'transparent'
                    },
                    xAxis: {
                        type: 'value',
                        axisLine: { show: true },
                        axisTick: { show: false },
                        axisLabel: {
                            show: false,
                            formatter: function (value) {
                                return Math.abs(value);
                            }
                        },
                        splitLine: { show: false },
                        min: function (value) {
                            return value.min - (value.max - value.min) * 0.3;
                        },
                        max: function (value) {
                            return value.max + (value.max - value.min) * 0.3;
                        }
                    },
                    yAxis: {
                        type: 'category',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        data: terminalName,
                        splitLine: { show: false }
                    },
                    series: hasBarData ? [
                        {
                            name: '开放',
                            type: 'bar',
                            data: [-batT1Open, -batT2Open],
                            stack: 'total',
                            barWidth: '30%',
                            itemStyle: { color: '#6E65F1' },
                            label: {
                                show: function (params) {
                                    return Math.abs(params.value) !== 0;
                                },
                                position: 'left',
                                formatter: function (params) {
                                    return Math.abs(params.value) === 0 ? '' : Math.abs(params.value);
                                }
                            }
                        },
                        {
                            name: '未开放',
                            type: 'bar',
                            stack: 'total',
                            barWidth: '30%',
                            data: [batT1Close, batT2Close],
                            itemStyle: { color: '#D4D1FB' },
                            label: {
                                show: function (params) {
                                    return Math.abs(params.value) !== 0;
                                },
                                position: 'right',
                                formatter: function (params) {
                                    return Math.abs(params.value) === 0 ? '' : Math.abs(params.value);
                                }
                            }
                        }
                    ] : [],
                    graphic: !hasBarData ? [{
                        // 无数据时显示提示
                        type: 'text',
                        left: 'center',
                        top: 'center',
                        style: {
                            text: '暂无数据',
                            font: '16px sans-serif',
                            fill: '#999'
                        }
                    }] : []
                });
            }


            let batT1NormalPerson = barT1?.onDutyCount;//T1航站楼在岗人数
            let batT2NormalPerson = barT2?.onDutyCount;//T2航站楼在岗人数
            let batT1FreePerson = barT1 ? barT1.openChannelCount - barT1.onDutyCount : 0;//T1航站楼空闲人数
            let batT2FreePerson = barT2 ? barT2.openChannelCount - barT2.onDutyCount : 0;//T2航站楼空闲人数
            console.log(batT1NormalPerson, batT2NormalPerson, batT1FreePerson, batT2FreePerson, "batT2NormalPerson")
            // 检查条形图数据是否有效
            const hasBar2Data = (batT1NormalPerson > 0 || batT2NormalPerson > 0 || batT1FreePerson > 0 || batT2FreePerson > 0);
            // 人员情况正负条形图
            if (this.currentTab === 'all') {
                this.barChart2 && this.barChart2.setOption({
                    tooltip: { 
                        trigger: 'axis', 
                        axisPointer: { type: 'shadow' },
                        formatter: function(params) {
                            let result = params[0].name + '<br/>';
                            params.forEach(function(item) {
                                result += item.marker + ' ' + item.seriesName + ': ' + Math.abs(item.value) + '<br/>';
                            });
                            return result;
                        }
                    },
                    legend: { data: ['在岗人数', '空闲人数'], top: '15%' },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '4%',
                        containLabel: true,
                        backgroundColor: 'transparent'
                    },
                    xAxis: {
                        type: 'value',
                        axisLine: { show: true },
                        axisTick: { show: false },
                        axisLabel: {
                            show: false,
                            formatter: function (value) {
                                return Math.abs(value);
                            }
                        },
                        splitLine: { show: false },
                        min: function (value) {
                            return value.min - (value.max - value.min) * 0.3;
                        },
                        max: function (value) {
                            return value.max + (value.max - value.min) * 0.3;
                        }
                    },
                    yAxis: {
                        type: 'category',
                        axisLine: { show: false },
                        axisTick: { show: false },
                        data: terminalName,
                        splitLine: { show: false }
                    },
                    series: hasBar2Data ? [
                        {
                            name: '在岗人数',
                            type: 'bar',
                            data: [-batT1NormalPerson, -batT2NormalPerson],
                            stack: 'total',
                            barWidth: '30%',
                            itemStyle: { color: '#6E65F1' },
                            label: {
                                show: true,
                                position: 'left',
                                formatter: function (params) {
                                    return Math.abs(params.value) === 0 ? '' : Math.abs(params.value);
                                }
                            }
                        },
                        {
                            name: '空闲人数',
                            type: 'bar',
                            stack: 'total',
                            barWidth: '30%',
                            data: [batT1FreePerson, batT2FreePerson],
                            itemStyle: { color: '#D4D1FB' },
                            label: {
                                show: true,
                                position: 'right',
                                formatter: function (params) {
                                    return Math.abs(params.value) === 0 ? '' : Math.abs(params.value);
                                }
                            }
                        }
                    ] : [],
                    graphic: !hasBar2Data ? [{
                        // 无数据时显示提示
                        type: 'text',
                        left: 'center',
                        top: 'center',
                        style: {
                            text: '暂无数据',
                            font: '16px sans-serif',
                            fill: '#999'
                        }
                    }] : []
                });
            }


        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    padding: 20rpx;
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    background: none !important;
}

.card-detail {
    padding: 0;
    background: #fff;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.card {
    background: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.card-header {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
}

.chart-container {
    position: relative;
    height: 300rpx;
    margin-bottom: 20rpx;
}

.pie-chart,
.bar-chart {
    width: 100% !important;
    height: 400rpx;
}




.open-rate {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 28rpx;
    color: #666;
}

.detail-content {
    padding: 20rpx;
}

.detail-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    font-size: 26rpx;
    color: #666;
    flex-direction: column;

    .detail-title {
        margin: 10rpx 0;
        color: #6E65F1;
    }
}
</style>