<template>
   <div class="layout-padding">
      <div class="!overflow-auto px-1">
         <Lcard>
            <template #default>
               <Title style="margin-bottom: 10px;" title="整体趋势">
                  <el-popover class="box-item" placement="right" trigger="hover" width="250">
                     <template #reference>
                        <el-icon class="ml-1" style="color: #a4b8cf">
                           <InfoFilled />
                        </el-icon>
                     </template>
                     <template #default>
                        <div class="ant-popover-inner-content">
                           <div class="um-page-tips-content" style="line-height: 24px">
                              <p><span class="highlight">新增用户：</span><span>第一次启动应用的用户（以设备为判断标准）</span></p>
                              <p><span class="highlight">新增账号：</span><span>第一次启动应用的账号</span></p>
                              <p><span class="highlight">新增用户占比：</span><span>某时段内新增用户占该时段活跃用户的比例</span></p>
                              <p>
                                 <span>
                                    按天、周或月查看数据可进行版本、渠道的交叉筛选，小时数据最多展示7天并且不支持筛选。周区间定义为周日至次周周六。按周（按月）显示时，界面上用每周的周日（每个月的第一日）来代表该周（该月）
                                 </span>
                              </p>
                           </div>
                        </div>
                     </template>
                  </el-popover>
               </Title>
               <div style="position: relative; top: -37px">
                  <div class="link" style="float: right;">
                     <svg style="margin-left: 20px;transform: translateY(3px);" width="16" height="16" viewBox="0 0 16 16"
                        fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path
                           d="M2.66663 14.6668V2.00016C2.66663 1.63197 2.9651 1.3335 3.33329 1.3335H12.6666C13.0348 1.3335 13.3333 1.63197 13.3333 2.00016V14.6668L7.99996 11.9093L2.66663 14.6668Z"
                           stroke="#167AF0" stroke-linejoin="round" />
                        <path d="M7.98328 4.6499V8.6499" stroke="#167AF0" stroke-linecap="round" stroke-linejoin="round" />
                        <path d="M5.98328 6.6499H9.98328" stroke="#167AF0" stroke-linecap="round"
                           stroke-linejoin="round" />
                     </svg>
                     <span style="margin-left: 8px;">订阅</span>
                  </div>
                  <div class="link" style="float: right;">
                     <svg style="transform: translateY(3px);" width="16" height="16" viewBox="0 0 16 16" fill="none"
                        xmlns="http://www.w3.org/2000/svg">
                        <path
                           d="M13.3333 5.3335V2.00016C13.3333 1.63197 13.0348 1.3335 12.6666 1.3335H3.33329C2.9651 1.3335 2.66663 1.63197 2.66663 2.00016V14.0002C2.66663 14.3684 2.9651 14.6668 3.33329 14.6668H5.33329"
                           stroke="#167AF0" stroke-linecap="round" stroke-linejoin="round" />
                        <path d="M5.33337 5.3335H10" stroke="#167AF0" stroke-linecap="round" />
                        <path d="M9 11H15" stroke="#167AF0" stroke-linecap="round" />
                        <path d="M12 14V8" stroke="#167AF0" stroke-linecap="round" />
                        <path d="M5.33337 8H8.00004" stroke="#167AF0" stroke-linecap="round" />
                     </svg>
                     <span style="margin-left: 8px;">编辑指标</span>
                  </div>
                  <!-- <div class="link" style="float: right;">生成AI简报</div> -->
               </div>
               <div class="msg">
                  <el-icon class="ml-1" style="color: #a4b8cf; vertical-align: middle;">
                     <InfoFilled />
                  </el-icon>
                  前往
                  <span class="link">U-DOP数据开放平台</span>
                  ，获取用户访问明细日志，点击查看
                  <span class="link">支持返还的字段</span>
               </div>
               <div class="box1">
                  <Lcard style="margin-right: 20px;">
                     <div class="card-box1">
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon1.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon2.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon3.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon4.svg" alt="icon">
                           </template>
                        </InfoCard>
                     </div>
                  </Lcard>
                  <Lcard>
                     <div class="card-box2">
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon5.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon6.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon7.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon8.svg" alt="icon">
                           </template>
                        </InfoCard>
                        <InfoCard title="订单数量" value="1,234" description="较昨日减少 1.2%">
                           <template #icon>
                              <img src="./icons/icon9.svg" alt="icon">
                           </template>
                        </InfoCard>
                     </div>
                  </Lcard>
               </div>
            </template>
         </Lcard>
         <Lcard>
            <el-date-picker style="float: left;width: 240px;height: 30px;" v-model="timeRange" type="daterange"
               value-format="YYYY-MM-DD" start-placeholder="开始日期" end-placeholder="结束日期" />
            <div class="line"></div>
            <div class="flex items-center justify-between mb-2 mt-3">
               <el-form>
                  <el-form-item>
                     <el-select style="width: 140px" placeholder="渠道对比">
                        <!-- <el-option v-for="item in channelCompareOptions" :key="item.value" :label="item.label" :value="item.value" /> -->
                     </el-select>
                     <el-button class="ml-2">对比时间</el-button>
                  </el-form-item>
               </el-form>
               <div class="flex items-center">
                  <el-radio-group v-model="lineChartUser">
                     <el-radio-button label="new">新增用户</el-radio-button>
                     <el-radio-button label="active">活跃用户</el-radio-button>
                     <el-radio-button label="doing">启动次数</el-radio-button>
                     <el-radio-button label="total">累计用户</el-radio-button>
                  </el-radio-group>
               </div>
            </div>
            <div class="relative">
               <div ref="qChartRef" style="width: 100%; height: 320px"></div>
            </div>
            <div class="mt-3">
               <div class="flex items-center justify-between mb-2">
                  <div class="text-base font-medium cursor-pointer select-none" @click="showDetail1 = !showDetail1">
                     {{ showDetail1 ? '收起明细数据' : '展开明细数据' }}
                  </div>
                  <div>
                     <el-button>导出</el-button>
                  </div>
               </div>
               <el-table v-if="showDetail1" :data="pagedTableRows" border>
                  <el-table-column prop="date" label="日期" min-width="140" />
                  <el-table-column label="新增用户（占比）" min-width="220">
                     <template #default="scope">
                        <div class="flex items-center justify-between w-full">
                           <span>{{ scope.row.newUsers }}</span>
                           <span class="text-gray-500 text-xs">{{ scope.row.ratio }}</span>
                        </div>
                     </template>
                  </el-table-column>
               </el-table>
               <div v-if="showDetail1" class="flex justify-end mt-3">
                  <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                     layout="total, prev, pager, next, sizes" :total="tableRows.length" :page-sizes="[5, 10, 20]" />
               </div>
            </div>
         </Lcard>
         <Lcard :height="660">
            <div class="msg">
               <el-icon class="ml-1" style="color: #a4b8cf; vertical-align: middle;">
                  <InfoFilled />
               </el-icon>
               点击下列环形图中单个版本/渠道将跳转到对应的详情页
            </div>
            <div class="box1">
               <lcard :height="540" style="margin-right: 20px;">
                  <div class="box1-title" style="float: left;">TOP版本</div>
                  <div class="link" style="float: right;">详情</div>
                  <div class="line" style="margin-top: 40px;"></div>
                  <el-radio-group v-model="circleEchartUser1">
                     <el-radio-button label="hour">新增用户</el-radio-button>
                     <el-radio-button label="day">活跃用户</el-radio-button>
                     <el-radio-button label="month">累计用户</el-radio-button>
                  </el-radio-group>
                  <div ref="circleEchartRef1" style="width: 100%; height: 380px;"></div>
               </lcard>
               <lcard :height="540">
                  <div class="box1-title" style="float: left;">TOP版本</div>
                  <div class="link" style="float: right;">详情</div>
                  <div class="line" style="margin-top: 40px;"></div>
                  <el-radio-group v-model="circleEchartUser1">
                     <el-radio-button label="hour">新增用户</el-radio-button>
                     <el-radio-button label="day">活跃用户</el-radio-button>
                     <el-radio-button label="month">累计用户</el-radio-button>
                  </el-radio-group>
                  <div ref="circleEchartRef2" style="width: 100%; height: 380px;"></div>
               </lcard>
            </div>
         </Lcard>
      </div>
   </div>
</template>

<script lang="ts" name="countMainTrend" setup>
// import { ref, onMounted, watch, computed, defineAsyncComponent } from 'vue';
import { useI18n } from 'vue-i18n';
import * as echarts from 'echarts';
// 引入组件
const Lcard = defineAsyncComponent(() => import('/@/components/LYcom/Lcard/index.vue'));
const Title = defineAsyncComponent(() => import('/@/components/Title/index.vue'));
const InfoCard = defineAsyncComponent(() => import('./infoCard.vue'));
const { t } = useI18n();
const timeRange = ref(null);
const qChartRef = ref<HTMLDivElement | null>(null);
let qualityChart: echarts.ECharts | null = null;

const lineChartUser = ref('new')

onMounted(() => {
   setTimeout(() => {
      initQualityChart();
      initCircleChart2()
      initCircleChart1()
   }, 500);
});
const qualityXAxis = ref<string[]>([
   '2025-07-01',
   '2025-07-08',
   '2025-07-15',
   '2025-07-22',
   '2025-07-29',
   '2025-08-05',
   '2025-08-12',
   '2025-08-19',
   '2025-08-26',
   '2025-09-02',
   '2025-09-09',
   '2025-09-16',
]);
const retentionSeries = ref<number[]>([20, 23, 27, 24, 22, 15, 5, 4, 16, 26, 25, 2]);
const industryAvgSeries = ref<number[]>([16, 18, 20, 24, 25, 24, 16, 10, 15, 22, 21, 12]);
const peerSameScaleSeries = ref<number[]>([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
function initQualityChart(): void {
   console.log(qChartRef.value, qChartRef);
   if (!qChartRef.value) return;
   if (qualityChart) qualityChart.dispose();
   qualityChart = echarts.init(qChartRef.value);
   const option: echarts.EChartsOption = {
      tooltip: { trigger: 'axis', valueFormatter: (v) => `${v}%` },
      legend: { data: ['留存率', '同行业App', '同行业同规模App'] },
      grid: { left: 40, right: 20, top: 30, bottom: 30 },
      xAxis: { type: 'category', data: qualityXAxis.value },
      yAxis: {
         type: 'value',
         min: 0,
         max: 30,
         axisLabel: { formatter: '{value}%' },
         splitLine: { lineStyle: { color: '#f3f4f6' } },
      },
      series: [
         { name: '留存率', type: 'line', smooth: true, data: retentionSeries.value },
         { name: '同行业App', type: 'line', smooth: true, data: industryAvgSeries.value, color: '#f59e0b' },
         { name: '同行业同规模App', type: 'line', smooth: true, data: peerSameScaleSeries.value, color: '#60a5fa' },
      ],
   };
   qualityChart.setOption(option);
}


interface TableRow {
   date: string;
   newUsers: number;
   ratio: string;
}
// 展开/收起明细
const showDetail1 = ref(true);
const pagedTableRows = computed(() => {
   const startIndex = (currentPage.value - 1) * pageSize.value;
   return tableRows.value.slice(startIndex, startIndex + pageSize.value);
});
// 表格相关（静态数据）
const currentPage = ref(1);
const pageSize = ref(5);
const tableRows = ref<TableRow[]>(
   Array.from({ length: 42 }).map((_, idx) => ({
      date: `2025-08-${String(11).padStart(2, '0')}`,
      newUsers: 727,
      ratio: '97.45%',
   }))
);


// 环形图
// 添加圆环图相关的引用和数据
const circleEchartRef1 = ref(null);
let circleChart1: echarts.ECharts | null = null;
const circleEchartUser1 = ref('hour');

const circleEchartRef2 = ref(null);
let circleChart2: echarts.ECharts | null = null;
const circleEchartUser2 = ref('hour');

// 初始化圆环图
function initCircleChart1(): void {
   if (!circleEchartRef1.value) return;
   if (circleChart1) circleChart1.dispose();

   circleChart1 = echarts.init(circleEchartRef1.value);

   const option: echarts.EChartsOption = {
      tooltip: {
         trigger: 'item'
      },
      legend: {
         bottom: '0',
         left: 'center'
      },
      series: [
         {
            name: '版本分布',
            type: 'pie',
            radius: ['50%', '70%'], // 设置内半径和外半径，形成圆环效果
            avoidLabelOverlap: false,
            padAngle: 2, // 扇区间隙
            itemStyle: {
               borderRadius: 5 // 扇区圆角
            },
            label: {
               show: true,
               formatter: '{b}: {d}%' // 显示标签和百分比
            },
            emphasis: {
               label: {
                  show: true,
                  fontSize: 14,
                  fontWeight: 'bold'
               }
            },
            labelLine: {
               show: true
            },
            data: [
               { value: 35, name: 'v3.2.1' },
               { value: 25, name: 'v3.1.5' },
               { value: 20, name: 'v3.0.8' },
               { value: 10, name: 'v2.9.3' },
               { value: 10, name: '其他' }
            ]
         }
      ]
   };

   circleChart1.setOption(option);
}
// 初始化圆环图
function initCircleChart2(): void {
   if (!circleEchartRef2.value) return;
   if (circleChart2) circleChart2.dispose();

   circleChart2 = echarts.init(circleEchartRef2.value);

   const option: echarts.EChartsOption = {
      tooltip: {
         trigger: 'item'
      },
      legend: {
         bottom: '0',
         left: 'center'
      },
      series: [
         {
            name: '版本分布',
            type: 'pie',
            radius: ['50%', '70%'], // 设置内半径和外半径，形成圆环效果
            avoidLabelOverlap: false,
            padAngle: 2, // 扇区间隙
            itemStyle: {
               borderRadius: 5 // 扇区圆角
            },
            label: {
               show: true,
               formatter: '{b}: {d}%' // 显示标签和百分比
            },
            emphasis: {
               label: {
                  show: true,
                  fontSize: 14,
                  fontWeight: 'bold'
               }
            },
            labelLine: {
               show: true
            },
            data: [
               { value: 35, name: 'v3.2.1' },
               { value: 25, name: 'v3.1.5' },
               { value: 20, name: 'v3.0.8' },
               { value: 10, name: 'v2.9.3' },
               { value: 10, name: '其他' }
            ]
         }
      ]
   };

   circleChart2.setOption(option);
}


</script>
<style lang="scss" scoped>
.msg {
   height: 30px;
   background-color: #f4f5fa;
   line-height: 30px;
   font-size: 12px;
}

.link {
   color: #167af0;
   cursor: pointer;
}

.box1 {
   display: flex;
   margin-top: 30px;

   .card-box1,
   .card-box2 {
      display: flex;
      flex-wrap: wrap;
      justify-content: start;
   }

   .card-box1 {
      .info-card {
         width: 48%;
      }
   }

   .card-box2 {
      .info-card {
         width: 33%;
         min-width: 150px;
      }
   }
}

.line {
   margin: 60px -30px 30px;
   height: 1px;
   background-color: #E6E6E6;
}
</style>