<template>
   <div class="layout-padding">
    <div class="overview">
      <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="流失概况">
            <template #tooltip-content>
              流失概况展示您应用每周的卸载用户量和召回用户量，并展示趋势。
              <br /><span>卸载设备数：</span>当前时段内，有过卸载行为的设备去重数。
              若某设备在当前时段内卸载又重新安装、或多次卸载再安装，都算它为有过卸载行为的1个卸载设备。 
              <br /><span>卸载召回设备：</span>曾经被识别为卸载，当前时段内又被识别为重新安装的设备去重数。
              仅统计卸载后90天内重新安装的设备，卸载90天后重新安装的设备不算在卸载召回设备中。
              产品页面中，会在每周四刷新上周的卸载召回数据。
            </template>
            <template #content>
              <div class="top-content">
                <ProgressCard :title="'当周卸载流失设备数'" :counts="trendProgressData.uninstallCounts" :rates="trendProgressData.uninstallRates" />
                <ProgressCard :title="'当周卸载召回设备数'" :counts="trendProgressData.recallCounts" :rates="trendProgressData.recallRates" />
              </div>
            </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="title">流失趋势</div>
              <div class="tabs">
                <div class="tabs-item" :class="{ active: activeTab === 'churnTrend' }" @click="handleTabClick('churnTrend')">卸载流失设备</div>
                <div class="tabs-item" :class="{ active: activeTab === 'recallTrend' }" @click="handleTabClick('recallTrend')">卸载召回设备</div>
              </div>
              <!-- 折线图 -->
              <div class="chart-container">
                <LineChart :data="currentChartData" :color="'#167af0'" :title="currentChartTitle" height="270px"
                  :smooth="false" :area-style="true" />
                <div class="echarts-name">{{currentChartTitle}}</div>
              </div>
              
              <el-divider style="margin: 30px 0; background: rgba(230, 230, 230, 1);"/>

              <div class="table-container">
                <div class="btn-toggle-table" :class="{ 'hide-table': hideTable }" @click="hideTable = !hideTable">
                  {{ hideTable ? '展开' : '收起' }}明细数据<svg 
                    width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10.5 8.75L7 5.25L3.5 8.75" stroke="#167AF0" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                </div>

                <el-table class="statistics-table" :data="paginatedData" row-key="date" style="width: 100%"
                  :cell-style="cellStyle"
                  :header-cell-style="headerCellStyle"
                  v-if="!hideTable"
                  >
                  <el-table-column :label="'日期'" prop="date" show-overflow-tooltip>
                    <template #default="scope">
                      {{ scope.row.startDate }} - {{ scope.row.endDate }}
                    </template>
                  </el-table-column>
                  <el-table-column :label="'卸载流失设备'" :formatter="statusFormatter" prop="uninstallCounts" show-overflow-tooltip></el-table-column>
                  <el-table-column :label="'卸载召回设备'" :formatter="statusFormatter" prop="recallCounts" show-overflow-tooltip></el-table-column>
                </el-table>

                <pagination 
                  v-if="!hideTable"
                  @current-change="handleCurrentChange" 
                  @size-change="handleSizeChange" 
                  v-bind="state.pagination">
                </pagination>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
   </div>
</template>

<script lang="ts" name="churnOverview" setup>
import LineChart from '/@/views/count/components/LineChart.vue'
import { BasicTableProps, useTable } from '/@/hooks/table';
import { ref, computed, reactive } from 'vue'
import { uninstallTrend, uninstallTrendDetail } from '/@/api/count/churn'
import { formatDate } from '/@/utils/formatTime';
import ProgressCard from './ProgressCard.vue'
import LayoutHeader from '/@/views/count/components/LayoutHeader.vue'

const cellStyle = ref({
  textAlign: 'center',
  fontSize: '14px',
  height: '50px',
  background: 'transparent !important'
})

const headerCellStyle = ref({
  textAlign: 'center',
  border: 'none',
  background: 'rgba(244, 245, 250, 1)',
  height: '32px',
  color: 'rgba(100, 100, 100, 1)',
  fontSize: '14px',
})

const trendProgressData = ref({
  recallCounts: 0,  
  recallRates: 0,
  uninstallCounts: 0,
  uninstallRates: 0,
})

const activeTab = ref('churnTrend')

// 计算当前图表数据
const currentChartData = computed(() => {
  return dataList.value.map((item: any) => ({
    date: item.endDate,
    value: activeTab.value === 'churnTrend' ? item.uninstallCounts : item.recallCounts
  }))
})

// 计算当前图表标题
const currentChartTitle = computed(() => {
  return activeTab.value === 'churnTrend' ? '卸载流失设备' : '卸载召回设备'
})

const handleTabClick = (tab: string) => {
  activeTab.value = tab
} 

// 表格数据
const hideTable = ref(false);
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
  },
  pagination: {
    current: 1,
    size: 10,
    total: 0,
    pageSizes: [5, 10, 20, 50, 100]
  },
});

const dataList = ref([]);

const statusFormatter = (row: any, column: any, cellValue: any, index: any) => {
  return cellValue || '--';
}

const handleCurrentChange = (val: number) => {
  state.pagination!.current = val;
};

const handleSizeChange = (val: number) => {
  state.pagination!.size = val;
  state.pagination!.current = 1; // 切换每页条数时重置到第一页
};

// 计算分页后的数据
const paginatedData = computed(() => {
  if (!state.pagination || typeof state.pagination.current === 'undefined' || typeof state.pagination.size === 'undefined') {
    return dataList.value;
  }
  const start = (state.pagination.current - 1) * state.pagination.size;
  const end = start + state.pagination.size;
  return dataList.value.slice(start, end);
});

const getDate = (day: string, num: number) => {
  const [year, month, date] = day.split('-').map(item => parseInt(item));
  return formatDate(new Date(new Date(year, month-1, date - num)), 'YYYY-mm-dd');
}

const getUninstallTrend = () => {
  const today = new Date();
  let startDate = '';
  let endDate = '';
  let day = today.getDay();
  if (day>=4) {
    startDate = getDate(formatDate(today, 'YYYY-mm-dd'), day - 4 + 7);
    endDate = getDate(formatDate(today, 'YYYY-mm-dd'), day - 4 + 1);
  } else {
    startDate = getDate(formatDate(today, 'YYYY-mm-dd'), 14 - 4 + day);
    endDate = getDate(formatDate(today, 'YYYY-mm-dd'), 7 - 4 + day + 1);
  }
  uninstallTrend({
    startDate: startDate,
    endDate: endDate,
    timeUnit: 'week',
    pageNum: state.pagination!.current,
    pageSize: state.pagination!.size,
  }).then(res => {
    trendProgressData.value = res.data
  })
}

const getUninstallTrendDetail = () => {
  uninstallTrendDetail({
    startDate: formatDate(new Date(new Date().setDate(new Date().getDate() - 50)), 'YYYY-mm-dd'),
    endDate: formatDate(new Date(), 'YYYY-mm-dd'),
    timeUnit: 'week',
    pageNum: state.pagination!.current,
    pageSize: state.pagination!.size,
  }).then(res => {
    dataList.value = res?.data?.records || [];
    state.pagination!.total = res?.data?.total || 0;
  })
}

onMounted(() => {
  getUninstallTrend();
  getUninstallTrendDetail();
})

</script>
<style scoped lang="scss">
svg {
  vertical-align: middle;
  margin: 0 0 0 12px;
}
.overview {
  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;
  margin-bottom: 25px;


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

  .aside {
    display: flex;
  }

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

  .goto-smart-operation {
    padding: 4px 12px;
    border-radius: 4px;
    border: 1px solid rgba(22, 122, 240, 1);
    font-weight: 400;
    font-size: 14px;
    line-height: 20px;
    color: rgba(22, 122, 240, 1);
  }

}

.top-content {
  display: flex;
  gap: 20px;

  .content-item {
    display: flex;
    align-items: center;
    gap: 0;
    flex: 1;
    padding: 27.5px;
    justify-content: center;
  }

  .content-item-left {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 30px;
  }

  .content-item-right {
    // flex: 1;
  }

  .content-item-title {
    color: rgba(18, 18, 18, 1);
    font-weight: 400;
    font-size: 15px;
    line-height: 20px;
    margin-bottom: 12px;
  }

  .content-item-value {
    font-weight: 500;
    font-style: Medium;
    font-size: 28px;
    margin-bottom: 16px;
    line-height: 41px;
  }

  .content-item-percent {
    font-weight: 400;
    font-size: 14px;
    vertical-align: middle;
    line-height: 20px;
  }

  .content-item-percent span {
    color: rgba(0, 188, 113, 1);
  }
}

.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);
    }
  }

  .tabs {
    display: flex;
    width: 100%;
    max-width: 1476px;
    margin: 0 auto 0;
    .tabs-item {
      padding: 0 12px;
      height: 32px;
      line-height: 30px;
      border: 1px solid rgba(22, 122, 240, 1);
      text-align: center;
      color: rgba(22, 122, 240, 1);
      cursor: pointer;
      &.active {
        background: rgba(22, 122, 240, 1);
        color: #ffffff;
      }
    }
  }

  .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>
