<script setup lang="ts">
import { computed, nextTick, onErrorCaptured, ref, useTemplateRef, watch } from 'vue';
import { useSetPieChart } from '@/hooks/chart/usePieChart';
import {
  formatData,
  getTableData,
  setDimensionData
} from '@/views/Survey/views/Analysis/components/AnalysisInfo/hooks/pieSeries';
import EmptyContainer from '@/views/Survey/components/EmptyContainer.vue';

const tableData = ref([]);
const analysis = defineModel<any>('analysis');

const pieChart = useTemplateRef<HTMLSpanElement>('pieChart');
// series 信息
const series = ref([]);
const dimension = defineModel('dimension');
// 图标高度
const chartHeight = computed(() => {
  // 需要增加的高度， 由于字多了他就会高度异常，所有要指定一个动态高度
  let addHeight = 0;
  // const optionLength = analysis.value?.option?.length;

  // 做一些额外的检测, 如果 option 下面的title 字段超过 8 个，就把 addHeight 增加
  analysis.value?.option?.forEach((item: any) => {
    if (item.title?.length > 8) {
      addHeight += 2;
    }
  });

  // 每三个选项高度增加 20px， 默认 300px
  return dimension.value ? 280 : 280 + addHeight;
});

const index = ref(0);
// 饼图 dom 结构
// 当 keyword 变动的时候，标记脏数据
watch(
  () => analysis.value,
  async (value) => {
    tableData.value = {
      ...analysis.value,
      option: getTableData(analysis.value)
    };

    // console.log(`tableData.value`, tableData.value);

    series.value = formatData(dimension.value ? tableData.value : analysis.value, index.value);
    // console.log(`series value`, series.value);

    if (!series.value.data?.length) return;
    // nextTick(() => {
    // setTimeout(() => {
    useSetPieChart(pieChart, series, { title: false, legend: false });
    // }, 1000);
    // });
  },
  { immediate: true }
);

const changeChart = (i: number) => {
  index.value = i;

  series.value = formatData(tableData.value, index.value);
  // console.log(`series value. by changeChart`, series.value);

  if (series.value.data.length <= 0) {
    series.value.data = [{ value: 0, name: 0 }];
  }
  // const pieChart = useTemplateRef<HTMLSpanElement>('pieChart');
  // useSetPieChart(pieChart, series, { title: false, legend: false });
};

const chartVisible = computed(() => {
  /**
   * 针对特殊题型做处理，
   *  首先就是矩阵的题目  question_type 为  8 9 10
   *
   *  */

  if (
    analysis.value.question_type === 8 ||
    analysis.value.question_type === 9 ||
    analysis.value.question_type === 10
  ) {
    // console.log(`series.value on matrix`, series.value?.data);
    const data = series.value?.data as { name: any; value: any }[];

    // 过滤后的 data 数据，
    const filterData = data.filter((item) => item.value != 0 && item.name != 0);
    return filterData.length;
    // series.value?.data.forEach((item: any`1[]) => {
    //   if (item.value > 0) {
    //     return true;
    //   }
    // });
  } else if (analysis.value.question_type === 106 || analysis.value.question_type === 5) {
    const data = series.value?.data as { name: any; value: any }[];
    const filterData = data?.filter((item) => item.value && Number(item.value) > 0);

    return filterData?.length;
    // console.log(`series.value on nps`, series.value?.data);
  }

  return series.value?.data?.length;
});

onErrorCaptured((err) => {
  console.log(`err`, err);
  return false;
});
</script>

<template>
  <section>
    <div v-if="dimension" style="margin: 10px 0">
      <van-radio-group v-model="index" direction="horizontal" @change="changeChart">
        <van-radio
          v-for="(item, index) in tableData.option"
          :key="index"
          icon-size="0.45rem"
          :name="index"
        >
          {{ item.option }}
        </van-radio>
      </van-radio-group>
    </div>

    <!-- 图表部分 -->
    <div
      v-if="chartVisible"
      class="charts"
      :style="{
        display: 'flex',
        height: chartHeight + 'px',
        'justify-content': 'center',
        margin: '16px 0'
      }"
    >
      <span
        ref="pieChart"
        :style="{
          width: '100%',
          height: chartVisible ? chartHeight + 'px' : ''
        }"
      ></span>
    </div>
    <!-- 图标没有实例就开始展示空图标 -->
    <div v-else>
      <empty-container :error-msg="'本题暂无有效答题数据'" />
    </div>
  </section>
</template>

<style lang="scss" scoped>
.task-card {
  //margin: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.charts {
  width: calc(100vw - 50px);
}
</style>
