<template>
  <div class="zl">
    <div id="bar" style="width: 100%; height: 55vw"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,defineProps,watch } from "vue";
import * as echarts from "echarts";
import { zlDjtjxx } from "../../../../api/zlzx.js";
const props = defineProps({
  timeType: {
    type: String,
    default: "1",
  },
})
watch(
  () => props.timeType,
  () => {
    getData();
  },{deep:true}
);
const data = ref([
  {
    name: "蓝色",
    value: 0,
    dict: "40",
  },
  {
    name: "橙色",
    value: 0,
    dict: "20",
  },
  {
    name: "黄色",
    value: 0,
    dict: "30",
  },
  {
    name: "红色",
    value: 0,
    dict: "10",
  },
]);
function lineChartFn() {
  var chartDom = document.getElementById("bar");
  var myChart = echarts.init(chartDom);
  let bgColor = "#fff";
  let title = "总量";

  let formatNumber = function (num) {
    let reg = /(?=(\B)(\d{3})+$)/g;
    return num.toString().replace(reg, ",");
  };
  let total = data.value.reduce((a, b) => {
    return a + b.value * 1;
  }, 0);
  var option;
  const color = ["#177FFF", "orange", "#ffcc40", "#F6426C"];
  option = {
    color,
    tooltip: {
      trigger: "item",
    },
    legend: {
      bottom: "0",
      left: "center",
      textStyle: {
        color: "#333",
      },
    },
    //   legend: {},
    series: [
      {
        type: "pie",
        radius: ["45%", "70%"],
        center: ["50%", "50%"],
        data: data.value,
        hoverAnimation: false,
        labelLine: {
          normal: {
            length: 20,
            length2: 30,
          },
        },
        label: {
          normal: {
            formatter: function(val){
              if(val.percent === undefined){
                return val.name +'('+ val.value +')'+ '\n' +  0 +'%'
              }else{
                return val.name +'('+ val.value +')'+'\n' +  val.percent +'%'
              }
              
            }

          },
        },
      },
    ],
  };
  option && myChart.setOption(option);
  document.getElementById("bar").setAttribute("_echarts_instance_", "");
}
function getData() {
  zlDjtjxx({type:props.timeType}).then((res) => {
    res.forEach((v) => {
      data.value.filter((item) => item.dict === v.zldj).map((item) => {
          item.value = v.total;
        });
    });
    lineChartFn();
  });
}
onMounted(() => {
  getData();
});
</script>

<style lang="scss" scoped>
.zl {
  margin: 5px 0;
  padding-top: 8px;
  background-size: 100% 100%;
}
</style>