import { ref } from 'vue';

export const series = ref({
  name: 'yl form chart',
  type: 'pie',
  radius: ['30%', '50%'],
  center: ['50%', '35%'],
  data: [
    { value: 1048, name: 'Search Engine' },
    { value: 735, name: 'Direct' },
    { value: 580, name: 'Email' },
    { value: 484, name: 'Union Ads' },
    { value: 300, name: 'Video Ads' }
  ],
  emphasis: {
    itemStyle: {
      // shadowBlur: 10,
      shadowOffsetX: 0
      // shadowColor: 'rgba(0, 0, 0, 0.5)'
    }
  }
});

export function formatData(data: any, index: number, isEmpty: boolean = true) {
  const _series = JSON.parse(JSON.stringify(series.value));
  // 当内容为单选的时候处理方式
  if (data.question_type === 1 || data.question_type === 2) {
    let { option } = data;

    _series.data = option.map((item: any) => {
      return {
        ...item,
        value: item.number,
        name: item.title,
        questionItem: { ...data }
      };
    });

    if (isEmpty) {
      _series.data = _series.data.filter((item) => item.value != 0);
    }
  }
  if (
    data.question_type === 5 ||
    data.question_type === 9 ||
    data.question_type === 106 ||
    data.question_type === 10
  ) {
    let copyData = setDimensionData(data);

    // copyData 删除 value 为0 的数据
    if (isEmpty) {
      copyData = copyData.map((item) => {
        return item.filter((item) => item.value !== 0);
      });
    }

    _series.data = copyData[index || 0]?.map((item) => {
      return {
        ...item,
        questionItem: { ...data }
      };
    });
  }

  // console.log(`series value is :`, _series);
  return _series;
}

export function getTableData(data: any, isEmpty = true) {
  const analysis = JSON.parse(JSON.stringify(data));
  const rows = analysis.option || [];
  return rows.map((rowItem: any) => {
    const rowData = {
      option: rowItem.option_title || '未知行'
    };

    // 遍历每个列字段，填充对应值
    analysis.head.forEach((col: any) => {
      if (col.key !== 'option') {
        const matched = rowItem.option
          ? rowItem.option.find((opt: any) => opt.index === col.key)
          : '';
        rowData[col.key] = matched ? `${matched.number}` : rowItem[col.key];
      }
    });
    return rowData;
  });
}

export function setDimensionData(data: any) {
  const { option } = data;
  return option.map((item: any) => {
    const array = [];
    for (const keys in item) {
      const obj = {};

      if (keys !== 'option' && keys !== 'avg' && item[keys] != 0) {
        obj.name = data.head.find((head: any) => head.key === keys)?.title;
        obj.value = item[keys];
        obj.avg = item.avg;

        array.push(obj);
      }
    }
    return array;
  });
}
