<template>
  <div class="dashboard-container">
    <!-- 顶部两个图表 -->
    <div class="chart-row">
      <!-- 用户增长数量柱状图 -->
      <div class="chart-card">
        <div class="chart-header">
          <span class="table-header">用户增长数量</span>
          <el-date-picker
            v-model="userDateRange"
			@change="userDateRangeChange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
			format="YYYY-MM-DD"
			value-format="YYYY-MM-DD"
            size="small"
            style="font-size: 12px;max-width: 220px;"
          />
        </div>
        <div class="chart-content" ref="userChartRef" style="height: 220px;"></div>
      </div>

      <!-- 收益金额折线图 -->
      <div class="chart-card">
        <div class="chart-header">
          <span class="table-header">收益金额</span>
          <el-date-picker
            v-model="incomeDateRange"
			@change="incomeDateRangeChange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
			format="YYYY-MM-DD"
			value-format="YYYY-MM-DD"
            size="small"
            style="font-size: 12px;max-width: 220px;"
          />
        </div>
        <div class="chart-content" ref="incomeChartRef" style="height: 220px;"></div>
      </div>
    </div>

    <!-- 底部两个表格 -->
    <div class="table-row">
      <!-- 付费收益表格 -->
      <div class="table-card">
        <div class="table-header">付费收益</div>
        <el-table ref="payIncomeTable" :data="payIncomeList" v-model:page="payIncomePage"  @getTableData="getPayIncome"  border style="width: 100%; font-size: 12px;">
          <el-table-column prop="name" label="名称" >
			  <template #default="scope">
				  <div style="display: flex;">
					  <el-image :src="scope.row.headImage" :preview-src-list="[scope.row.headImage]" fit="cover" preview-teleported="true"  style="min-width: 50px;height: 50px;border-radius: 50%;"></el-image>
					  <div style="margin-left: 10px;">
						  <div>
							  昵称：{{ scope.row.nickName }}
						  </div>
						  <div>
							  ID：{{ scope.row.userId }}
						  </div>
					  </div>
				  </div>
			  </template>
		  </el-table-column>
          <el-table-column prop="orderInfo" width="180" label="订单名称" />
          <el-table-column prop="createTime" width="140" label="时间" >
	          <template #default="scope">
	            {{ formatDateFull(scope.row.createTime) || '--' }}
	          </template>
	        </el-table-column>
          <el-table-column prop="channelEarningSum" width="100" label="收益金额(元)" />
        </el-table>
		<el-pagination style="margin-top: 10px;" v-model:current-page="payIncomePage.pageNum" class="system-page" background
		  layout="total, sizes, prev, pager, next, jumper" :total="payIncomePage.total" :page-size="payIncomePage.pageSize"
		  @current-change="($event)=>handleCurrentChange($event,1)" @size-change="($event)=>handleSizeChange($event,1)">
		</el-pagination>
      </div>

      <!-- 任务收益表格 -->
      <div class="table-card">
        <div class="table-header">任务收益</div>
        <el-table ref="taskIncomeTable" :data="taskIncomeList" v-model:page="taskIncomePage"  @getTableData="getTaskIncome" border style="width: 100%; font-size: 12px;">
		  <el-table-column prop="name" label="名称" >
			  <template #default="scope">
				  <div style="display: flex;">
					  <el-image :src="scope.row.headImage" :preview-src-list="[scope.row.headImage]" fit="cover" preview-teleported="true"  style="min-width: 50px;height: 50px;border-radius: 50%;"></el-image>
					  <div style="margin-left: 10px;">
						  <div>
							  昵称：{{ scope.row.nickName }}
						  </div>
						  <div>
							  ID：{{ scope.row.userId }}
						  </div>
					  </div>
				  </div>
			  </template>
		  </el-table-column>
          <el-table-column prop="consumptionType" width="100" label="类型" />
          <el-table-column prop="taskTitle" label="任务名称" />
          <el-table-column prop="createTime" width="140" label="时间" >
	          <template #default="scope">
	            {{ formatDateFull(scope.row.createTime) || '--' }}
	          </template>
	        </el-table-column>
          <el-table-column prop="channelEarningSum" width="100" label="收益金额(元)" />
        </el-table>
		<el-pagination style="margin-top: 10px;" v-model:current-page="taskIncomePage.pageNum" class="system-page" background
		  layout="total, sizes, prev, pager, next, jumper" :total="taskIncomePage.total" :page-size="taskIncomePage.pageSize"
		  @current-change="($event)=>handleCurrentChange($event,2)" @size-change="($event)=>handleSizeChange($event,2)">
		</el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { ElDatePicker, ElTable, ElTableColumn } from 'element-plus';
import { statisticsHomePart2,statisticsHomePart3,statisticsHomePart4,statisticsHomePart5 } from '@/api/dashboard.js'
import Table from "@/components/table/index.vue";
import { formatDateFull } from '@/utils/index.js'
// userId  beginTime   endTime
// 工具函数：格式化日期为 YYYY-MM-DD 格式
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 计算近7天的日期范围（当前日期的前6天 至 当前日期）
const getRecent7Days = () => {
  const endDate = new Date(); // 当前日期
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 6); // 前6天，合计7天

  return [formatDate(startDate), formatDate(endDate)];
};

// 日期范围数据 - 默认值改为近7天
const userDateRange = ref(getRecent7Days());
const incomeDateRange = ref(getRecent7Days());

// 图表容器ref
const userChartRef = ref(null);
const incomeChartRef = ref(null);

// 付费收益表格数据
const payIncomeList = ref([]);

// 任务收益表格数据
const taskIncomeList = ref([]);
const userDateRangeChange = ()=>{
	initUserChart()
}
// 初始化用户增长柱状图
const initUserChart = () => {
  const chart = echarts.init(userChartRef.value);
  var dateXArr = []
  var userYArr = []
  // 获取用户增长数量数据
  statisticsHomePart2({
	  beginTime:userDateRange.value[0]+'T00:00:00',
	  endTime:userDateRange.value[1]+'T00:00:00',//+'T23:59:59',
  }).then(res=>{
	  if (res.data) {
	        // 动态提取键值对到数组
	        dateXArr = Object.keys(res.data);
	        userYArr = Object.values(res.data);
			chart.setOption({
			  tooltip: { trigger: 'axis' },
			  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
			  xAxis: {
			    type: 'category',
			    data: dateXArr || [],
				axisLabel: {
				   rotate: dateXArr.length > 7 ? -45 : 0, // 旋转标签
				   fontSize: 10
				 },
			  },
			  yAxis: { type: 'value', min: 0 },
			  series: [
			    {
			      data: userYArr || [],
			      type: 'bar',
			      itemStyle: { color: '#3370FF' }
			    }
			  ]
			});
			// 自适应窗口变化
			window.addEventListener('resize', () => chart.resize());
	    }
  })
};
const incomeDateRangeChange = ()=>{
	initIncomeChart()
}
// 初始化收益金额折线图
const initIncomeChart = () => {
  const chart = echarts.init(incomeChartRef.value);
  var XArr = []
  var YArr = []
  statisticsHomePart3({
	  beginTime:incomeDateRange.value[0]+'T00:00:00',
	  endTime:incomeDateRange.value[1]+'T00:00:00',//+'T23:59:59',
  }).then(res=>{
	  if (res.data) {
	        // 动态提取键值对到数组
	        XArr = Object.keys(res.data);
	        YArr = Object.values(res.data);
			chart.setOption({
			  tooltip: { trigger: 'axis' },
			  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
			  xAxis: {
			    type: 'category',
			    data: XArr || [],
				axisLabel: {
				   rotate: XArr.length > 7 ? -45 : 0, // 旋转标签
				   fontSize: 10
				 },
			  },
			  yAxis: { type: 'value', min: 0 },
			  series: [
			    {
			      data: YArr || [],
			      type: 'bar',
			      itemStyle: { color: '#3370FF' }
			    }
			  ]
			});
			// 自适应窗口变化
			window.addEventListener('resize', () => chart.resize());
	    }
  })
};
const payIncomePage = ref({
	pageNum:1,
	pageSize:10,
	total:0,
})
const taskIncomePage = ref({
	pageNum:1,
	pageSize:10,
	total:0,
})
// 获取付费收益
const getPayIncome = ()=>{
	statisticsHomePart4({
		userId:null,
		...payIncomePage.value
	}).then(res=>{
		payIncomeList.value = res.data.page.records
		payIncomePage.value.total = res.data.page.total
		
	})
}
// 获取任务收益
const getTaskIncome = ()=>{
	statisticsHomePart5({
		userId:null,
		...taskIncomePage.value
	}).then(res=>{
		taskIncomeList.value = res.data.page.records
		taskIncomePage.value.total = res.data.page.total
	})
}
const handleCurrentChange = (val,type)=>{
	console.log(val,type)
	if(type == 1){
		payIncomePage.value.pageNum = val
		getPayIncome()
	}else{
		taskIncomePage.value.pageNum = val
		getTaskIncome()
	}
}
const handleSizeChange = (val,type)=>{
	console.log(val,type)
	if(type == 1){
		payIncomePage.value.pageSize = val
		getPayIncome()
	}else{
		taskIncomePage.value.pageSize = val
		getTaskIncome()
	}
}
// 页面挂载后初始化图表
onMounted(() => {
  // 获取用户增长数量统计图
  initUserChart();
  // 获取收益金额统计图
  initIncomeChart();
  // 获取付费收益列表
  getPayIncome()
  // 获取任务收益列表
  getTaskIncome()
});
</script>

<style scoped lang="scss">
.dashboard-container {
  /* padding: 20px; */
  /* background: #F5F7FA; */
  min-height: 100vh;
}

.chart-row, .table-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card, .table-card {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.table-card{
	padding: 16px 16px 50px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 500;
}

.table-header {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 12px;
  text-align: left;
}
.system-page {

    &::before {
      content: '';
    }
  }
</style>