<script setup lang="ts">
import SmallTitle from '../smallTitle/smallTitle.vue'
import './PassengerFlowChanges.less'
import { onMounted, onBeforeUnmount, watch, 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 { handleGetTransactionConvert, handleGetTransactionTimeAnalysis } from '../../service';

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

let myChart: echarts.ECharts;
// 当前查询的时间
let searchTime = ref<string>()

onMounted(async () => {
  await handleGoMounted()
})

// 传入的数据
const props = defineProps<{
  currentService?: any;
}>();

// 监听传入的选中服务区
watch(
  () => props.currentService,
  (newVal, oldVal) => {
    handleGoMounted()
  },
  { deep: true }
);

// 初始运行的方法
const handleGoMounted = async () => {
  const res: any = await handleGetData()

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

  myChart = echarts.init(chartDom);

  const option = {
    xAxis: {
      type: 'category',
      data: res.category,
      // boundaryGap: true,
      axisLabel: {
        interval: 3,
        showMinLabel: true,
        showMaxLabel: true
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '车流量',
        splitLine: { show: false },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#FFFFFF'
          }
        },
        axisLabel: {
          formatter: '{value}' // 添加单位
        },
        nameTextStyle: {
          color: '#666',
          padding: [0, 0, 0, 30]  // 调整单位位置
        }
      },
      {
        type: 'value',
        name: '客单量',
        splitLine: { show: false },
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#FFFFFF'
          }
        },
        axisLabel: {
          formatter: '{value}' // 添加单位
        },
        nameTextStyle: {
          color: '#666',
          padding: [0, 0, 0, 30]  // 调整单位位置
        },
        offset: 0 // 确保Y轴紧贴图表
      }
    ],
    grid: {
      left: '10',    // 增加左侧空间
      right: '10',   // 增加右侧空间
      bottom: '10',
      top: '30',
      containLabel: true
    },
    series: [
      {
        name: '车流量',
        data: res.carData.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'
        },
        yAxisIndex: 0 // 绑定左侧Y轴
      },
      {
        name: '客单量',
        data: res.customerOrderList.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' // 改为橙色
        },
        yAxisIndex: 1 // 绑定右侧Y轴
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line' // 改为线条指示器
      },
      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.carRealList[param.dataIndex] : res.customerOrderRealList[param.dataIndex]
          tip += `<div>${param.seriesName}: ${value ? value.toLocaleString() : ''}${unit}</div>`;
        });
        return tip;
      }
    }
  };

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

}

// 拿到数据的方法
const handleGetData = async () => {
  const req: any = {
    Province_Code: "530000",
    Statistics_Date: moment().subtract(1, 'd').format('YYYY-MM-DD'),
    Serverpart_ID: props.currentService?.SERVERPART_ID || "",
    TimeSpan: 1
  }

  searchTime.value = moment(req.Statistics_Date).format('MM')

  const data = await handleGetTransactionConvert(req)

  console.log('fhdusyfusahfjsdh', data);

  // 客单数据
  let customerOrder = data.TransactionList

  // 车流数据
  let carData = data.BayonetList
  let category: string[] = []


  let customerOrderList: number[] = []
  let customerOrderRealList: number[] = []
  if (customerOrder.data && customerOrder.data.length > 0) {
    customerOrder.data.forEach((item: any, index: number) => {
      category.push(`${index < 10 ? '0' + index : index}:00`)
      // customerOrderList.push(Number((item[1] / 10000).toFixed(2)))
      customerOrderList.push(item[1])
      customerOrderRealList.push(item[1])
    })
  }

  let carList: number[] = []
  let carRealList: number[] = []
  if (carData.data && carData.data.length > 0) {
    carData.data.forEach((item: any) => {
      // carList.push(Number((item[1] / 10000).toFixed(2)))
      carList.push(item[1])
      carRealList.push(item[1])
    })
  }

  let res: any = {
    category: category,// x轴的内容
    carData: carList,// y轴的数据
    customerOrderList: customerOrderList,// y轴的数据
    carRealList: carRealList,
    customerOrderRealList: customerOrderRealList
    // realData: realData// 真实数据
  }

  console.log('fjioadhgasdhnfjks', res);


  return res


  // return

  // let category: string[] = []
  // let seriesData: number[] = []
  // let realData: string[] = []

  // if (data && data.length > 0) {
  //   data.forEach((item: any, index: number) => {
  //     category.push(`${index < 10 ? '0' + index : index}:00`)
  //     // data 是客单数  key 是消费金额
  //     seriesData.push(item.data)
  //     realData.push(Number(item.data).toLocaleString())
  //   })
  // }
  // let res: any = {
  //   category: category,// x轴的内容
  //   seriesData: seriesData,// y轴的数据
  //   realData: realData// 真实数据
  // }
  // return res
}


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

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


</script>

<template>
  <div class="PassengerFlowChangesBox">
    <SmallTitle :title="`客流变化${searchTime ? `(${searchTime}月)` : ''}`"></SmallTitle>

    <div class="PassengerFlowChangesCharts" style="margin-top:15px">
      <!-- <div class="PassengerFlowChangesUnit"
        style="width: 100%;display: flex;align-items: center;justify-content: space-between;">
        <span>辆</span>
        <span>单</span>
      </div> -->
      <div class="PassengerFlowChanges" id="PassengerFlowChanges"></div>
    </div>
  </div>
</template>