<template>
  <jsv-focus-block autoFocus :onAction="actionDefines">
    <div class="bgStyle">
      <JsvPieChart
        :centerPosition="center"
        :radius="360"
        :data="data"
        :animationTime="0.5"
      ></JsvPieChart>
      <!-- 文字说明 -->
      <div class="text">
        {{
          "图为圆心在(400,400)位置，半径为360的饼图。此样例限制最多六个扇形。"
        }}
      </div>
      <!-- 操作说明 -->
      <div class="text1">
        {{
          "按【上】键随机板块增加百分比，按【下】键随机减小板块百分比,按【左】键删除项，按【右】键增加项"
        }}
      </div>
    </div>
  </jsv-focus-block>
</template>

<script setup>
import { reactive, shallowRef } from "vue";
import { JsvPieChart } from "jsview";
const center = {
  x: 400,
  y: 400,
};

let data = shallowRef([
  {
    percent: 23.33,
    color: "#0000FF",
  },
  {
    percent: 24.67,
    color: "#FFFF00",
  },
  {
    percent: 15,
    color: "#FF12FF",
  },
  {
    percent: 13,
    color: "#FF1213",
  },
  {
    percent: 24,
    color: "#6EFFE1",
  },
]);
let TempData = reactive([]);
for (let i = 0; i < data.value.length; i++) {
  TempData.push({
    percent: data.value[i].percent,
    color: data.value[i].color,
  });
}
// 生成随机整数
const randomNumber = () => {
  const randomInt = Math.floor(Math.random() * data.value.length) + 1;
  return randomInt;
};
//随机颜色函数
const randomColor = () => {
  let randomColor = Math.round(Math.random() * 2 ** 24).toString(16);
  return (
    "#" + new Array(6 - randomColor.length).fill("0").join("") + randomColor
  );
};
//找出最大的百分比
const findMaxPercentItem = (data) => {
  let maxPercent = 0;
  let maxItem = null;

  for (let i = 0; i < data.length; i++) {
    if (data[i].percent > maxPercent) {
      maxPercent = data[i].percent;
      maxItem = data[i];
    }
  }

  return maxItem;
};

const onKeyDown = (ev) => {
  switch (ev.keyCode) {
    //删除项
    case 37:
      if (data.value.length >= 2) {
        const tempPercent = TempData[TempData.length - 1].percent;
        TempData.pop();
        TempData[TempData.length - 1].percent += tempPercent;
        data.value = TempData;
      }
      break;
    case 38:
      //最后一项随机增加
      const random = randomNumber();
      TempData[TempData.length - 1].percent += random;
      if (TempData[TempData.length - 1].percent > 100) {
        TempData[TempData.length - 1].percent = 100;
        for (let i = 0; i < TempData.length - 1; i++) {
          TempData[i].percent = 0;
        }
      } else {
        for (let i = 0; i < TempData.length - 1; i++) {
          TempData[i].percent -= random / (TempData.length - 1);
          if (TempData[i].percent < 0) {
            let tempPercent = TempData[i].percent;
            TempData[i].percent = 0;
            let maxItem = findMaxPercentItem(TempData);
            maxItem.percent += tempPercent;
          }
        }
      }
      data.value = TempData;
      break;
    case 39:
      //增加项
      if (data.value.length >= 1 && data.value.length <= 5) {
        TempData.push({
          percent: 10,
          color: randomColor(),
        });
        let maxItem = findMaxPercentItem(TempData);
        maxItem.percent -= 10;
        data.value = TempData;
      }
      break;
    case 40:
      // 随机减;
      if (data.value[data.value.length - 1].percent == 0) {
        // 随机减少百分比
        let randomDecrement = randomNumber();
        let adjusted = false;

        for (let i = TempData.length - 1; i >= 0; i--) {
          if (TempData[i].percent > 0) {
            if (TempData[i].percent >= randomDecrement) {
              TempData[i].percent -= randomDecrement;
              adjusted = true;
              break; // 成功减少，结束循环
            } else {
              // 如果当前项百分比不足以减去randomDecrement，则全部减去并尝试从前一个元素继续减少
              randomDecrement -= TempData[i].percent;
              TempData[i].percent = 0;
            }
          }
        }

        if (!adjusted) {
          // 如果没有成功减少（所有项都为0或randomDecrement大于所有项的总和），可以选择忽略剩余的randomDecrement
          // 或者根据需求进行特殊处理
        }

        // 确保总和为100%
        let totalPercent = TempData.reduce(
          (total, item) => total + item.percent,
          0
        );
        let diff = 100 - totalPercent; // 计算差异

        if (diff !== 0) {
          // 如果总和不为100%，则尝试平衡，优先从前往后增加
          for (let i = 0; i < TempData.length && diff !== 0; i++) {
            let availableIncrease = 100 - TempData[i].percent; // 计算当前项可增加的最大值
            let increment = Math.min(diff, availableIncrease); // 确定实际增加的值
            TempData[i].percent += increment;
            diff -= increment; // 更新剩余差异
          }
        }
      } else {
        const random = randomNumber();
        if (TempData[TempData.length - 1].percent - random < 0) {
          const shouldNumber = TempData[TempData.length - 1].percent;
          TempData[TempData.length - 1].percent = 0;
          for (let i = 0; i < TempData.length - 2; i++) {
            TempData[i].percent += shouldNumber / (TempData.length - 2);
          }
        } else {
          TempData[TempData.length - 1].percent -= random;
          for (let i = 0; i < TempData.length - 1; i++) {
            TempData[i].percent += random / (TempData.length - 1);
          }
        }
      }
      data.value = TempData;
      break;

    default:
      break;
  }
};
let actionDefines = {
  onKeyDown,
};
</script>

<style lang="css" scoped>
.bgStyle {
  width: 1280;
  height: 720;
  background-color: #007788;
}
.text {
  width: 500;
  height: 60;
  left: 700;
  top: 300;
  background-color: rgba(255, 255, 255, 0.5);
  font-size: 24;
  line-height: 28;
}
.text1 {
  width: 500;
  height: 90;
  left: 700;
  top: 440;
  background-color: rgba(255, 255, 255, 0.5);
  font-size: 24;
  line-height: 28;
}
</style>
