<template>
  <div class="layout-padding">
    <div class="ascribe">
      <el-row :gutter="12" style="padding: 0 12px 12px; row-gap: 12px;">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <LayoutHeader title="卸载归因" :style="{ marginBottom: '0' }">
            <template #aside>
              <div class="data-source-status">数据源状态：Demo数据</div>
            </template>
            <template #tooltip-content>
              卸载归因解读卸载设备在您应用中的最后活跃行为。<br/>
              本模块功能展示周期内的卸载设备，在卸载前的最后7天（含当天）在您的应用中浏览次数TOP10的页面；<br/>
              展示应用在全网设备中的卸载量，及是否在当前周期内新安装了您关注行业的头部竞品。<br/>
              同时基于行业提供各周期的应用安装卸载比，辅助您判断行业的规模趋势。
            </template>
            <template #content>
            </template>
          </LayoutHeader>
        </el-col>
      </el-row>
      <el-row :gutter="12" style="padding: 0 12px 12px; row-gap: 12px;">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card shadow="none">
            <div class="trend-container">
              <div class="card-title" style="margin-bottom: 53px;">卸载设备全量预测<svg
                width="24" height="22" viewBox="0 0 24 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M0 13C0 5.8203 5.8203 0 13 0H22C23.1046 0 24 0.895431 24 2V9C24 16.1797 18.1797 22 11 22H2C0.89543 22 0 21.1046 0 20V13Z" fill="url(#paint0_linear_834_812)"/>
                <path d="M6 16.5L9.63695 5.5H11.6343L15.2712 16.5H13.4379L12.5137 13.3806H8.6979L7.77376 16.5H6ZM9.11526 12.0075H12.0964L11.6641 10.5299C11.3064 9.33582 10.9784 8.11194 10.6356 6.87313H10.576C10.2481 8.12687 9.90525 9.33582 9.54752 10.5299L9.11526 12.0075Z" fill="white"/>
                <path d="M16.271 16.5V5.5H18V16.5H16.271Z" fill="white"/>
                <defs>
                <linearGradient id="paint0_linear_834_812" x1="12" y1="0" x2="12" y2="22" gradientUnits="userSpaceOnUse">
                <stop stop-color="#4CFFEA"/>
                <stop offset="1" stop-color="#0081EB"/>
                </linearGradient>
                </defs>
              </svg></div>
              <div class="card-tabs">
                <div class="card-tab" :class="{ active: activeTab === Type.CHURN }"
                  @click="handleTabClick(Type.CHURN)">
                  卸载流失设备（预测）
                  <el-tooltip effect="light" content="" placement="right-start">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M7 14C8.93298 14 10.683 13.2165 11.9497 11.9497C13.2165 10.683 14 8.93298 14 7C14 5.06702 13.2165 3.31702 11.9497 2.05025C10.683 0.783503 8.93298 0 7 0C5.06702 0 3.31702 0.783503 2.05025 2.05025C0.783503 3.31702 0 5.06702 0 7C0 8.93298 0.783503 10.683 2.05025 11.9497C3.31702 13.2165 5.06702 14 7 14Z"
                        fill="#1B4D88" fill-opacity="0.4" />
                      <path fill-rule="evenodd" clip-rule="evenodd"
                        d="M6.99957 1.94434C7.5365 1.94434 7.97179 2.37962 7.97179 2.91656C7.97179 3.4535 7.5365 3.88878 6.99957 3.88878C6.46263 3.88878 6.02734 3.4535 6.02734 2.91656C6.02734 2.37962 6.46263 1.94434 6.99957 1.94434Z"
                        fill="white" />
                      <path
                        d="M6.99957 1.94434C7.5365 1.94434 7.97179 2.37962 7.97179 2.91656C7.97179 3.4535 7.5365 3.88878 6.99957 3.88878C6.46263 3.88878 6.02734 3.4535 6.02734 2.91656C6.02734 2.37962 6.46263 1.94434 6.99957 1.94434ZM6.99957 2.33322C6.6774 2.33322 6.41623 2.5944 6.41623 2.91656C6.41623 3.23872 6.6774 3.49989 6.99957 3.49989C7.32173 3.49989 7.5829 3.23872 7.5829 2.91656C7.5829 2.5944 7.32173 2.33322 6.99957 2.33322Z"
                        fill="white" />
                      <path d="M7.19477 10.8888V5.44434H6.80588H6.41699" fill="white" />
                      <path
                        d="M6.41645 10.8892V6.22255C5.98689 6.22255 5.63867 5.87432 5.63867 5.44477C5.63867 5.01522 5.98689 4.66699 6.41645 4.66699H7.19423L7.27398 4.67079C7.66608 4.71071 7.97201 5.04213 7.97201 5.44477V10.8892C7.97201 11.3188 7.70354 11.3452 7.27398 11.3452C6.84443 11.3452 6.41645 11.3188 6.41645 10.8892Z"
                        fill="white" />
                      <path
                        d="M8.55566 10C8.98522 10 9.33344 10.3482 9.33344 10.7778C9.33344 11.2073 8.98522 11.5556 8.55566 11.5556H5.83344C5.40389 11.5556 5.05566 11.2073 5.05566 10.7778C5.05566 10.3482 5.40389 10 5.83344 10H8.55566Z"
                        fill="white" />
                    </svg>
                    <template #content>
                      <div style="width: 300px;">
                        由算法根据您的全量活跃设备预测得出，不受版本覆盖率影响。
                      </div>
                    </template>
                  </el-tooltip>

                </div>
                <div class="card-tab" :class="{ active: activeTab === Type.RECALL }"
                  @click="handleTabClick(Type.RECALL)">卸载召回设备（预测）
                  <el-tooltip effect="light" content="" placement="right-start">
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"
                      xmlns="http://www.w3.org/2000/svg">
                      <path
                        d="M7 14C8.93298 14 10.683 13.2165 11.9497 11.9497C13.2165 10.683 14 8.93298 14 7C14 5.06702 13.2165 3.31702 11.9497 2.05025C10.683 0.783503 8.93298 0 7 0C5.06702 0 3.31702 0.783503 2.05025 2.05025C0.783503 3.31702 0 5.06702 0 7C0 8.93298 0.783503 10.683 2.05025 11.9497C3.31702 13.2165 5.06702 14 7 14Z"
                        fill="#1B4D88" fill-opacity="0.4" />
                      <path fill-rule="evenodd" clip-rule="evenodd"
                        d="M6.99957 1.94434C7.5365 1.94434 7.97179 2.37962 7.97179 2.91656C7.97179 3.4535 7.5365 3.88878 6.99957 3.88878C6.46263 3.88878 6.02734 3.4535 6.02734 2.91656C6.02734 2.37962 6.46263 1.94434 6.99957 1.94434Z"
                        fill="white" />
                      <path
                        d="M6.99957 1.94434C7.5365 1.94434 7.97179 2.37962 7.97179 2.91656C7.97179 3.4535 7.5365 3.88878 6.99957 3.88878C6.46263 3.88878 6.02734 3.4535 6.02734 2.91656C6.02734 2.37962 6.46263 1.94434 6.99957 1.94434ZM6.99957 2.33322C6.6774 2.33322 6.41623 2.5944 6.41623 2.91656C6.41623 3.23872 6.6774 3.49989 6.99957 3.49989C7.32173 3.49989 7.5829 3.23872 7.5829 2.91656C7.5829 2.5944 7.32173 2.33322 6.99957 2.33322Z"
                        fill="white" />
                      <path d="M7.19477 10.8888V5.44434H6.80588H6.41699" fill="white" />
                      <path
                        d="M6.41645 10.8892V6.22255C5.98689 6.22255 5.63867 5.87432 5.63867 5.44477C5.63867 5.01522 5.98689 4.66699 6.41645 4.66699H7.19423L7.27398 4.67079C7.66608 4.71071 7.97201 5.04213 7.97201 5.44477V10.8892C7.97201 11.3188 7.70354 11.3452 7.27398 11.3452C6.84443 11.3452 6.41645 11.3188 6.41645 10.8892Z"
                        fill="white" />
                      <path
                        d="M8.55566 10C8.98522 10 9.33344 10.3482 9.33344 10.7778C9.33344 11.2073 8.98522 11.5556 8.55566 11.5556H5.83344C5.40389 11.5556 5.05566 11.2073 5.05566 10.7778C5.05566 10.3482 5.40389 10 5.83344 10H8.55566Z"
                        fill="white" />
                    </svg>
                    <template #content>
                      <div style="width: 300px;">
                        由卸载流失设备（预测）推测得出，预测为卸载的设备在当前周期下重新安装，即为卸载召回设备（预测）
                      </div>
                    </template>
                  </el-tooltip>
                </div>
              </div>
              <!-- 折线图 -->
              <div class="chart-container">
                <LineChart :data="currentChartData" :color="'#167af0'" height="270px"
                  :smooth="false" :area-style="true" :title="activeTab === Type.CHURN ? '卸载流失设备' : '卸载召回设备'" :showLegend="true" />
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="12" style="padding: 0 12px 12px; row-gap: 12px;">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-card shadow="none">
            <div class="trend-container">
              <div class="card-title" style="margin-bottom: 53px;">安装卸载比</div>
              <!-- 折线图 -->
              <div class="chart-container">
                <LineChart :data="data" :color="'#167af0'" height="270px" :showLegend="true"
                  :smooth="false" :area-style="true" :isMultiSeries="true" :seriesNames="seriesNames" />
              </div>
              
              <el-divider style="margin: 30px 0; background: rgba(230, 230, 230, 1);"/>

              <!-- 表格 -->
              <ExportToCSV :data="formatData" :columns="columns" :fileName="''" :hide-table="false" :tableStyle="{maxWidth: '1476px'}" />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts" name="churnAscribe" setup>
import LineChart from '/@/views/count/components/LineChart.vue'
import ExportToCSV from '/@/views/count/components/ExportToCSV.vue';
import { ref, computed } from 'vue'
import LayoutHeader from '/@/views/count/components/LayoutHeader.vue';
import { uninstallPredict, predictDetail } from '/@/api/count/churn';
import { formatDate } from '/@/utils/formatTime';

// 类型枚举
enum Type {
  CHURN = 0,
  RECALL = 1
}

const activeTab = ref(Type.CHURN);
const currentChartData = ref([] as any[])

const handleTabClick = (tab: number) => {
  activeTab.value = tab
  getUninstallPredict();
}

const data = ref([
  // { date: '2025-01-01', values: [{ value: 1, seriesName: '当前应用' }, { value: 2, seriesName: '移动视频行业TOP5' }, { value: 5, seriesName: '医疗服务行业TOP5' }] },
])

const columns = ref([
  {prop: 'date', label: '日期'},
  // {prop: 'app1', label: '当前应用'},
])

const seriesNames = computed(() => {
  return columns.value.filter((item: any) => item.prop !== 'date').map((item: any) => item.label)
})

const formatData = computed(() => {
  return data.value.map((item: any) => {
    const formattedItem: any = {
      date: item.date
    };
    
    // 动态添加每个系列的数据
    item.values.forEach((valueItem: any, index: number) => {
      const propName = `app${index + 1}`;
      formattedItem[propName] = valueItem.value;
    });
    
    return formattedItem;
  })
})

const getUninstallPredict = (data?: any) => {
  uninstallPredict({
    type: activeTab.value,
    cycle: 'week',
    ...data
  }).then((res) => {
    if(res.code === 0 && res.data?.length > 0) {
      currentChartData.value = res.data.map((item: any) => ({
        date: formatDate(new Date(item.predictTime), 'YYYY-mm-dd'),
        value: activeTab.value === Type.CHURN ? item.uninstallCount : item.recallCount
      }))
    }
  })
}

const getPredictDetail = (params?: any) => {
  predictDetail({
    cycle: 'week',
    ...params
  }).then((res) => {
    console.log(res);
    const newColumns: any[] = []
    if(res.code === 0 && res.data?.length > 0) {
      columns.value = [];
      data.value = res.data.map((item: any, index: number) => {
        let rowData = {
          date: formatDate(new Date(item.date), 'YYYY-mm-dd'),
          values: [] as {value: number, seriesName: string}[]
        }

        item.type.forEach((type: any, _index: number) => {
          const [key, _value] = Object.entries(type)[0];
          console.log(key, _value);
          rowData.values.push({
            value: _value as number,
            seriesName: key
          })
          newColumns.push({
            prop: 'app' + (1+_index),
            label: key
          })
        })

        if(index === 0) {
          columns.value = [
            {prop: 'date', label: '日期'},
            ...newColumns
          ];
        }

        console.log(columns.value);
        return rowData;
      })
      data.value = data.value.sort((a: any, b: any) => {
        return new Date(a.date).getTime() - new Date(b.date).getTime()
      })
      console.log(data.value);
    }
  })
}

onMounted(() => {
  getUninstallPredict();
  getPredictDetail();
})
</script>
<style scoped lang="scss">
@import '/@/views/count/styles/common.scss';

svg {
  vertical-align: middle;
  margin: 0 0 0 12px;
}

.ascribe {
  font-family: Source Han Sans SC;
  color: rgba(18, 18, 18, 1);

  .top-info {
    color: rgba(18, 18, 18, 1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
    margin: -2.5px 0;

    .title {
      font-size: 16px;
      font-weight: 500;
      line-height: 20px;
      padding: 4px 0;
    }

    .data-source-status {
      font-weight: 400;
      font-size: 14px;
      line-height: 20px;
      color: rgba(18, 18, 18, 1);
      padding: 4px 0;
    }
  }

  .trend-container {
    padding: 10px 14px;

    .title {
      line-height: 19px;
      font-weight: 500;
      font-size: 16px;
      padding-left: 12px;
      position: relative;
      margin-bottom: 53px;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 14px;
        background: rgba(22, 122, 240, 1);
      }
    }

    .card-tabs {
      width: 100%;
      max-width: 1476px;
      margin: 0 auto 0;

      .card-tab {
        svg {
          margin: 0;
        }
      }
    }

    .chart-container {
      // margin: 20px 85px 0;
      width: 100%;
      max-width: 1476px;
      margin: 20px auto 0;
      text-align: center;
    }

    .echarts-name {
      display: inline-block;
      margin: 28px auto 0;
      padding-left: 16px;
      font-weight: 400;
      font-size: 14px;
      line-height: 20px;
      color: rgba(18, 18, 18, 1);
      position: relative;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8px;
        height: 8px;
        background: rgba(22, 122, 240, 1);
        border-radius: 50%;
      }
    }

    .table-container {
      // padding: 0 85px;
      width: 100%;
      max-width: 1476px;
      margin: 0 auto;

      .btn-toggle-table {
        font-weight: 500;
        font-size: 14px;
        line-height: 20px;
        color: rgba(22, 122, 240, 1);
        margin-bottom: 20px;
        cursor: pointer;

        svg {
          transition: transform 0.3s ease-in-out;
        }

        &.hide-table svg {
          transform: rotate(-180deg);
        }
      }

      .table-container {
        margin-top: 20px;
      }
    }
  }
}
</style>
