<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue'
import './PrivateRideService.less'
import { onMounted, onBeforeUnmount, ref } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import moment from 'moment';
import { handleGetRevenueCompare } from '../../service';

// 注册组件
echarts.use([
    LineChart,
    GridComponent,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    CanvasRenderer
]);

let myChart: echarts.ECharts;
// 季月年的选中
let selectType = ref<number>(3)


onMounted(async () => {

    const res: any = await handleGetData()

    const chartDom = document.getElementById('PrivateRideService');
    if (!chartDom) return;

    myChart = echarts.init(chartDom);

    const option = {
        legend: {
            top: ['今年', '去年'],
            bottom: 0,
            textStyle: {
                color: '#666',
                fontSize: 12,
                fontWeight: 'bold'
            },
            itemGap: 20,
            itemWidth: 12,
            itemHeight: 12,
            icon: 'circle', // 图例图标类型
            selectedMode: true, // 允许点击图例切换系列显示/隐藏
            padding: [5, 10, 5, 10], // 图例内边距
        },
        xAxis: {
            type: 'category',
            data: res.category,
            boundaryGap: true,

        },
        yAxis: {
            type: 'value',
            splitLine: { show: false }  // 隐藏刻度线
        },
        grid: {
            left: '10',    // 左侧间距
            right: '10',   // 右侧间距
            bottom: '0',    // 底部间距
            top: '10',       // 顶部间距
            containLabel: true // 确保坐标轴标签在grid内
        },
        series: [
            {
                name: "今年",
                data: res.seriesData.map((value: any, index: any) => {
                    return {
                        value: value,
                        // 只在显示标签的位置显示symbol
                        symbol: index % 3 === 0 ? 'circle' : 'none',
                        symbolSize: 6
                    }
                }),
                realData: res.realData,
                type: 'line',
                smooth: true,
                color: '#00FFFF'
            },
            {
                name: "去年",
                data: res.seriesDataSecond.map((value: any, index: any) => {
                    return {
                        value: value,
                        // 只在显示标签的位置显示symbol
                        symbol: index % 3 === 0 ? 'circle' : 'none',
                        symbolSize: 6
                    }
                }),
                realData: res.realData,
                type: 'line',
                smooth: true,
                color: '#FF307C'
            }
        ],
        tooltip: {  // 新增 tooltip 配置
            trigger: 'axis',  // 触发类型：坐标轴触发
            axisPointer: {    // 坐标轴指示器配置
                type: 'shadow' // 阴影指示器（适合柱状图）
            },
            formatter: function (params: any) {  // 自定义提示框内容
            }
        },
    };


    myChart.setOption(option);
    myChart.resize();
    window.addEventListener('resize', resizeChart);
})

// 拿到数据的方法
const handleGetData = async () => {

    let startTime: string = ''
    let endTime: string = ''
    // 去年
    let startTime_LY: string = ''
    let endTime_LY: string = ''

    if (selectType.value === 1) {
        startTime = moment().subtract(1, 'd').startOf('M').format('YYYY/MM/DD')
        endTime = moment().subtract(1, 'd').format('YYYY/MM/DD')
        startTime_LY = moment().subtract(1, 'y').subtract(1, 'd').startOf('M').format('YYYY/MM/DD')
        endTime_LY = moment().subtract(1, 'y').subtract(1, 'd').format('YYYY/MM/DD')
    } else if (selectType.value === 2) {
        startTime = moment().clone().startOf('quarter').format('YYYY-MM-DD');
        endTime = moment().clone().endOf('quarter').format('YYYY-MM-DD');
        startTime_LY = moment().subtract(1, 'd').subtract(1, 'y').clone().startOf('quarter').format('YYYY-MM-DD');
        endTime_LY = moment().subtract(1, 'd').subtract(1, 'y').clone().endOf('quarter').format('YYYY-MM-DD');
    } else if (selectType.value === 3) {
        startTime = moment().subtract(1, 'd').startOf('y').format('YYYY/MM/DD')
        endTime = moment().subtract(1, 'd').format('YYYY/MM/DD')
        startTime_LY = moment().subtract(1, 'd').subtract(1, 'y').startOf('y').format('YYYY/MM/DD')
        endTime_LY = moment().subtract(1, 'y').subtract(1, 'd').format('YYYY/MM/DD')
    }

    const req: any = {
        action_type: "RevenueCompare",
        province_code: 5564,
        action_data: `${startTime}|${endTime}`,
        action_record: `${startTime_LY}|${endTime_LY}`,
    }

    console.log('请求参数:', req)
    const data = await handleGetRevenueCompare(req)
    console.log('服务私乘数据:', data);

    let list: any = data.RevenueCompareObject

    let category: string[] = []
    // y轴的数据
    let seriesData: number[] = []
    // y轴的数据(第二个)
    let seriesDataSecond: number[] = []
    let realData: string[] = []

    if (list && list.length > 0) {
        list.forEach((item: any) => {
            category.push(moment(item.ENDACCOUNT_DATE).format('MM-DD'))
            seriesData.push(item.TOTALPRICE)
            seriesDataSecond.push(item.TOTALPRICE_LY)
        })
    }


    let res: any = {
        category: category,// x轴的内容
        seriesData: seriesData,// y轴的数据
        seriesDataSecond: seriesDataSecond, // y轴的数据(第二个)
        realData: realData// 真实数据
    }
    return res
}

const resizeChart = () => {
    myChart?.resize();
};

// 修改选择的季月年
const handleChangeType = async (value: number) => {
    selectType.value = value
    handleGetData()
}

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
    myChart?.dispose();
});


</script>

<template>
    <div class="PrivateRideServiceBox">
        <SmallTitle :title="'服务私乘'">
            <template #extra>
                <!-- 本月 本季 本年 -->
                <div class="changeTypeBox">
                    <div :class="selectType === 1 ? 'changeTypeItem selectChangeTypeItem' : 'changeTypeItem'"
                        @click="handleChangeType(1)">月</div>
                    <div :class="selectType === 2 ? 'changeTypeItem selectChangeTypeItem' : 'changeTypeItem'"
                        @click="handleChangeType(2)">季</div>
                    <div :class="selectType === 3 ? 'changeTypeItem selectChangeTypeItem' : 'changeTypeItem'"
                        @click="handleChangeType(3)">年</div>
                </div>
            </template>

        </SmallTitle>

        <div class="PrivateRideServiceCharts">
            <div class="PrivateRideService" id="PrivateRideService"></div>
        </div>
    </div>
</template>