<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import SmallTitle from '../smallTitle/smallTitle.vue'
import './TodayTrend.less'
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 onlineService from '../../../../assets/image/onlineService.png'
import onlineCashRegister from '../../../../assets/image/onlineCashRegister.png'
import { handleGetCurrentCount, handleGetRevenueTrendChart, handleGetTodaysTrend } from '../../service';
import { handleGetFiveNumber } from '../../../../options/serveice';

// 季月年的选中
let selectType = ref<number>(1)

// 在营服务区
let onlineServiceValue = ref<any>({
    paddedPart: "",
    originalNum: "0"
})
// 在营收银机
let onlineCashRegisterValue = ref<any>({
    paddedPart: "",
    originalNum: "0"
})

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

let myChart: echarts.ECharts;

onMounted(async () => {

    // handleGetOnlineData()

    const res: any = await handleGetData()

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

    myChart = echarts.init(chartDom);

    const option = {
        legend: {
            textStyle: {
                color: '#fff' // 设置图例文字颜色为白色，与你的主题一致
            },
            top: 0, // 图例位置在顶部
            right: 0
        },
        xAxis: {
            type: 'category',
            data: res.category,
            // boundaryGap: true,
            axisLabel: {
                interval: 3,
                showMinLabel: true,
                showMaxLabel: true
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#fff'
                }
            },
            axisTick: {
                alignWithLabel: true // 保证刻度线与标签对齐
            }
        },
        yAxis: [
            {
                type: 'value',
                name: '营收(元)',
                nameTextStyle: {
                    color: '#fff',
                    padding: [0, 30, 0, 0]  // 调整单位位置

                },
                splitLine: { show: false },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#fff'
                    }
                }
            },
            {
                type: 'value',
                name: '客单(笔)',
                nameTextStyle: {
                    color: '#fff',
                    padding: [0, 0, 0, 10]  // 调整单位位置
                },
                splitLine: { show: false },
                position: 'right',
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: '#fff'
                    }
                },
            }
        ],
        grid: {
            left: '10',
            right: '10',
            bottom: '10',
            top: '50',
            containLabel: true
        },
        series: [
            {
                name: '营收',
                data: res.seriesData.map((value: any, index: any) => ({
                    value: value,
                    symbol: index % 3 === 0 ? 'circle' : 'none',
                    symbolSize: 6
                })),
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 2,
                    color: '#00FFFF'
                },
                itemStyle: {
                    color: '#00FFFF'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(0, 255, 255, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(0, 255, 255, 0.1)'
                        }
                    ])
                },
                yAxisIndex: 0
            },
            {
                name: '客单',
                data: res.seriesDataSecond.map((value: any, index: any) => ({
                    value: value,
                    symbol: index % 3 === 0 ? 'circle' : 'none',
                    symbolSize: 6
                })),
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 2,
                    color: '#FFA500'
                },
                itemStyle: {
                    color: '#FFA500'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(255, 165, 0, 0.3)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(255, 165, 0, 0.1)'
                        }
                    ])
                },
                yAxisIndex: 1
            }
        ],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
                snap: true, // 关键点：启用吸附
                lineStyle: {
                    color: '#FFF', // 可选：调整竖线颜色
                    width: 1
                }
            },
            formatter: function (params: any) {
                let tip = `<div style="font-weight:bold">${params[0].name}</div>`;
                params.forEach((param: any) => {
                    const unit = param.seriesName === '营收' ? '元' : '单';
                    let value = param.seriesName === '营收' ? res.seriesData[param.dataIndex] : res.seriesDataSecond[param.dataIndex]
                    tip += `<div>${param.seriesName}: ${value ? value.toLocaleString() : ''}${unit}</div>`;
                });

                return tip
            }
        }
    };

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

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

// 拿到图表数据
const handleGetData = async () => {
    // x轴
    let category: string[] = []
    // y轴
    let seriesData: number[] = []
    // y轴2
    let seriesDataSecond: number[] = []
    let realData: string[] = []

    // const req: any = {
    //     action_type: "getDataCollect",
    //     province_code: 5564
    // }

    // const data = await handleGetTodaysTrend(req)

    // let list: any = data.CollectionObject

    // if (list && list.length > 0) {
    //     list.forEach((item: any) => {
    //         category.push(`${item.DATACOLLECTION_DATE}:${item.HALFTYPE}`)
    //         seriesData.push(Number(item.TOTALSELL_AMOUNT))
    //         seriesDataSecond.push(Number(item.TICKET_COUNT))
    //     })
    // }


    const req: any = {
        ProvinceCode: 530000,
        ServerpartId: ""
    }
    const data = await handleGetRevenueTrendChart(req)

    console.log('dadasdashandleGetRevenueTrendChart', data);


    if (data && data.length > 0) {
        data.forEach((item: any) => {
            category.push(`${item.TradeDate.substring(0, 2) + ":" + item.TradeDate.substring(2)}`)
            seriesData.push(Number(item.TotalAmount))
            seriesDataSecond.push(Number(item.TicketCount))
        })
    }

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

// 拿到在线服务区  和 在营收银机
const handleGetOnlineData = async () => {
    const req: any = {
        action_type: "GetCurrentCount",
        province_code: 5564
    }

    const data = await handleGetCurrentCount(req)
    let res: any = data.CurrentData[0]


    onlineServiceValue.value = handleGetFiveNumber(res.SERVERPARTCOUNT)
    onlineCashRegisterValue.value = handleGetFiveNumber(res.MACHINECOUNT)
}

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

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

</script>


<template>
    <div class="TodayTrendBox">
        <SmallTitle :title="`今日走势图(${moment().format('YYYY-MM-DD')})`" style="margin-top: 13px;"></SmallTitle>

        <!-- <div class="TodayTrendUnit">
            <span>元</span>
            <span>单</span>
        </div> -->
        <div class="TodayTrendContent">
            <div class="TodayTrend" id="TodayTrend"></div>
        </div>

        <!-- <div class="onlineServiceBox">
            <div class="onlineServiceItem">
                <div class="onlineServiceItemLeft">
                    <img class="onlineServiceItemImg" :src="onlineService" />
                </div>

                <div class="onlineServiceItemRight">
                    <div class="onlineServiceItemRightTop">在线服务区</div>
                    <div class="onlineServiceItemRightBottom">
                        <div class="onlineServiceItemBottomLeft">
                            <span style="color: #455062;">{{ onlineServiceValue.paddedPart }}</span>
                            <span>{{ onlineServiceValue.originalNum }}</span>
                        </div>
                        <div class="onlineServiceItemBottomUnit">个</div>
                    </div>
                </div>
            </div>
            <div class="onlineServiceItem">
                <div class="onlineServiceItemLeft">
                    <img class="onlineServiceItemImg" :src="onlineCashRegister" />
                </div>

                <div class="onlineServiceItemRight">

                    <div class="onlineServiceItemRightTop">在线收银机</div>
                    <div class="onlineServiceItemRightBottom">
                        <div class="onlineServiceItemBottomLeft">
                            <span style="color: #455062;">{{ onlineCashRegisterValue.paddedPart }}</span>
                            <span>{{ onlineCashRegisterValue.originalNum }}</span>
                        </div>
                        <div class="onlineServiceItemBottomUnit">个</div>
                    </div>
                </div>
            </div>
        </div> -->
    </div>
</template>