<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset" />

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData" :showSelection="true"
        @selection-change="handleSelectionChange" @select-all="handleSelectAll" @select="handleSelect"
        :revenue="totalRevenue">
		<el-table-column prop="userId" label="查看明细" width="130">
		  <template #default="scope">
		    <el-button type="primary" @click="lookDetail(scope.row)">查看明细</el-button>
		  </template>
		</el-table-column>
		<el-table-column prop="channelCode" label="渠道码" />
		<el-table-column prop="userId" label="用户ID" />
		<el-table-column prop="headImage" label="用户头像" >
			<template #default="scope">
				<el-image style="width: 80px;height: 80px;border-radius: 50%;"
				 :src="scope.row.headImage" :preview-src-list="[scope.row.headImage]" fit="cover" preview-teleported="true"   preview-z-index="9999"></el-image>
			</template>
		</el-table-column>
		<el-table-column prop="nickName" label="用户昵称" />
		<el-table-column prop="phone" label="手机号" />
		<el-table-column prop="realName" label="真实姓名" />
		<el-table-column prop="idCard" label="身份证号" />
		<!-- <el-table-column prop="userStatus" label="用户状态" ></el-table-column> -->
		<el-table-column prop="userType" label="用户类型" >
			<template #default="scope">
				{{ scope.row.userType == 1?'app':scope.row.userType == 2?'平台':'代理端' }}
			</template>
		</el-table-column>
		<!-- <el-table-column prop="rewardBalance" label="悬赏余额" /> -->
		<!-- <el-table-column prop="taskBalance" label="任务余额" /> -->
		<el-table-column prop="totalIncome" label="总收益" />
		<el-table-column prop="loginTime" width="160" label="最后登录时间" >
			<template #default="scope">
				{{ formatDateFull(scope.row.loginTime) }}
			</template>
		</el-table-column>
		<el-table-column prop="" width="100" label="操作" >
			<template #default="scope">
				<el-button type="text" @click="handleView(scope.row)"> <el-icon size="16"><View /></el-icon> </el-button>
			</template>
		</el-table-column>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
		<Table @getTableData="changeTableDetailData" v-model:page="pageDetail" ref="tableDetail" :data="tableDetailData" >
				<el-table-column prop="orderInfo" label="订单名称" />
				<el-table-column prop="createTime" label="订单时间" />
				<el-table-column prop="amount" label="订单金额" />
				<el-table-column prop="serviceFee" label="平台收取的服务费/手续费" />
		</Table>
    </Layer>
	<!-- 查看详情 -->
	<Layer :layer="layerView" @close="layerView.show = false">
	  <div class="revenue-container">
	    <!-- 1. 收益类型切换 + 日期筛选栏 -->
	    <div class="revenue-header">
	      <!-- 付费/任务收益切换按钮 -->
	      <el-button-group class="revenue-type-btn">
	        <el-button
	          :type="activeRevenueType === 'pay' ? 'primary' : 'default'"
	          @click="activeRevenueType = 'pay';changeTableDetail()"
	        >
	          付费收益
	        </el-button>
	        <el-button
	          :type="activeRevenueType === 'task' ? 'primary' : 'default'"
	          @click="activeRevenueType = 'task';changeTableDetail()"
	        >
	          任务收益
	        </el-button>
	      </el-button-group>
	
	      <!-- 快捷日期 + 日期范围筛选 -->
	      <div class="date-filter-group">
	        <el-button-group class="quick-date-btn">
	          <el-button
	            :type="activeQuickDate === 'today' ? 'primary' : 'default'"
	            @click="handleQuickDate('today')"
	          >
	            当日
	          </el-button>
	          <el-button
	            :type="activeQuickDate === 'yesterday' ? 'primary' : 'default'"
	            @click="handleQuickDate('yesterday')"
	          >
	            昨天
	          </el-button>
	          <el-button
	            :type="activeQuickDate === 'sevenDays' ? 'primary' : 'default'"
	            @click="handleQuickDate('sevenDays')"
	          >
	            七天
	          </el-button>
	        </el-button-group>
	
	        <el-date-picker
	          v-model="revenueDateRange"
	          type="daterange"
	          range-separator="至"
	          start-placeholder="开始日期"
	          end-placeholder="结束日期"
	          style="width: 240px; margin-left: 12px;"
			  format="YYYY-MM-DD"
			  value-format="YYYY-MM-DD"
	          @change="fetchRevenueData();activeQuickDate=null"
	        />
	      </div>
	    </div>
	
	    <!-- 2. 收益表格（根据类型切换） -->
	    <div class="revenue-table-wrap">
	      <!-- 付费收益表格 -->
	      <Table
	        v-if="activeRevenueType === 'pay'"
	        :data="payRevenueList"
	        border
	        class="revenue-table"
	        empty-text="暂无付费收益记录"
			@getTableData="changeTableDetail"
			v-model:page="pageDetail"
			ref="table1"
	        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 500 }"
	      >
	        <el-table-column prop="orderInfo" label="订单名称" min-width="160" align="center" />
	        <el-table-column prop="createTime" label="时间" min-width="180" align="center">
	          <template #default="scope">
	            {{ formatDateFull(scope.row.createTime) || '--' }}
	          </template>
	        </el-table-column>
	        <el-table-column prop="channelEarningSum" label="收益金额(元)" min-width="140" align="center">
	          <template #default="scope">
	            {{ scope.row.channelEarningSum ? scope.row.channelEarningSum.toFixed(2) : '0.00' }}
	          </template>
	        </el-table-column>
	      </Table>
	
	      <!-- 任务收益表格 -->
	      <Table
	        v-if="activeRevenueType === 'task'"
	        :data="taskRevenueList"
	        border
	        class="revenue-table"
	        empty-text="暂无任务收益记录"
			@getTableData="changeTableDetail"
			v-model:page="pageDetail"
			ref="table2"
	        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 500 }"
	      >
	        <el-table-column prop="taskTitle" label="订单名称" min-width="160" align="center"></el-table-column>
	        <el-table-column prop="createTime" label="时间" min-width="180" align="center">
	          <template #default="scope">
	            {{ formatDateFull(scope.row.createTime) || '--' }}
	          </template>
	        </el-table-column>
	        <el-table-column prop="channelEarningSum" label="收益金额(元)" min-width="140" align="center">
	          <template #default="scope">
	            {{ scope.row.channelEarningSum ? scope.row.channelEarningSum.toFixed(2) : '0.00' }}
	          </template>
	        </el-table-column>
	      </Table>
	    </div>
	
	    <!-- 3. 合计收益统计行 -->
	    <div class="revenue-total">
	      <span class="total-label">合计收益:</span>
	      <span class="total-amount">{{ activeRevenueType === 'pay' ? payTotalAmount : taskTotalAmount }}元</span>
	    </div>
	  </div>
	</Layer>
  </div>
</template>

<script setup>
import { onBeforeMount,computed, ref, reactive, nextTick } from "vue";
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from '@/components/layer/index.vue'
import { FullScreen } from '@element-plus/icons'
import { ElMessage, ElLoading } from 'element-plus'
import { View } from "@element-plus/icons-vue";
import { invitationCodeUser,getUserList,orderPageList } from '@/api/userModule.js'
import { convertUTCToBeijing, getTodayRangeLocal,formatDateFull } from '@/utils/index.js'
import { statisticsHomePart4,statisticsHomePart5 } from '@/api/dashboard.js'
import { useStore } from 'vuex'

const store = useStore()
const parentId = computed(() => store.state.user.info.parentId);
console.log('parentId',parentId.value)
const tableData = ref([]);
const table = ref(null)
const tableDetail = ref(null)
const tableDetailData = ref([]);
// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const pageDetail = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});


const formSearch = ref({
  nickName: undefined,// 用户昵称
  phone: undefined,// 用户手机号
  pageNum: 1,// 当前页码
  pageSize: 10,// 当前页数量(查询量)
  loginTime: undefined, //登录时间
});

const dynamicFormItems = ref([])

onBeforeMount(() => {
  settingData()
  getList();
});
const curUserId = ref('') // 用户id
const lookDetail = (row)=>{
	curUserId.value = row.userId
	layer.value.show = true
	getDetailList()
}
// 获取缓存数据设置筛选数据
const settingData = async () => {
    dynamicFormItems.value = [
      {
        label: '用户昵称',
        prop: 'nickName',
        type: 'input',
        needEnterEvent: true
      },
      {
        label: '用户手机号',
        prop: 'phone',
        type: 'input',
        needEnterEvent: true
      },
	  { label: '登录时间', prop: 'loginTime', type: 'daterange' },
    ]
}


const firstApp = ref('')

const totalRevenue = ref(0)

// 分页数据
const getList = async (timeout = 0) => {
  // openFullScreen('数据请求中，请勿重复点击！！！')
  return new Promise((resolve) => {
    setTimeout(async () => {
      try {
		let apiRequest =  parentId.value ? invitationCodeUser : getUserList
        const listRes = await apiRequest({...formSearch.value })
		console.log('listRes',listRes)
        tableData.value = listRes.data.records;
        page.total = listRes.data.total;
        resolve(true);
      } catch (e) {
        console.log('数据请求超时或报错', e)
        resolve(false);
      } finally {
		  
      }
    }, timeout)
  });
};
const getDetailList = ()=>{
	orderPageList({
		...pageDetail,
		userId:curUserId.value
	}).then(res=>{
		tableDetailData.value = res.data.records;
		pageDetail.total = res.data.total;
	})
}
const changeTableData = (type) => {
	formSearch.value.pageNum =  page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	getList();
};

const changeTableDetailData = ()=>{
	formSearch.value.pageNum = page.pageNum;
	formSearch.value.pageSize = page.pageSize;
	getDetailList();
}

// 1. 收益表格核心响应式变量
const activeRevenueType = ref('pay'); // 当前选中收益类型：pay-付费收益，task-任务收益
const activeQuickDate = ref('today'); // 当前快捷日期：today-当日，yesterday-昨天，sevenDays-七天
const revenueDateRange = ref([]); // 日期范围选择器值
const payRevenueList = ref([]); // 付费收益数据列表
const taskRevenueList = ref([]); // 任务收益数据列表
const payTotalAmount = ref('0.00'); // 付费收益合计
const taskTotalAmount = ref('0.00'); // 任务收益合计
const currentViewUserId = ref(''); // 当前查看详情的用户ID

// 2. 快捷日期选择处理（匹配图片中的“当日/昨天/七天”）
const handleQuickDate = (type) => {
  activeQuickDate.value = type;
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  const sevenDaysAgo = new Date(today);
  sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

  // 格式化日期为 YYYY-MM-DD
  const format = (date) => date.toISOString().split('T')[0];
  
  // 设置日期范围
  switch (type) {
    case 'today':
      revenueDateRange.value = [format(today), format(today)];
      break;
    case 'yesterday':
      revenueDateRange.value = [format(yesterday), format(yesterday)];
      break;
    case 'sevenDays':
      revenueDateRange.value = [format(sevenDaysAgo), format(today)];
      break;
  }
  // 重新拉取收益数据
  fetchRevenueData();
};
// 3. 拉取收益数据（复用 orderPageList API，区分付费/任务类型）
const fetchRevenueData = async () => {
  if (!currentViewUserId.value || !revenueDateRange.value.length) return;

  // 处理日期参数（格式：YYYY-MM-DD HH:mm:ss）
  const [startDate, endDate] = revenueDateRange.value;
  const params = {
    userId: currentViewUserId.value,
    beginTime: `${startDate}T00:00:00`,
    endTime: `${endDate}T00:00:00`,
    pageNum: pageDetail.pageNum,
    pageSize: pageDetail.pageSize
  };

  try {
	  // 付费收益
	  if(activeRevenueType.value == 'pay'){
		  // 获取付费收益
		  	statisticsHomePart4(params).then(res=>{
		  		payRevenueList.value = res.data.page.records
		  		pageDetail.total = res.data.page.total
				payTotalAmount.value = res.data.totalChannelEarningSum
		  	})
	  }else{
		  // 获取任务收益
		  	statisticsHomePart5(params).then(res=>{
		  		taskRevenueList.value = res.data.page.records
		  		pageDetail.total = res.data.page.total
				taskTotalAmount.value = res.data.totalChannelEarningSum
		  	})
	  }
  } catch (error) {
    ElMessage.error('获取收益数据失败');
    console.error('收益数据请求错误：', error);
  }
};

// 4. 重写 handleView 方法（打开详情弹窗时初始化数据）
const handleView = async (row) => {
  currentViewUserId.value = row.userId; // 记录当前查看的用户ID
  layerView.value.show = true; // 显示弹窗
  
  // 初始化日期（默认“当日”）
  const today = new Date();
  revenueDateRange.value = [today.toISOString().split('T')[0], today.toISOString().split('T')[0]];
  
  // 拉取初始收益数据
  await fetchRevenueData();
};

// 5. 重写 changeTableDetailData 方法（表格分页适配）
const changeTableDetail = () => {
  pageDetail.pageNum = pageDetail.pageNum;
  pageDetail.pageSize = pageDetail.pageSize;
  
  fetchRevenueData(); // 分页时重新拉取收益数据
};


// 搜索
const handleFormSubmitted = (formData) => {
  // console.log("接收到子组件传递的数据", formData);
  formSearch.value.pageNum = page.pageNum;
  formSearch.value.pageSize = page.pageSize;
  formSearch.value.nickName = formData.nickName;
  formSearch.value.phone = formData.phone;
  if(formData.loginTime){
	  formSearch.value.loginTimeStart = (convertUTCToBeijing(formData.loginTime[0], false) + ' 00:00:00') || undefined
	  formSearch.value.loginTimeEnd = (convertUTCToBeijing(formData.loginTime[1], false) + ' 23:59:59') || undefined
  }

  getList(0);
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    nickName: undefined,// 用户昵称
    pageNum: 1,// 当前页码
    pageSize: 10,// 当前页数量(查询量)
    // lastLoginTimeBegin: getTodayRangeLocal(), //最新登录时间开始
    // lastLoginTimeEnd:undefined //最新登录时间结束
  };

  page.pageNum = 1
  page.pageSize = 10
  page.total = 0
  getList();
  // settingData()
};

const selectData = ref([])
const currentAppName = ref(null) // 存储允许全选的 appName
// 选择监听器
const handleSelectionChange = (val) => {
  selectData.value = val
}

// 全选
const handleSelectAll = (selection) => {
  if (selection.length === 0) {
    // 全选取消
    currentAppName.value = null
    return
  }

  // 取第一个选中的 appName 作为基准
  const firstAppName = selection[0].appName
  // 先全部取消
  table.value.table.clearSelection()

  // 再只选中同一 appName 的行
  tableData.value.forEach(row => {
    if (row.appName === firstAppName) {
      table.value.table.toggleRowSelection(row, true)
    }
  })

  currentAppName.value = firstAppName

}

// 取消全选
const clearSelection = () => {
  currentAppName.value = null
  table.value.table.clearSelection()
}

// 单选
const handleSelect = (selection, row) => {
  // 如果是单选时第一次选中，就记录当前 appName
  if (selection.length === 1) {
    currentAppName.value = selection[0].appName
  }

  // 如果选了不同 appName 的数据，则取消
  if (selection.length > 0 && row.appName !== currentAppName.value) {
    table.value.table.toggleRowSelection(row, false)
    ElMessage.warning('只能选择同一个应用的用户哦')
  }
}

const loading = ref(null)

// 加载信息
const openFullScreen = (loadText) => {
  loading.value = ElLoading.service({
    lock: true,
    text: loadText,
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

const closeFullScreen = () => {
  loading.value.close()
}

// 弹窗
const layer = ref({
  show: false,
  title: "查看消费明细",
  showButton: false,
  // width: '500px',
  isMulty: false
});
const layerView = ref({
	show: false,
	title: "查看详情",
	showButton: false,
	// width: '500px',
	isMulty: false
})
const formEdit = ref({
  bannedLimit: undefined, //封禁期限
  bannedReason: undefined,//封禁原因
  bannedTargetId: undefined,//封禁目标ID
  bannedType: undefined,//封禁类型 1-渠道 2-平台
  operator: undefined,//操作人
  operatorName: undefined,//操作人名称
  userId: undefined, //用户ID
  appId: undefined,//应用ID
  userIds: undefined, //用户ID
})

const edit = (row, isMulty = 0) => {
  ruleForm.value?.resetFields()
  layer.value.isMulty = isMulty

  if (isMulty === 1) {
    layer.value.title = '批量封禁用户'
    formEdit.value = {}

  } else if(isMulty === 2) {
    layer.value.title = '批量封禁母包'
    formEdit.value = {}

  } else {
    layer.value.title = '封禁用户'

    formEdit.value.bannedTargetId = row.appId
    formEdit.value.bannedType = row.channelType
    formEdit.value.operator = store.state.user.info.loginName
    formEdit.value.operatorName = store.state.user.info.nickName
    formEdit.value.userId = row.userId
    formEdit.value.appId = row.appId
  }

  layer.value.show = true
}

const ruleForm = ref(null);

const rules = reactive({
  formEditbannedLimit: [
    { required: true, message: "请输入封禁期限", trigger: "blur" },
  ],
  bannedReason: [
    {
      required: true,
      message: "请输入封禁原因",
      trigger: "blur",
    },
  ],
});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      
    } else {
      console.log("error submit!", fields);
    }
  })
}

</script>

<style scoped lang="scss">
.layout-container {

  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    //flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}

.btn {
  display: flex;
  margin: 10px 0 -10px 30px;
}

.full-icon {
  position: absolute;
  right: 40px;
  top: 15px;
  cursor: pointer;
  padding: 8px;
  border-radius: 5px;
}

/* 收益容器整体样式 */
.revenue-container {
  padding: 16px;
}

/* 收益类型切换与日期筛选栏样式 */
.revenue-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
}

/* 收益类型切换按钮样式 */
.revenue-type-btn :deep(.el-button) {
  border-radius: 0;
  &:first-child {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  &:last-child {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
}

/* 日期筛选组样式 */
.date-filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quick-date-btn :deep(.el-button) {
  padding: 6px 12px;
  font-size: 12px;
}

/* 收益表格样式（穿透修改 Element Plus 表格） */
.revenue-table-wrap {
  margin-bottom: 12px;

  :deep(.revenue-table) {
    --el-table-border-color: #e5e7eb;
    --el-table-text-color: #303133;
    width: 100%;

    /* 表格行样式优化 */
    .el-table__body tr {
      background-color: #fff;
    }
    .el-table__body tr:hover > td {
      background-color: #f9fafb !important;
    }

    /* 表格单元格样式 */
    td.el-table__cell {
      border-bottom: 1px solid #f3f4f6 !important;
      padding: 12px 0;
      font-size: 13px;
    }

    /* 去除表格底部多余边框 */
    &::before {
      height: 0;
    }
  }
}

/* 合计收益行样式（匹配图片中的合计展示） */
.revenue-total {
  text-align: right;
  padding: 10px 0;
  margin-top: -8px;

  .total-label {
    color: #333;
    font-size: 16px;
    margin-right: 8px;
  }

  .total-amount {
    color: #cf2d2d;
    font-size: 20px;
    font-weight: 500;
  }
}

/* 适配弹窗宽度 */
:deep(.el-dialog__body) {
  padding: 16px;
  overflow: hidden;
}
</style>