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

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

let myChart: echarts.ECharts;

onMounted(async () => {

    const res: any = await handleGetSectionFlowCount()

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


    myChart = echarts.init(chartDom);

    const option = {
        tooltip: { // 新增 tooltip 配置
            trigger: 'item',
            formatter: function (params: any) {
                console.log('params', params);
                let str: string = `<div>${params?.seriesName}：</div>`
                for (let i = 0; i < res.category.length; i++) {
                    str += `<div>${res.category[i].name}：${params.value[i]}%</div>`
                    // list.push({ label: res.category[i], value: params.value + '%' })
                }
                return `<div>${str}</div>
            `;
            }
        },
        radar: {
            indicator: res.category,
            shape: 'circle',
            splitNumber: 5,
            radius: '40%', // 调整雷达图大小，留出空间给文字
            center: ['50%', '45%'], // 2. 确保居中
            axisName: {
                color: 'rgb(255, 255, 255)',
                padding: 10
            },
            splitLine: {
                lineStyle: {
                    color: [
                        'rgba(25, 46, 76, 1)',
                        'rgba(25, 46, 76, 1)',
                        'rgba(25, 46, 76, 1)',
                        'rgba(25, 46, 76, 1)',
                        'rgba(25, 46, 76, 1)',
                        'rgba(25, 46, 76, 1)',
                    ]
                }
            },
            splitArea: {
                show: false
            },
            axisLine: {
                lineStyle: {
                    color: 'rgba(25, 46, 76, 1)',
                }
            }
        },
        series: [
            {
                name: "男性",
                type: 'radar',
                lineStyle: {
                    width: 1,
                    opacity: 0.5
                },
                data: res.seriesData,
                symbol: 'none',
                itemStyle: {
                    color: '#0094FF'
                },
                areaStyle: {
                    opacity: 0.1
                }
            },
            {
                name: "女性",
                type: 'radar',
                lineStyle: {
                    width: 1,
                    opacity: 0.5
                },
                data: res.seriesDataMan,
                symbol: 'none',
                itemStyle: {
                    color: '#FF5E5E'
                },
                areaStyle: {
                    opacity: 0.1
                }
            }
        ],
        legend: {
            data: ['男性', '女性'],
            textStyle: {
                color: '#fff'
            },
            bottom: -5,
            left: 'center',
        },
    };

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

// 拿到业态偏好数据
const handleGetSectionFlowCount = async () => {

    const req: any = {
        // ProvinceCode: '530000',
        // StatisticsDate: moment(moment().subtract(1, 'M')).format('YYYY-MM-DD'),
        // BusinessTradeIds: -1
        statisticsType: 1,
        startMonth: moment().startOf('y').format('YYYYMM'),
        endMonth: moment().format('YYYYMM'),
        provinceCode: '530000',
        showTradeLevel: 1,
        fromRedis: true

    }

    let PreferenceType = sessionStorage.getItem('PreferenceType')
    let data: any = []
    if (PreferenceType) {
        data = JSON.parse(PreferenceType)
    } else {
        data = await handleGetCustomerSaleRatio(req)
        sessionStorage.setItem("PreferenceType", JSON.stringify(data))
    }

    // const data = await handleGetBusinessTradeRevenue(req)

    let category: any = []
    // 男
    let seriesData: any = []
    let realData: any = []
    // 女
    let seriesDataMan: any = []
    let realDataMan: any = []
    let aiObj: any = {}

    let max: number = 0
    // let list: any = data.BusinessTradeRank
    let list: any = data.CustomerSaleList
    if (list && list.length > 0) {
        list.forEach((item: any) => {

            if (item.FemaleRatio > max) {
                max = item.FemaleRatio
            }
            if (item.MaleRatio > max) {
                max = item.MaleRatio
            }

            category.push({ name: `${item.BusinessTradeName}`, max: 100 })
            seriesData.push(Number(item.FemaleRatio))
            realData.push(item.FemaleRatio)

            seriesDataMan.push(Number(item.MaleRatio))
            realDataMan.push(item.MaleRatio)


            aiObj[item.BusinessTradeName + '男性'] = item.FemaleRatio + '%'
            aiObj[item.BusinessTradeName + '女性'] = item.MaleRatio + '%'

            // category.push({ name: `${item.name}：${item.value}%`, max: 100 })
            // seriesData.push(Number(item.value))
            // realData.push(item.data)
            // aiObj[item.name] = item.value + '%'
        })
    }

    if (category && category.length > 0) {
        category.forEach((item: any) => {
            item.max = max
        })
    }

    let res: any = {
        category: category,// x轴的内容
        seriesData: [seriesData],// y轴的数据
        realData: realData,// 真实数据
        seriesDataMan: [seriesDataMan],
        realDataMan: realDataMan,
    }


    console.log('resresresres', res);


    let PreferenceTypeAI = sessionStorage.getItem('PreferenceTypeAI')
    if (PreferenceTypeAI) { } else {
        sessionStorage.setItem("PreferenceTypeAI", JSON.stringify(aiObj))
    }

    return res
}


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

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

</script>




<template>
    <div class="PreferenceTypeBox">
        <SmallTitle :title="'偏好类型'" :pageType="'center'"></SmallTitle>

        <div class="PreferenceTypeCharts">
            <!-- <div class="PreferenceTypeUnit">万元</div> -->
            <div class="PreferenceTypeChartsContent">
                <div class="PreferenceType" id="PreferenceType"></div>
            </div>
        </div>
    </div>
</template>