<template>
  <div ref="map" style="width: 1600px; height: 551px"></div>
  <div
    style="width: 1231px; height: 72px; margin-top: -55px; background: linear-gradient(to top, #DAEBFD, #ffffff); margin-left: 182px">
    <div style="width: 1231px; height: 40px; display: flex; justify-content: space-between;">
      <div style="display: flex; align-self: center;">
        <div class="time-btn">
          ⏸
        </div>
        <div class="time-btn">
          ⏹
        </div>
        <div class="time-btn">
          重置
        </div>
      </div>
      <div style="display: flex; align-self: center;">
        <div>
          当前时间：
        </div>
        <input></input>
        <div style="margin: 0 10px 0 40px; color: #04295A;">刻度</div>
        <select name="firstSelect" id="firstSelect">
          <option value="option1">周制</option>
        </select>
        <div style="margin: 0 10px 0 40px; color: #04295A;">速率</div>
        <select name="secondSelect" id="secondSelect" style="margin-right: 20px;">
          <option value="optionA">1X</option>
          <option value="optionB">2X</option>
        </select>
      </div>
    </div>

    <div ref="timeLineChart" style="width: 1231px; height: 30px; background-color: #6091D6;"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import worldJson from "@/assets/json/world.json";
import {getCharacterTrends} from "@/api/technologyFigures/technologyFigures"
import { ref,onMounted } from "vue";

// const props = defineProps({
//   peoDate: {
//     type: String,
    
//     default:"jinri"
//   }
// })






// 获取人物动向
const CharacterTrends = ref([]);
const time = ref("");
const date = ref("");
const handlegetCharacterTrendsFn = async () => {
	const params = {
		startTime: "2025-01-01" ||  date.value
	};
	try {
		const res = await getCharacterTrends(params);
		console.log("人物动向", res);
    
		if (res.code === 200) {
			CharacterTrends.value = res.data.map(item=>{
        return{
          time: item.newsDate,
          text: item.newsContent.substring(0, 17),
          lon: item.lon || (Math.random() * 360 - 180).toFixed(6), //没数据
          lat: item.lat || (Math.random() * 180 - 90).toFixed(6), //没数据
          avatar: item.imageUrl
        };
      });
      
		}
	} catch (error) {}
};

function getDateDaysAgo(days) {
	// 获取当前日期
	const currentDate = new Date();
	// 计算指定月数之前的日期
	const pastDate = new Date(currentDate);
	pastDate.setDate(currentDate.getDate() - days); // 减去指定的天数
	// 格式化日期为 "YYYY-MM-DD" 的形式
	const year = pastDate.getFullYear();
	const month = String(pastDate.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
	const day = String(pastDate.getDate()).padStart(2, "0");
	return `${year}-${month}-${day}`;
}

// onMounted(async () => {
// 	handlegetCharacterTrendsFn();
// })

export default {
  name: "MapAnimation",
  props: {
    peoDate: {
      type: String,
      default:"本周"
    }
  },
  watch: {
    async peoDate(Val) {
      time.value = Val;
      const days = ref();
      if(time.value === "本周"){
        days.value = 7;
      }else if(time.value === "今天"){
        days.value = 0;
      }else if(time.value === "昨天"){
        days.value = 1;
      }else if(time.value === "近三天"){
        days.value = 3;
      }else if(time.value === "本月"){
        days.value = new Date().getDate()-1;
      }
      date.value = getDateDaysAgo(days.value);
      await handlegetCharacterTrendsFn();
      this.initMap();
    }
  },
  setup(props) {
     onMounted(async () => {
      
      time.value = props.peoDate;
      const days = ref();
      if(time.value === "本周"){
        days.value = 7;
      }else if(time.value === "今天"){
        days.value = 0;
      }else if(time.value === "昨天"){
        days.value = 1;
      }else if(time.value === "近三天"){
        days.value = 3;
      }else if(time.value === "本月"){
        days.value = new Date().getDate()-1;
      }
      date.value = getDateDaysAgo(days.value);
     

     });
  },
  async mounted() {
    
    await handlegetCharacterTrendsFn();
    this.initMap();
    
    
  },
  methods: {
    initMap() {
      // 注册自定义地图数据
      echarts.registerMap("China", worldJson);
      // const eventsData = [
      //   {
      //     time: "9月23日",
      //     text: "随美国总统特朗普进行国事访问",
      //     lon: 116.46,
      //     lat: 39.92,
      //     avatar: "/testData/united_states 1 copy.png"
      //   },
      //   {
      //     time: "9月23日",
      //     text: "出席中国发展高层论坛2025年年会",
      //     lon: 116.46,
      //     lat: 39.92,
      //     avatar: "/testData/united_states 1 copy.png"
      //   },
      //   {
      //     time: "9月23日",
      //     text: "与民主党领导人查克·舒默及哈基姆...",
      //     lon: 1.46,
      //     lat: 39.92,
      //     avatar: "/testData/united_states 1 copy.png"
      //   },
      //   {
      //     time: "9月23日",
      //     text: "与阿拉伯国家领导人会晤，商讨加...",
      //     lon: 116.46,
      //     lat: -44.92,
      //     avatar: "/testData/united_states 1 copy.png"
      //   },
      //   {
      //     time: "9月23日",
      //     text: "对印度进行为期四天的访问，与总理...",
      //     lon: 78.1,
      //     lat: 20.7,
      //     avatar: "/testData/united_states 1 copy.png"
      //   }
      // ];
      const eventsData = CharacterTrends;
      const chart = echarts.init(this.$refs.map);

      

      const option = {
        grid: {
          left: "10%",
          right: "10%",
          bottom: "10%",
          top: "10%",
          containLabel: true
        },
        geo: {
          map: "China",
          roam: true,
          label: {
            emphasis: {
              show: false,
              color: "#fff"
            }
          },
          silent: true,
          itemStyle: {
            areaColor: "#F6FAFF",
            borderColor: "#B9DCFF"
          }
        },
        series: [
          {
            name: "行程",
            type: "effectScatter",
            coordinateSystem: "geo",
            data: eventsData.value.map(item => ({
              value: [item.lon, item.lat],
              time: item.time,
              text: item.text,
              avatar: item.avatar,
              itemStyle: { color: "#ffcc00" }
            })),
            symbolSize: 10,
            showEffectOn: "render",
            rippleEffect: {
              brushType: "stroke"
            },
            // label: {
            //   normal: {
            //     show: true,
            //     formatter: params => {
            //       const { time, text } = eventsData[params.dataIndex];
            //       return `{time|${time}} \n {text|${text}}`;
            //     },
            //     rich: {
            //       time: { fontSize: 16, color: 'rgba(5, 95, 194, 1)' },
            //       text: { fontSize: 14, color: 'rgb(95, 101, 108)' }
            //     }
            //   }
            // },
            itemStyle: {
              color: "#ddb926",
              shadowBlur: 10,
              shadowColor: "#333"
            }
          }
        ]
      };
      chart.setOption(option);
      
   
      // 添加 graphic 元素并设置其位置
      this.updateGraphics(chart, eventsData);

      // 监听地图缩放和移动事件，以更新 graphic 的位置
      chart.on('georoam', () => {
        this.updateGraphics(chart, eventsData);
      });

      const chart2 = echarts.init(this.$refs.timeLineChart);

      const option2 = {
        xAxis: {
          type: "time",
          position: "top",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#000"
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            formatter: "{value}日",
            color: "#000"
          },
          splitLine: {
            show: true
          },
          data: [
            "2024-03-25",
            "2024-04-08",
            "2024-04-15",
            "2024-04-22",
            "2024-04-29",
            "2024-05-06",
            "2024-05-13",
            "2024-05-20",
            "2024-05-27",
            "2024-06-03",
            "2024-06-10",
            "2024-06-17",
            "2024-06-24",
            "2024-07-01",
            "2024-07-08",
            "2024-07-15",
            "2024-07-22",
            "2024-07-29"
          ]
        },
        yAxis: {
          type: "value",
          show: false
        },
        series: [
          {
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            type: "line",
            areaStyle: {},
            emphasis: {
              focus: "series"
            }
          }
        ],
        visualMap: {
          show: false,
          dimension: 1,
          pieces: [{ gt: 0, lte: 1, color: "#ffcc00" }]
        }
      };

      chart2.setOption(option2);
    },
    updateGraphics(chart, eventsData) {
      const graphics = eventsData.value.map((event, index) => {
        const position = chart.convertToPixel({ geoIndex: 0 }, [event.lon, event.lat]);
        return {
          type: 'group',
          position: position,
          children: [

            {
              type: 'image',
              x: -170, y: -72,
              style: {
                image: "/icon/map-text-bg.png",
                borderWidth: 2,
                borderColor: '#1890ff', width: 339, height: 72
              }
            },
            {
              type: 'image',
              x: -160, y: -63,
              style: {
                image: event.avatar,
                borderWidth: 2,
                borderColor: '#1890ff', width: 42, height: 42
              }
            }, {
              type: 'text',
              x: -106, y: -63,
              style: {
                text: event.time,
                fontSize: 16,
                fontWeight: '800',
                fill: 'rgba(5, 95, 194, 1)',        // 文字颜色（ECharts 中用 fill，不是 color）
                textAlign: 'left'
              }
            },
            {
              type: 'text',
              x: -106, y: -40,
              style: {
                text: event.text,
                fontSize: 16,
                fontWeight: '400',
                fill: 'rgba(59, 65, 75, 1)',        // 文字颜色（ECharts 中用 fill，不是 color）
                textAlign: 'left',
                
              }
            }
          ]
        };
      });

      chart.setOption({
        graphic: graphics
      });
      chart.resize(); // 强制刷新图表
    }
  }
};
</script>

<style scoped>
#map {
  width: 1600px;
  height: 581px;
  font-family: Microsoft YaHei;
}

.time-btn {
  color: #04295A;
  background-color: #F9FDFE;
  border: 1px solid #04295A;
  padding: 0 10px;
  margin: 0 10px;
}
</style>