<template>
  <div class="layout-padding">
    <div class="!overflow-auto px-1">
      <Lcard :height="150">
        <template #default>
          <div class="box1">
            <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>
                </template>
              </el-popover>
            </Title>
            <span class="link">查看完整AI简报</span>
          </div>
          <div class="box1" style="margin-top: 20px;">
            <el-select v-model="selectChannel" style="width: 200px;">
              <el-option label="全部渠道" value="1"></el-option>
              <el-option label="安卓" value="2"></el-option>
              <el-option label="苹果" value="3"></el-option>
            </el-select>
            <div class="box1-time">
              <el-radio-group v-model="timeGroup">
                <el-radio-button label="day">今天</el-radio-button>
                <el-radio-button label="week">过去七天</el-radio-button>
                <el-radio-button label="month">过去三十天</el-radio-button>
              </el-radio-group>
              <el-date-picker style="float: left;" v-model="timeRange" type="datetimerange" range-separator="To"
                start-placeholder="Start date" end-placeholder="End date" />
            </div>
          </div>
        </template>
      </Lcard>
      <Lcard :height="550">
        <Title left-line title="渠道趋势对比">
        </Title>
        <div class="flex items-center justify-between mb-2 mt-3" style="margin-top: 20px;margin-left: 60px;">
          <div class="flex items-center">
            <el-radio-group v-model="lineChartUser">
              <el-radio-button label="hour">新增用户</el-radio-button>
              <el-radio-button label="day">活跃用户</el-radio-button>
              <el-radio-button label="week">启动次数</el-radio-button>
              <el-radio-button label="month">平均单次使用时长</el-radio-button>
              <el-radio-button label="month">新增次日留存率</el-radio-button>
            </el-radio-group>
          </div>
          <div class="flex items-center">
            <el-select v-model="selectVersion" style="width: 200px;">
              <el-option label="全部版本" value="1"></el-option>
              <el-option label="1.0.1" value="2"></el-option>
              <el-option label="1.02" value="3"></el-option>
            </el-select>
          </div>
        </div>
        <el-select v-model="selectLineChannel" multiple clearable style="width: 400px;margin: 20px 60px;">
          <el-option label="App Store" value="1"></el-option>
          <el-option label="应用宝" value="2"></el-option>
          <el-option label="安卓" value="3"></el-option>
        </el-select>
        <div class="relative">
          <div ref="qChartRef" style="width: 100%; height: 320px"></div>
        </div>
      </Lcard>
      <Lcard :height="650">
        <Title left-line 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">
                  可通过矩阵分析了解各个渠道的价值，在您推广平台选择时也可选择高转化高偏好的渠道作为重点渠道
                </div>
              </div>
            </template>
          </el-popover>
        </Title>
        <div style="margin: 30px 60px">
          <span>横轴：新增用户（日均）</span>
          纵轴：<el-select v-model="selectSanDian" style="width: 200px;display: inline-block;">
            <el-option label="次日留存率（日均）" value="1"></el-option>
            <el-option label="后日留存率（日均）" value="2"></el-option>
          </el-select>
        </div>
        <div ref="SDChartRef" style="width: 100%; height: 480px"></div>
      </Lcard>
      <Lcard>
        <Title left-line title="渠道明细数据">
        </Title>
        <div class="box1" style="margin: 30px 60px">
          <div class="flex items-center justify-between">
            <el-radio-group v-model="radioTableDay">
              <el-radio-button label="today">今日</el-radio-button>
              <el-radio-button label="yesterday">昨日</el-radio-button>
            </el-radio-group>
            <el-select class="ml-2" v-model="tableChannel" style="width: 140px" placeholder="渠道选择">
              <el-option label="全部" value="1"></el-option>
              <el-option label="未分组" value="2"></el-option>
            </el-select>
          </div>
          <div class="link">导出</div>
        </div>
        <el-table :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>
      </Lcard>
    </div>
  </div>
</template>

<script lang="ts" 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 { t } = useI18n();

const props = defineProps({
  channel: {
    type: String,
    default: '1',
  },
});
const emit = defineEmits(['update:channel'])

// 渠道选择
const selectChannel = computed({
  get() {
    return props.channel;
  },
  set(val) {
    emit('update:channel', val);
    console.log(val);
  },
})

const timeGroup = ref('1')
const timeRange: any = ref(null);
watch(timeGroup, (newVal) => {
  const now = new Date();
  let start: Date;
  let end: Date = new Date(now);

  switch (newVal) {
    case 'day':
      // 设置为今天 00:00:00 到 23:59:59
      start = new Date(now);
      start.setHours(0, 0, 0, 0);
      end.setHours(23, 59, 59, 999);
      break;
    case 'week':
      // 设置为本周第一天(周日)到本周最后一天(周六)
      start = new Date(now);
      const day = start.getDay();
      const diff = start.getDate() - day;
      start.setDate(diff);
      start.setHours(0, 0, 0, 0);
      end = new Date(start);
      end.setDate(start.getDate() + 6);
      end.setHours(23, 59, 59, 999);
      break;
    case 'month':
      // 设置为本月第一天到本月最后一天
      start = new Date(now.getFullYear(), now.getMonth(), 1);
      start.setHours(0, 0, 0, 0);
      end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      end.setHours(23, 59, 59, 999);
      break;
    default:
      // 其他情况清空时间范围
      timeRange.value = null;
      return;
  }

  timeRange.value = [start, end];
}, { immediate: true });

const selectVersion = ref('1') // 选择版本

const selectLineChannel = ref([]) // 选择线形图渠道

const selectSanDian = ref('1') // 选择散点图纵坐标

const radioTableDay = ref('1') // 选择表格时间
const tableChannel = ref('1') // 选择表格渠道

let qualityChart: echarts.ECharts | null = null;
const qChartRef = ref(null);
const lineChartUser = ref(null);
onMounted(() => {
  setTimeout(() => {
    initQualityChart();
    initScatterChart();
  }, 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 SDChartRef = ref(null);
let scatterChart: echarts.ECharts | null = null;

// 散点图数据
const scatterData = ref([
  { name: 'App Store', x: 120, y: 45.2, symbolSize: 80 },
  { name: '应用宝', x: 210, y: 38.7, symbolSize: 120 },
  { name: '华为应用市场', x: 98, y: 32.5, symbolSize: 65 },
  { name: '小米应用商店', x: 180, y: 41.3, symbolSize: 110 },
  { name: 'OPPO软件商店', x: 156, y: 36.8, symbolSize: 95 },
  { name: 'vivo应用商店', x: 134, y: 34.2, symbolSize: 85 },
  { name: '360手机助手', x: 178, y: 39.1, symbolSize: 105 },
  { name: '应用汇', x: 89, y: 28.6, symbolSize: 60 },
  { name: '安卓市场', x: 145, y: 35.7, symbolSize: 90 },
  { name: '91助手', x: 112, y: 31.4, symbolSize: 70 }
]);

// 初始化散点图
function initScatterChart(): void {
  if (!SDChartRef.value) return;
  if (scatterChart) scatterChart.dispose();

  scatterChart = echarts.init(SDChartRef.value);

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        return `${params.name}<br/>新增用户: ${params.data.x}<br/>留存率: ${params.data.y}%`;
      }
    },
    grid: {
      left: '7%',
      right: '12%',
      top: '10%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '新增用户（日均）',
      scale: true,
      axisLine: {
        show: true
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '次日留存率（日均）',
      scale: true,
      axisLine: {
        show: true
      },
      splitLine: {
        show: true
      },
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      type: 'scatter',
      symbolSize: (data: any) => data[2],
      data: scatterData.value.map(item => [item.x, item.y, item.symbolSize, item.name]),
      itemStyle: {
        color: (params: any) => {
          const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
          return colors[params.dataIndex % colors.length];
        }
      },
      label: {
        show: true,
        formatter: (params: any) => params.data[3],
        position: 'inside',
        fontSize: 10,
        color: '#fff'
      }
    }]
  };

  scatterChart.setOption(option);
}


</script>
<style lang="scss" scoped>
.link {
  color: #167af0;
  cursor: pointer;
}

.box1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

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