<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useEcharts } from '@/hooks/common/echarts';
import { api_pointsCount, api_taskCount } from '@/api/index.ts'

defineOptions({
  name: 'PieChart'
});

const appStore = useAppStore();

const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    // type: 'scroll',

    // orient: 'vertical',
    // right: 10,
    // top: 20,
    // bottom: 20,
  },
  series: [
    {
      color: ['#1872F0', '#f8f8f9'],
      name: '任务分析状态',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
      ]
    }
  ]
}));

async function mockData() {
  await new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
  updateOptions(opts => {
    opts.series[0].data = [
      { name: `已启动`, value: 20 },
      { name: `已停用`, value: 30 }
    ];
    return opts;
  });
}

function updateLocale() {
  updateOptions((opts, factory) => {
    const originOpts = factory();

    opts.series[0].name = originOpts.series[0].name;

    opts.series[0].data = [
      { name: $t('page.home.study'), value: 20 },
      { name: $t('page.home.entertainment'), value: 10 },
      { name: $t('page.home.work'), value: 40 },
      { name: $t('page.home.rest'), value: 30 }
    ];

    return opts;
  });
}

async function init() {
  mockData();
}

const form = ref([]);

const getCardData = async () => {
  // await api_pointsCount().then(res => {
  //   if (res.data.code === 200) {

  //     // 真实数据
  //     res.data.data.forEach(item => {
  //       form.value.push(item.count)
  //     })

  //     // 更新
  //     updateOptions((opts, factory) => {
  //       const originOpts = factory();
  //       opts.series[0].data = [
  //         { name: $t('page.home.study'), value: 20 },
  //         { name: $t('page.home.rest'), value: 30 }
  //       ];

  //       return opts;
  //     });
  //   };
  // })

  await api_taskCount().then(res => {
    if (res.data.code === 200) {
      updateOptions(opts => {
        opts.series[0].data = [
          { name: `已启动`, value: res.data.data[0].count },
          { name: `已停用`, value: res.data.data[1].count },
        ];
        return opts;
      });
    };
  });
}


watch(
  () => appStore.locale,
  () => {
    updateLocale();
  }
);

onMounted(() => {
  getCardData();
});

// init
// init();
</script>

<template>
  <div ref="domRef" class="h-260px overflow-hidden"></div>
</template>

<style scoped></style>
