<script setup lang="ts">
/**
 * @Name: IndicatorOverview.vue
 * @Description: 分析页-指标总览
 * @Author: Cheney
 */
import { inject, onBeforeUnmount, reactive, ref, Ref, watch } from 'vue';
import { Bottom, Top } from '@element-plus/icons-vue';
import * as api from '/@/views/searchTerm/analysisPage/api';
import emitter from '/@/utils/emitter';

const filter = inject<Ref>('filter');
const metricLoading = ref(false);
const responseData = ref(null);
const indicator = reactive([
  {
    title: '',
    value: '',
    compare: '',
    color: '#edf6fd',
  },
  {
    title: '',
    value: '',
    compare: '',
    color: '#eefdf0',
  },
  {
    title: '',
    value: '',
    compare: '',
    color: '#fff7ed',
  },
  {
    title: '',
    value: '',
    compare: '',
    color: '#f0f0fe',
  },
]);
// 指标与返回数据字段的映射关系
const mapping = {
  imp: {
    title: '曝光量',
    key: 0, // indicator 数组中对应的索引
    kw: 'Impressions',
  },
  click: {
    title: '点击率',
    key: 1,
    kw: 'Clicks',
  },
  cart_add: {
    title: '加购份额',
    key: 2,
    kw: 'Cart_Adds',
  },
  purchases: {
    title: '购买份额',
    key: 3,
    kw: 'Purchases',
  },
};

onBeforeUnmount(() => {
  emitter.all.clear();
});

emitter.on('QueryCondition-sendRequest', () => {
  fetchIndicatorData();
});

watch(responseData, (newData) => {
  if (newData) {
    for (const key in mapping) {
      if (newData[key]) {
        const index = mapping[key].key;
        indicator[index].title = mapping[key].title;
        indicator[index].value = newData[key][`${mapping[key].kw + '_A_B_Share'}`];
        indicator[index].compare = newData[key][`diff_${mapping[key].kw + '_A_B_Share'}`];
      }
    }
  } else {
    indicator.forEach((item) => {
      item.title = '暂无数据';
      item.value = '--';
      item.compare = '--';
    });
  }
});

async function fetchIndicatorData() {
  metricLoading.value = true;
  const query = {
    date_start: filter.value.reportDate[0],
    date_end: filter.value.reportDate[1],
    layer_type: filter.value.layerType,
    search_term: filter.value.searchTerm,
    report_range: filter.value.reportType,
    [filter.value.layerType.split('_')[0]]: filter.value.variable,
  };
  try {
    const response = await api.getAsinMetrics(query);
    responseData.value = response.data;
  } catch (error) {
    console.error('==Error==', error);
  } finally {
    metricLoading.value = false;
  }
}
</script>

<template>
  <el-card
    v-loading="metricLoading"
    shadow="hover"
    body-class="flex justify-between w-full"
    style="border: none; margin-bottom: 10px">
    <el-card
      v-for="(item, index) in indicator"
      :key="index"
      body-class="flex flex-col items-center"
      class="flex-1 mx-1"
      :style="{
        background: item.color
          ? `linear-gradient(to top, ${item.color}, transparent)`
          : 'linear-gradient(to top, #fff, transparent)',
      }">
      <div class="text-2xl font-bold mb-1.5">{{ item.title || '暂无数据' }}</div>
      <div class="font-medium text-2xl mb-1.5">
        {{ item.value !== null && item.value !== undefined && item.value !== '' ? item.value : '--' }}
        <span v-if="item.value !== null && item.value !== undefined && item.value !== '' && item.value !== '--'">%</span>
      </div>
      <div>
        <span class="mr-2 font-medium" style="color: #9ca3af">较上期</span>
        <template v-if="item.compare !== '-'">
          <el-icon
            v-if="item.compare && item.compare !== '--'"
            :color="Number(item.compare) > 0 ? '#59b939' : '#e36f53'"
            style="display: inline-block; padding-top: 2px">
            <component :is="Number(item.compare) > 0 ? Top : Bottom" />
          </el-icon>
          <span
            class="font-medium"
            :style="{
              color:
                item.compare && item.compare !== '--'
                  ? Number(item.compare) > 0
                    ? '#59b939'
                    : Number(item.compare) < 0
                    ? '#e36f53'
                    : ''
                  : '',
            }">
            {{ item.compare !== null && item.compare !== undefined && item.compare !== '' ? item.compare : '--' }}
          </span>
          <span
            v-if="item.compare && item.compare !== '--'"
            :style="{
              color: Number(item.compare) > 0 ? '#59b939' : Number(item.compare) < 0 ? '#e36f53' : '',
            }"
            >%</span
          >
        </template>
        <template v-else>
          <span class="font-medium">无数据</span>
        </template>
      </div>
    </el-card>
  </el-card>
</template>

<style scoped></style>
