<template>
  <div class="todayIncomeList">
    <!-- 头部 -->
    <div class="header">
      <el-button class="back-btn" @click="goBack"> 返回 </el-button>
      <h2 class="title">今日收益</h2>
    </div>
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        :pagination="true"
        :height="tableHeight"
      >
        <!-- 表格操作 -->
        <template #operation="scope">
          <el-button type="primary" link @click="toDetail(scope.row)"> 查看详情 </el-button>
        </template>
      </ProTable>
      <el-dialog v-model="dialogVisible" title="详情" width="500px">
        <h2 class="orderInfo">
          {{ unposted.storeName }}
        </h2>
        <el-row class="couponRow">
          <el-col :span="12"> 实际收益: &yen;{{ formatNumber(unposted.money / 100) }} </el-col>
          <el-col :span="12">
            {{ `技术服务费(${commissionRate}%)` }}:
            {{ formatNumber(unposted.commission / 100) }}
          </el-col>
        </el-row>
        <el-row class="couponRow">
          <el-col :span="12">
            售价: &yen;{{ formatNumber((Number(unposted.money) + Number(unposted.commission)) / 100) }}
          </el-col>
        </el-row>
        <h3 class="orderInfo">订单信息</h3>
        <div>
          <div class="couponRow">下单时间: {{ unposted.orderTime != null ? unposted.orderTime : "--" }}</div>
          <div class="couponRow">验券时间: {{ unposted.checkTime != null ? unposted.checkTime : "--" }}</div>
          <div class="couponRow">入账时间: {{ unposted.incomeTime != null ? unposted.incomeTime : "--" }}</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="tsx" name="voucherManagement">
import { computed, onActivated, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getGroupIncome } from "@/api/modules/homeEntry";
import { ElMessageBox } from "element-plus/es";
import { localGet } from "@/utils";
const commissionRate = localGet("commissionRate") || "";
const router = useRouter();
const dialogVisible = ref(false);
const unposted = ref<any>({});
// 计算表格高度
const tableHeight = ref<string>("calc(100vh - 200px)");
const toDetail = (row: any) => {
  dialogVisible.value = true;
  unposted.value = row;
};
// 格式化数字为千分位
const formatNumber = (value: any): string => {
  if (value === null || value === undefined || value === "") {
    return "0.00";
  }
  const num = typeof value === "string" ? parseFloat(value) : Number(value);
  if (isNaN(num)) {
    return "0.00";
  }
  // 保留两位小数并添加千分位
  return num.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};
// 返回
const goBack = () => {
  router.back();
};
// ProTable 实例（需要在使用它的地方之前定义）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: "storeName",
    label: "商品名称"
  },
  {
    prop: "money",
    label: "实际收益",
    render: scope => {
      return formatNumber(scope.row.money / 100);
    }
  },
  {
    prop: "price",
    label: "售价",
    render: scope => {
      return formatNumber((Number(scope.row.money) + Number(scope.row.commission)) / 100);
    }
  },
  {
    prop: "commission",
    label: "技术服务费",
    render: scope => {
      return formatNumber(scope.row.commission / 100);
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  storeId: localGet("createdId"),
  incomeType: 0,
  startTime: null,
  endTime: null
});
// 页面加载时触发查询
onMounted(async () => {
  proTable.value?.getTableList();
});

// 从其他页面返回时触发查询
onActivated(() => {
  proTable.value?.getTableList();
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.incomeDetailsRecordVoList,
    total: data.data?.total || data.total || 0
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  // 获取当前日期，格式为 YYYY-MM-DD
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, "0");
  const day = String(today.getDate()).padStart(2, "0");
  const currentDate = `${year}-${month}-${day}`;

  let newParams = JSON.parse(JSON.stringify(params));
  // 设置固定参数
  newParams.date = currentDate;
  newParams.incomeType = 1;
  // 确保分页参数存在
  newParams.page = params.page || params.pageNum || 1;
  newParams.size = params.size || params.pageSize || 10;

  return getGroupIncome(newParams);
};
</script>

<style lang="scss" scoped>
.todayIncomeList {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}
.table-box {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
  :deep(.table-main) {
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: hidden;
    .el-table {
      flex: 1;
      overflow: hidden;
    }
    .el-table__body-wrapper {
      overflow-y: auto !important;
    }
  }
}
.header {
  position: relative;
  display: flex;
  align-items: center;
  padding: 15px;
  background: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 12px rgb(0 0 0 / 5%);
  .back-btn {
    padding: 8px 16px;
    font-size: 14px;
    color: #606266;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    &:hover {
      color: #409eff;
      background-color: #ecf5ff;
      border-color: #b3d8ff;
    }
  }
  .title {
    position: absolute;
    left: 50%;
    margin: 0;
    font-size: 18px;
    font-weight: bold;
    color: #333333;
    transform: translateX(-50%);
  }
}

// 在组件样式中添加
.date-range {
  display: block; // 确保换行生效
  padding: 0 8px; // 可选：增加内边距
  word-wrap: break-word; // 长单词内换行
  white-space: normal; // 允许自然换行
}
.table-header-btn {
  .button {
    margin-bottom: 10px;
  }
  .tabs {
    :deep(.el-tabs__nav-wrap::after) {
      height: 0;
    }
  }
}
.orderInfo {
  padding-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}
.couponRow {
  padding-bottom: 20px;
}
.couponRow:last-child {
  padding-bottom: 0;
}
.reject-reason-content {
  padding: 20px 0;
  .reject-reason-item {
    display: flex;
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    .reject-reason-label {
      flex-shrink: 0;
      min-width: 100px;
      font-size: 14px;
      font-weight: 500;
      color: #606266;
    }
    .reject-reason-value {
      flex: 1;
      font-size: 14px;
      color: #303133;
      word-break: break-word;
      &.reject-reason-text {
        min-height: 80px;
        padding: 12px;
        line-height: 1.6;
        white-space: pre-wrap;
        background-color: #f5f7fa;
        border-radius: 4px;
      }
    }
  }
}
</style>
