<script setup lang="ts">
import { Delete, Edit } from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import emitter from '/@/utils/emitter';
import { getProductCardData, postDeleteProductLine } from '/@/views/productCenter/productList/api';

emitter.on('ProductList-updateCardData', (value: any) => {
  if (value.isUpdate) {
    cardData.value.splice(0);
    fetchProductCardData();
  }
});

emitter.on('TopFilters-selectValue', (value: any) => {
  const newIndex = cardData.value.findIndex((item) => item.productlineId === value.selectValue);
  if (newIndex !== -1) {
    selectedCardIndex.value = newIndex;
  }
});

const profile = <any>inject('profile');
const dateRange = <any>inject('dateRange');
const loading = ref(false);
const cardData = ref([]);
const pieChartRefs = ref<HTMLDivElement[]>([]);

const selectedCardIndex = ref(0);

async function fetchProductCardData() {
  loading.value = true;
  try {
    const { data } = await getProductCardData({
      profileId: profile.value.profile_id,
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
    });
    cardData.value = data;
  } catch (error) {
    console.log('error:', error);
  } finally {
    loading.value = false;
  }
}

function initChart() {
  cardData.value.forEach((item, index) => {
    const chartId = `chart${index}-${item.productlineId}`;
    const el = document.getElementById(chartId);
    if (el) {
      const pieChart = echarts.init(el);
      const option = {
        animation: false,
        series: [
          {
            silent: true,
            avoidLabelOverlap: true,
            label: {
              show: true,
              position: 'center',
              formatter: '{d}%',
            },
            emphasis: {
              disable: true,
              scale: false,
              shadowBlur: 0,
              hoverAnimation: false,
              label: {
                show: true,
                fontSize: 12,
              },
            },
            labelLine: {
              show: false,
            },
            radius: ['75%', '100%'],
            type: 'pie',
            data: [
              {
                value: item.salesPercentage,
                name: item.productlineName,
              },
              {
                value: 100 - item.salesPercentage,
                name: '',
                itemStyle: {
                  color: '#f1eff5',
                },
                label: {
                  show: false,
                },
              },
            ],
          },
        ],
      };
      pieChart.setOption(option);
      pieChartRefs.value[chartId] = pieChart;
    }
  });
}

function selectCard(index: number, item: any) {
  selectedCardIndex.value = index;
  const productlineId = item.productlineId;
  emitter.emit('ProductSelectCard-cardId', { productlineId: productlineId });
}

function editCard(item) {
  emitter.emit('ProductTab-editProductCard', { isVisible: true, data: item });
}

async function deleteProductLine(item) {
  const obj = {
    productlineId: item.productlineId,
  };
  try {
    const response = await postDeleteProductLine(obj);
    if (response.data.code == 'success') {
      ElMessage({ message: '已删除', type: 'success' });
      await fetchProductCardData();
      emitter.emit('ProductSelectCard-reloading', { reloading: true });
    } else {
      ElMessage({ message: '删除失败', type: 'error' });
    }
  } catch (error) {
    console.log('error:', error);
  }
}

watch(dateRange, async () => {
  loading.value = true;
  await fetchProductCardData();
  loading.value = false;
});

onMounted(async () => {
  await fetchProductCardData();
  initChart();
});

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

<template>
  <div class="out-container">
    <el-scrollbar v-loading="loading">
      <div class="scrollbar-flex-content" v-show="cardData">
        <el-card
          v-if="cardData.length !== 0"
          v-for="(item, index) in cardData"
          :key="item.productlineId"
          shadow="hover"
          body-style="padding: 0; box-sizing: border-box; position: relative; width: 100%;"
          class="scrollbar-demo-item"
          :class="{ selected: selectedCardIndex === index }"
          @click="selectCard(index, item)">
          <div class="pct-chart" :id="`chart${index}-${item.productlineId}`"></div>
          <el-popover v-if="index !== 0" placement="bottom" :width="150" trigger="click">
            <template #reference>
              <el-icon class="custom-icon" @click.stop="">
                <Setting />
              </el-icon>
            </template>
            <div class="custom-popoer">
              <el-button :icon="Edit" text size="small" @click="editCard(item)">编辑</el-button>
              <el-button :icon="Delete" text size="small" @click="deleteProductLine(item)" style="margin-left: 0">删除</el-button>
            </div>
          </el-popover>
          <div class="left-part-container">
            <div class="product-line-name">{{ item.productlineName }}</div>

            <div class="custom-part">
              <div class="total-sales">${{ item.totalSales }}</div>
              <span class="label">总销售额</span>
            </div>
          </div>
        </el-card>
      </div>
      <el-card
        v-if="cardData.length === 0"
        shadow="hover"
        body-style="padding: 0;box-sizing: border-box; position: relative; width: 100%;"
        class="scrollbar-demo-item">
        <el-empty description=" ">
          <template #image>
            <div style="color: #919398">暂无数据</div>
          </template>
        </el-empty>
      </el-card>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.out-container {
  width: 100%;
  padding: 5px 12px 0 12px;
}

.scrollbar-flex-content {
  display: flex;
}

.scrollbar-demo-item {
  flex-shrink: 0;
  display: flex;
  gap: 5px;
  width: 202px;
  height: 92px;
  margin: 10px 10px 10px 0;
  border-radius: 4px;
  box-sizing: border-box;
  border: 1px solid transparent; /* 添加透明边框 */
  transition: border-color 0.3s; /* 可选，使边框颜色改变更平滑 */
  cursor: pointer;
}

.product-line-name {
  position: relative;
  padding: 0 12px 8px 0;
  color: #4e5969;
  font-weight: 700;
  font-size: 13px;
  line-height: 17px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.custom-part {
  padding-top: 8px;
}

.total-sales {
  color: #4e5969;
  font-size: 13px;
  font-weight: 700;
}

.label {
  padding-right: 4px;
  color: #c9cdd4;
  font-size: 12px;
}

.pct-chart {
  box-sizing: border-box;
  position: absolute;
  top: 34px;
  right: 5%;
  width: 50px;
  height: 50px;
}

.selected {
  border: 1px solid #3359b5;
}

.custom-icon {
  position: absolute;
  top: 8px;
  right: 5%;
  z-index: 2;
  color: #c9cdd4;
  /* padding: 4px; */
  transform: rotate(90deg);
}

.custom-popoer {
  display: flex;
  flex-direction: column;
}

.left-part-container {
  padding: 10px;
  position: relative;
}
</style>
