import React, { useEffect, useState, useRef } from 'react';
// import aa from '@/assets/images/icon/形状.png';
import aa from '@/assets/images/图标.png';
import bb from '@/assets/images/图标1.png';
import cc from '@/assets/images/图标2.png';
import dd from '@/assets/images/图标3.png';
import * as echarts from 'echarts';
import { salesStatistics } from './request';

const OrderSalesStatistics = () => {
  // 在组件内部定义 refs
  const totalSalesAmountRef = useRef(null);
  const teacherPerformanceRef = useRef(null);
  const bookPerformanceRef = useRef(null);

  const sale = (data) => {
    const xAxisData = data.map((item) => item.month);
    const seriesData = data.map((item) => item.price);

    const saleOption = {
      title: {
        text: '销售总金额（元）/月',
        left: 'left',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },

        // formatter: function (params) {
        //   console.log('params', params);

        //   if (params[0].data == '0.00') {
        //     return '暂无数据';
        //   } else {
        //     return params[0].name + '月' + '<br/>' + params[0].value.toFixed(2) + '元';
        //   }
        // },

        formatter: function (params) {
          console.log('params', params);

          if (typeof params[0].data === 'string' && params[0].data === '0.00') {
            return '暂无数据';
          } else if (typeof params[0].value === 'number') {
            return params[0].name + '月' + '<br/>' + params[0].value.toFixed(2) + '元';
          } else if (typeof params[0].value === 'string') {
            const valueAsNumber = parseFloat(params[0].value);
            if (isNaN(valueAsNumber)) {
              return '数据异常';
            } else {
              return params[0].name + '月' + '<br/>' + valueAsNumber.toFixed(2) + '元';
            }
          } else {
            return '数据格式错误';
          }
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true,
          },
          axisLabel: {
            interval: 0, // 强制显示所有标签
            formatter: function (value, index) {
              // 仅显示 1、3、5、7、9、11 月的标签
              if ((index + 1) % 2 !== 0) {
                return value + '月';
              } else {
                return '';
              }
            },
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          splitLine: {
            show: false, // 取消 y 轴的横线
          },
        },
      ],
      series: [
        {
          name: 'Direct',
          type: 'bar',
          barWidth: '60%',
          data: seriesData,
          itemStyle: {
            color: '#d48ca0',
          },
        },
      ],
    };
    const saleEchart = echarts.init(document.getElementById('totalSalesAmount'));
    saleEchart.setOption(saleOption);
  };
  const teachers = (data) => {
    const seriesData = data.map((item) => ({
      name: item.teacher_name,
      value: item.price.replace(',', ''),
    }));

    const option = {
      title: {
        text: '老师业绩分布TOP10',
        left: 'left',
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          return `<div style="display: flex; align-items: center;">
                  <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
                  <span style="color: ${params.color}">老师名称</span> : ${params.name}。 <br/>               
                </div>
                
                <div style="display: flex; align-items: center;">
                  <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
                  <span style="color: ${params.color}">老师业绩</span> : ${params.value} 元。 
                </div>`;
        },
      },
      legend: {
        orient: 'vertical', // 将图例位置纵向展示
        top: '5%', // 调整 top 属性的值，控制图例位置
        itemStyle: {
          color: seriesData.length === 0 ? '#d3d3d3' : 'auto', // 根据seriesData的长度设置图例颜色
        },
        itemHeight: 20, // 设置图例的高度
        height: 20,
      },
      series: [
        {
          name: '暂无数据',
          type: 'pie',
          radius: '50%',
          data: [...seriesData],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(211, 211, 211)',
            },
          },
          labelLine: {
            show: false,
          },
          label: {
            // 添加label属性，在formatter函数中获取price和ratio
            // formatter: function (params) {
            //   const { price, ratio } = data[params.dataIndex];
            //   return `${params.name} ${(ratio * 100).toFixed(2)}%`;
            // },

            formatter: function (params) {
              const { price, ratio } = data[params.dataIndex];
              const name =
                params.name.length > 10
                  ? `${params.name.slice(0, 10)}\n${params.name.slice(10)}`
                  : params.name; // 控制名字长度，超过10个字符换行
              return `${name} ${(ratio * 100).toFixed(2)}%`;
            },
            // rich: {
            //   name: {
            //     lineHeight: 20, // 控制每行的行高
            //   },
            // },
          },
        },
      ],
    };

    const teacherEchart = echarts.init(document.getElementById('teacherPerformance'));
    teacherEchart.setOption(option);
  };

  const books = (data) => {
    const seriesData = data.map((item) => ({
      name: item.book_name,
      value: item.price,
    }));

    const option = {
      title: {
        text: '书籍业绩分布TOP10',
        left: 'left',
      },
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          return `<div style="display: flex; align-items: center;">
          <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
          <span style="color: ${params.color}">书籍名称</span> : ${params.name}。 <br/>               
        </div>
        
        <div style="display: flex; align-items: center;">
          <div style="width: 10px; height: 10px; border-radius: 50%; background-color: ${params.color}; margin-right: 10px;"></div>
          <span style="color: ${params.color}">书籍价格</span> : ${params.value} 元。 
        </div>`;
        },
      },
      grid: {
        left: 'center',
        right: 'center',
        top: 'center',
        bottom: 'center',
      },
      legend: {
        orient: 'vertical', // 将 orient 设置为 'horizontal'
        top: '5%', // 调整 top 属性的值，控制图例位置

        itemStyle: {
          color: seriesData.length === 0 ? '#d3d3d3' : 'auto', // 根据seriesData的长度设置图例颜色
        },
        itemHeight: 20, // 设置图例的高度
        height: 20,
      },
      series: [
        {
          name: '暂无数据',
          type: 'pie',
          radius: '68%',
          center: ['50%', '50%'],
          clockwise: false,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(211, 211, 211)',
            },
          },
          data: seriesData,
          label: {
            // 添加label属性，在formatter函数中获取price和ratio
            // formatter: function (params) {
            //   const { price, ratio } = data[params.dataIndex];
            //   return `${params.name} ${(ratio * 100).toFixed(2)}%`;
            // },
            formatter: function (params) {
              const { price, ratio } = data[params.dataIndex];
              const name =
                params.name.length > 10
                  ? `${params.name.slice(0, 10)}\n${params.name.slice(10)}`
                  : params.name; // 控制名字长度，超过10个字符换行
              return `${name} ${(ratio * 100).toFixed(2)}%`;
            },
          },
          labelLine: {
            //取消选中饼图后往外指的小横线
            normal: {
              show: false,
            },
          },
          itemStyle: {
            //饼图之间的间距
            normal: {
              borderWidth: 4,
              borderColor: '#ffffff',
            },
            emphasis: {
              borderWidth: 0,
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
      color: ['#00acee', '#52cdd5', '#79d9f1', '#a7e7ff', '#c8efff'],
      backgroundColor: '#fff',
    };

    const bookEchart = echarts.init(document.getElementById('bookPerformance'));
    bookEchart.setOption(option);
  };

  const [tabArr, setTabArr] = useState([]);
  const [type, setType] = useState('');

  const initAllEcharts = async () => {
    const data = await salesStatistics();
    let { salesAmount, teacher, book, order_num, buy_num, average, income } = data;
    setType(data.type);

    // 添加延迟来等待DOM元素准备就绪
    await new Promise((resolve) => setTimeout(resolve, 100));
    if (data.type === 2) {
      sale(salesAmount);
      books(book);
    } else if (data.type === 1) {
      sale(salesAmount);
      teachers(teacher);
    }

    setTabArr([
      { name: '预计总收入', value: income },
      { name: '总订单数', value: order_num },
      { name: '总购买人数', value: buy_num },
      { name: '平均客单价', value: average },
    ]);
  };

  useEffect(() => {
    (async () => {
      console.log(type);
      await new Promise((resolve) => setTimeout(resolve, 100));
      await initAllEcharts();
    })();
  }, [totalSalesAmountRef, teacherPerformanceRef, bookPerformanceRef]);

  // useEffect(() => {
  //   const initCharts = async () => {
  //     const data = await salesStatistics();
  //     let { salesAmount, teacher, book, order_num, buy_num, average, income } = data;
  //     setType(data.type);

  //     if (data.type === 2) {
  //       if (totalSalesAmountRef.current && bookPerformanceRef.current) {
  //         sale(salesAmount, totalSalesAmountRef.current);
  //         books(book, bookPerformanceRef.current);
  //       }
  //     } else if (data.type === 1) {
  //       if (totalSalesAmountRef.current && teacherPerformanceRef.current) {
  //         sale(salesAmount, totalSalesAmountRef.current);
  //         teachers(teacher, teacherPerformanceRef.current);
  //       }
  //     }

  //     console.log('buy_num', buy_num);

  //     setTabArr([
  //       { name: '预计总收入', value: income },
  //       { name: '总订单数1', value: order_num },
  //       { name: '总购买人数', value: buy_num },
  //       { name: '平均客单价', value: average },
  //     ]);
  //   };

  //   initCharts();
  // }, []);

  return (
    <div className='sales'>
      <div className='items'>
        {tabArr.map((item, index) => (
          <div className='item' key={Math.random()}>
            <div className='img'>
              {index === 0 && <img src={aa} alt='' />}
              {index === 1 && <img src={bb} alt='' />}
              {index === 2 && <img src={cc} alt='' />}
              {index === 3 && <img src={dd} alt='' />}
            </div>
            <div className='cont'>
              <div className='title'>{item.name}</div>
              <div className='total'>
                {index === 0 && (item.value - 0).toFixed(2)}
                {index === 1 && item.value - 0}
                {index === 2 && item.value - 0}
                {index === 3 && (item.value - 0).toFixed(2)}

                <span className='unit'>
                  {index === 0 && '元'}
                  {index === 1 && '单'}
                  {index === 2 && '人'}
                  {index === 3 && '元'}
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
      {/* <div className='echarts'>
        {type === 1 ? (
          <>
            <div className='echarts-item' id='totalSalesAmount'></div>
            <div className='echarts-item' id='teacherPerformance'></div>
          </>
        ) : type === 2 ? (
          <>
            <div className='echarts-item' id='totalSalesAmount'></div>
            <div className='echarts-item' id='bookPerformance'></div>
          </>
        ) : null}

        {/* <div className='echarts-item' id='totalSalesAmount'></div>
        <div className='echarts-item' id='teacherPerformance'></div>
        <div className='echarts-item' id='bookPerformance'></div> 
      </div> */}

      <div className='echarts'>
        {type === 1 ? (
          <>
            <div className='echarts-item' id='totalSalesAmount' ref={totalSalesAmountRef}></div>
            <div className='echarts-item' id='teacherPerformance' ref={teacherPerformanceRef}></div>
          </>
        ) : type === 2 ? (
          <>
            <div className='echarts-item' id='totalSalesAmount' ref={totalSalesAmountRef}></div>
            <div className='echarts-item' id='bookPerformance' ref={bookPerformanceRef}></div>
          </>
        ) : null}
      </div>
    </div>
  );
};

export default OrderSalesStatistics;
