<template>
  <div id="barEcharts" style="width: 380px; height: 350px"></div>
</template>
<script setup>
import { onMounted } from 'vue';
import { timeFinancialChart } from 'apis/projectFinance';

const projectId = useProjectId();

const data = reactive({
  timeList: [],
  taskNameList: [],
});

async function getChartData() {
  try {
    const params = { param: { projectId: projectId.value } };
    const res = await timeFinancialChart(params);
    console.log('res:', res);
    return processing(res);
  } catch (error) {
    console.error(error);
  }
}

function processing(list) {
  let timeList = [
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
  ];
  for (let i = 0; i < list.length; i++) {
    for (let j = 0; j < list[i].data.length; j++) {
      const m = list[i].data[j].time - 0;
      timeList[m - 1] = m + '月';
    }
  }
  for (let i = 0; i < timeList.length; i++) {
    if (!timeList[i]) {
      timeList.splice(i, 1);
      i -= 1;
    }
  }
  let series = [];
  let taskNameList = [];
  for (let i = 0; i < list.length; i++) {
    let data = [];
    taskNameList.push(list[i].name);
    for (let k = 0; k < timeList.length; k++) {
      data.push(null);
    }
    for (let k = 0; k < list[i].data.length; k++) {
      for (let m = 0; m < timeList.length; m++) {
        if (list[i].data[k].time - 0 + '月' === timeList[m]) {
          data[m] = list[i].data[k].expend - 0;
        }
      }
    }
    let obj = {
      name: list[i].name,
      type: 'bar',
      stack: 'total',
      label: {
        show: false,
        color: '#FFFFFF',
      },
      barWidth: 12,
      data: data,
    };
    series.push(obj);
  }
  data.timeList = timeList;
  data.taskNameList = taskNameList;
  console.log('series: ', series);
  return series;
}

onMounted(async () => {
  const myChart = echarts.init(document.getElementById('barEcharts'));
  const series = await getChartData();
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      top: 10,
      right: 0,
      icon: 'circle',
      orient: 'horizontal',
      itemGap: 10,
      itemWidth: 10,
      itemHeight: 14,
      textStyle: {
        fontSize: 14,
        color: '#858585',
        fontWeight: 400,
      },
    },
    data: data.taskNameList,
    color: ['#7E84A3', '#FF914C', '#5189F8', '#3FC7BB'],
    grid: {
      left: '15%',
      right: '0',
      bottom: '5%',
      containLabel: false,
    },
    xAxis: {
      type: 'category',
      data: data.timeList,
      axisTick: {
        show: false,
      },
      axisLabel: {
        show: true,
      },
      axisLine: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          color: '#F3F4F5',
        },
      },
    },
    series: series,
  };
  myChart.setOption(option);
});
</script>
