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

        <!-- 入区车流图表 -->
        <view class="chart-container">
            <QiunDataCharts type="column" :opts="vehicleChartOpts" :chartData="vehicleChartData" :canvas2d="true"
                :inScrollView="true" canvasId="vehicleChart" :animation="false" :ontap="true" :ontouch="true"
                tooltipFormat="vehicleChartData" />
        </view>

        <!-- 对客营收标题 -->
        <view class="section-header">
            <text class="section-title">对客营收</text>
        </view>

        <!-- 对客营收图表 -->
        <view class="chart-container">
            <QiunDataCharts type="line" :opts="revenueChartOpts" :chartData="revenueChartData" :canvas2d="true"
                :inScrollView="true" canvasId="revenueChart" :animation="false" :ontap="true" :ontouch="true"
                tooltipFormat="revenueChartDataVehicles" />
        </view>
    </view>
</template>

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

export default {
    components: {
        QiunDataCharts
    },

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

    computed: {
        // 入区车流图表数据
        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, 15, 0, 5],
                dataLabel: false,
                enableScroll: true, // 开启滚动
                xAxis: {
                    disableGrid: true,
                    itemCount: 6, // 默认显示6个月的数据
                    scrollShow: true, // 显示滚动条
                    scrollAlign: 'left', // 滚动条对齐方式
                    scrollColor: '#46B8F3', // 滚动条颜色
                    scrollWidth: 4, // 滚动条宽度
                    scrollHeight: 8 // 滚动条高度
                },
                yAxis: {
                    data: [{
                        min: 0,
                        title: '万辆',
                    }]
                },
                extra: {
                    column: {
                        type: 'group',
                        width: 12, // 柱子宽度调小一点
                        activeBgColor: '#000000',
                        activeBgOpacity: 0.08,
                        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, 15],
                legend: {},
                dataLabel: false,
                dataPointShape: true,
                enableScroll: true, // 开启滚动
                xAxis: {
                    disableGrid: true,
                    scrollShow: true, // 显示滚动条
                    scrollAlign: 'left', // 滚动条对齐方式
                    itemCount: 6, // 默认显示6个月的数据
                    scrollWidth: 4, // 滚动条宽度
                    scrollHeight: 8 // 滚动条高度
                },
                yAxis: {
                    gridType: 'dash',
                    dashLength: 2,
                    data: [{
                        min: 0,
                        title: '万元',
                        titleFontSize: 12,
                        titleOffsetY: -4,
                        titleOffsetX: 0
                    }],
                    splitNumber: 5
                },
                extra: {
                    line: {
                        type: 'straight', // 改为直线，不要圆滑曲线
                        width: 2,
                        activeType: 'hollow'
                    },
                    tooltip: {
                        showBox: true,
                        bgColor: '#000000',
                        bgOpacity: 0.7,
                        borderColor: '#333333',
                        borderWidth: 1
                    }
                }
            }
        }
    },

    onReady() {
        this.handleGetSectionFlowCount()
    },

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

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

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

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

        // 发起API请求获取月度分析数据
        async getMonthAnalysis(params) {
            const data = await request.$webGet(
                "CommercialApi/BigData/GetMonthAnalysis",
                params
            );
            console.log('入区车流数据', data);
            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 ? '0' + 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
            }

            console.log('处理后的图表数据', this.chartData)
        },

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