<template>
    <view class="vehicles-entering">
        <!-- 入区车流标题 -->
        <view class="section-header">
            <text class="section-title">入区车流</text>
        </view>

        <!-- 入区车流图表 -->
        <view class="chart-card">
            <view class="chart-content">
                <view class="bar-chart-container">
                    <!-- 图表加载效果 -->
                    <ChartLoading v-if="isLoading" text="数据加载中..." />
                    <!-- 实际图表 -->
                    <QiunDataCharts v-else type="column" :opts="vehicleChartOpts" :chartData="vehicleChartData"
                        :canvas2d="true" :inScrollView="true" canvasId="vehicleChart" :animation="false" :ontap="true"
                        :ontouch="true" tooltipFormat="vehicleChartData" />
                </view>
            </view>
        </view>

        <!-- 对客营收标题 -->
        <view class="section-header">
            <text class="section-title">对客营收</text>
        </view>
        <view class="chart-card">
            <view class="chart-content">
                <view class="bar-chart-container">
                    <!-- 图表加载效果 -->
                    <ChartLoading v-if="isLoading" text="数据加载中..." />
                    <!-- 实际图表 -->
                    <QiunDataCharts v-else type="line" :opts="revenueChartOpts" :chartData="revenueChartData"
                        :canvas2d="true" :inScrollView="true" canvasId="revenueChart" :animation="false" :ontap="true"
                        :ontouch="true" tooltipFormat="revenueChartDataVehicles" />
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import QiunDataCharts from './qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
import ChartLoading from './ChartLoading.vue'
import request from "@/util/index.js";
import moment from 'moment'

export default {
    components: {
        QiunDataCharts,
        ChartLoading
    },

    data() {
        return {
            isLoading: false,
            // 图表数据
            chartData: {
                category: [],
                seriesDataCar: [],
                seriesDataRevenue: [],
                realDataCar: [],
                realDataRevenue: [],
                yesSeriesDataCar: [],
                yesSeriesDataRevenue: [],
                yesRealDataCar: [],
                yesRealDataRevenue: [],
                currentYear: '',
                yesYear: '',
                carAdd: [],
                revenueAdd: []
            }
        }
    },

    props: {
        selectTime: {
            type: String,
            default: ""
        },
    },

    computed: {
        // 检查是否有入区车流图表数据
        hasVehicleChartData() {
            return this.chartData.category && this.chartData.category.length > 0
        },

        // 检查是否有对客营收图表数据
        hasRevenueChartData() {
            return this.chartData.category && this.chartData.category.length > 0
        },

        // 入区车流图表数据
        vehicleChartData() {
            return {
                categories: this.chartData.category,
                series: [
                    {
                        name: `${this.chartData.currentYear}年车流量`,
                        data: this.chartData.seriesDataCar
                    },
                    {
                        name: `${this.chartData.yesYear}年车流量`,
                        data: this.chartData.yesSeriesDataCar
                    }
                ]
            }
        },

        // 入区车流图表配置
        vehicleChartOpts() {
            return {
                padding: [15, 0, 0, 10],
                dataLabel: false,
                // enableScroll: true, // 开启滚动
                xAxis: {
                    disableGrid: true,
                    itemCount: 12, // 默认显示6个月的数据
                    fontSize: 10
                },
                yAxis: {
                    showTitle: true,
                    data: [{
                        min: 0,
                        title: '入区车流(万辆)',
                        titleFontSize: 12,
                        titleOffsetY: -5,
                        titleOffsetX: 10,
                        splitNumber: 5
                    }]
                },
                legend: {},
                extra: {
                    column: {
                        type: 'group',
                        width: 6, // 柱子宽度调小一点
                        seriesGap: 0, // 同一组别的柱子紧贴在一起
                        barBorderRadius: [3, 3, 0, 0]
                    }
                }
            }
        },

        // 对客营收图表数据
        revenueChartData() {
            return {
                categories: this.chartData.category,
                series: [
                    {
                        name: `${this.chartData.currentYear}年交易额`,
                        data: this.chartData.seriesDataRevenue
                    },
                    {
                        name: `${this.chartData.yesYear}年交易额`,
                        data: this.chartData.yesSeriesDataRevenue
                    }
                ]
            }
        },
        // 对客营收图表配置
        revenueChartOpts() {
            return {
                padding: [15, 10, 0, 10],
                legend: {},
                dataLabel: false,
                dataPointShape: true,
                // enableScroll: true, // 开启滚动
                xAxis: {
                    disableGrid: true,
                    itemCount: 12, // 默认显示6个月的数据
                    fontSize: 10
                },
                yAxis: {
                    gridType: 'dash',
                    dashLength: 2,
                    showTitle: true,
                    data: [{
                        min: 0,
                        title: '对客营收(万元)',
                        titleFontSize: 12,
                        titleOffsetY: -5,
                        titleOffsetX: 10,
                        splitNumber: 5
                    }],
                    splitNumber: 5
                },
                extra: {
                    line: {
                        type: 'straight', // 改为直线，不要圆滑曲线
                        width: 2,
                        seriesGap: 0, // 同一组别的柱子紧贴在一起
                        activeType: 'hollow'
                    }
                }
            }
        }
    },

    watch: {
        selectTime: {
            handler(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.handleGetSectionFlowCount()
                }
            },
            immediate: false
        }
    },

    onReady() {
        this.handleGetSectionFlowCount()
    },

    methods: {
        // 获取入区车辆的趋势数据
        async handleGetSectionFlowCount() {
            this.isLoading = true
            // 当前年份数据请求
            const currentReq = {
                StartDate: this.selectTime ? moment(this.selectTime).startOf('y').format('YYYY-MM-DD') : moment().startOf('y').format('YYYY-MM-DD'),
                EndDate: this.selectTime ? moment(this.selectTime).endOf('M').format('YYYY-MM-DD') : moment().endOf('M').format('YYYY-MM-DD'),
                ProvinceCode: 530000
            }

            // 去年数据请求
            const lastYearReq = {
                StartDate: this.selectTime ? moment(this.selectTime).subtract(1, 'y').startOf('y').format('YYYY-MM-DD') : moment().subtract(1, 'y').startOf('y').format('YYYY-MM-DD'),
                EndDate: this.selectTime ? moment(this.selectTime).subtract(1, 'y').endOf('M').format('YYYY-MM-DD') : moment().subtract(1, 'y').endOf('M').format('YYYY-MM-DD'),
                ProvinceCode: 530000
            }

            console.log('currentReqcurrentReqcurrentReq1111', currentReq);
            console.log('lastYearReqlastYearReqlastYearReq222', lastYearReq);



            // 并行调用两个API
            const [currentData, lastYearData] = await Promise.all([
                this.getMonthAnalysis(currentReq),
                this.getMonthAnalysis(lastYearReq)
            ]);
            this.isLoading = false

            // 处理数据
            this.processChartData(currentData.Result_Data.List, lastYearData.Result_Data.List)
        },

        // 发起API请求获取月度分析数据
        async getMonthAnalysis(params) {
            const data = await request.$webGet(
                "CommercialApi/BigData/GetMonthAnalysis",
                params
            );
            return data || []
        },

        // 处理图表数据
        processChartData(currentData, lastYearData) {
            let category = []
            let seriesDataCar = []
            let seriesDataRevenue = []
            let realDataCar = []
            let realDataRevenue = []

            // 处理当前年份数据
            if (currentData && currentData.length > 0) {
                currentData.forEach((item) => {
                    const month = item.Statistics_Month < 10 ? item.Statistics_Month : item.Statistics_Month
                    category.push(`${month}月`)
                    seriesDataCar.push(Number((item.Vehicle_Count / 10000).toFixed(2)))
                    realDataCar.push(item.Vehicle_Count)
                    seriesDataRevenue.push(Number((item.RevenueAmount / 10000).toFixed(2)))
                    realDataRevenue.push(item.RevenueAmount)
                })
            }

            let yesSeriesDataCar = []
            let yesSeriesDataRevenue = []
            let yesRealDataCar = []
            let yesRealDataRevenue = []

            // 处理去年数据
            if (lastYearData && lastYearData.length > 0) {
                lastYearData.forEach((item) => {
                    yesSeriesDataCar.push(Number((item.Vehicle_Count / 10000).toFixed(2)))
                    yesSeriesDataRevenue.push(Number((item.RevenueAmount / 10000).toFixed(2)))
                    yesRealDataCar.push(item.Vehicle_Count)
                    yesRealDataRevenue.push(item.RevenueAmount)
                })
            }

            // 计算增长率
            let carAdd = []
            let revenueAdd = []
            if (category && category.length > 0) {
                for (let i = 0; i < category.length; i++) {
                    let currentCar = realDataCar[i] || 0
                    let yesCar = yesRealDataCar[i] || 0
                    let add = ''
                    if (currentCar > 0 && yesCar > 0) {
                        add = (((currentCar - yesCar) / yesCar) * 100).toFixed(2)
                    }
                    carAdd.push(add)

                    let currentRevenue = realDataRevenue[i] || 0
                    let yesRevenue = yesRealDataRevenue[i] || 0
                    let addRenvenue = ""
                    if (currentRevenue > 0 && yesRevenue > 0) {
                        addRenvenue = (((currentRevenue - yesRevenue) / yesRevenue) * 100).toFixed(2)
                    }
                    revenueAdd.push(addRenvenue)
                }
            }

            // 更新图表数据
            this.chartData = {
                category: category,
                seriesDataCar: seriesDataCar,
                seriesDataRevenue: seriesDataRevenue,
                realDataCar: realDataCar,
                realDataRevenue: realDataRevenue,
                yesSeriesDataCar: yesSeriesDataCar,
                yesSeriesDataRevenue: yesSeriesDataRevenue,
                yesRealDataCar: yesRealDataCar,
                yesRealDataRevenue: yesRealDataRevenue,
                currentYear: moment().format('YYYY'),
                yesYear: moment().subtract(1, 'y').format('YYYY'),
                carAdd: carAdd,
                revenueAdd: revenueAdd
            }

        },

    }
}
</script>

<style scoped lang="less">
@primary-color: #46B8F3;
@secondary-color: #3CD495;
@danger-color: #FF5E5E;
@success-color: #52C41A;
@text-primary: #333;
@text-secondary: #666;
@text-light: #999;
@bg-white: #ffffff;
@border-radius: 16rpx;
@shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

.vehicles-entering {
    margin-top: 24rpx;

    .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;
        padding: 0 8rpx;

        .section-title {
            font-size: 30rpx;
            font-weight: 600;
            color: @text-primary;
        }
    }

    .chart-container {
        background: @bg-white;
        border-radius: @border-radius;
        padding: 24rpx;
        box-shadow: @shadow;
        margin-bottom: 24rpx;
        width: 100%;
        box-sizing: border-box;
        height: 400rpx;
    }

    .chart-card {
        background: @bg-white;
        border-radius: @border-radius;
        padding: 24rpx;
        box-shadow: @shadow;
        margin-bottom: 24rpx;



        .chart-content {
            .bar-chart-container {
                width: 100%;
                height: 400rpx;
            }
        }
    }
}
</style>