<template>
  <div class="reconciled">
    <!-- 头部 -->
    <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">
        <h3 class="orderInfo">
          {{ reconciled.couponName }}
        </h3>
        <el-row class="couponRow">
          <el-col :span="12"> 实际收益: &yen;{{ formatNumber(reconciled.money / 100) }} </el-col>
          <el-col :span="12">
            <!-- {{ `技术服务费(${unposted.commission / 100 || 3}%)` }}: 后续后端会变成可控的-->
            {{ `技术服务费(${commissionRate}%):` }}
            {{ formatNumber(reconciled.commission / 100) }}
          </el-col>
        </el-row>
        <el-row class="couponRow">
          <el-col :span="12"> 售价: &yen;{{ formatNumber(reconciled.orderPrice) }} </el-col>
        </el-row>
        <h3 class="orderInfo">订单信息</h3>
        <div>
          <div class="couponRow">下单时间: {{ reconciled.orderTime != null ? reconciled.orderTime : "--" }}</div>
          <div class="couponRow">验券时间: {{ reconciled.checkTime != null ? reconciled.checkTime : "--" }}</div>
          <div class="couponRow">入账时间: {{ reconciled.createdTime != null ? reconciled.createdTime : "--" }}</div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="tsx" name="voucherManagement">
import { onActivated, onMounted, reactive, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getPaymentCycle } from "@/api/modules/homeEntry";
import { localGet } from "@/utils";
import { useRouter } from "vue-router";
const commissionRate = localGet("commissionRate") || "";
const router = useRouter();
const dialogVisible = ref(false);
const reconciled = ref<any>({});
// 计算表格高度
const tableHeight = ref<string>("calc(100vh - 200px)");
// 返回
const goBack = () => {
  router.back();
};
const toDetail = (row: any) => {
  dialogVisible.value = true;
  reconciled.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
  });
};
// ProTable 实例（需要在使用它的地方之前定义）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: "couponName",
    label: "商品名称"
  },
  {
    prop: "createdTime",
    label: "入账时间",
    search: {
      el: "date-picker",
      props: {
        type: "daterange",
        "range-separator": " - ",
        "start-placeholder": "开始日期",
        "end-placeholder": "结束日期"
      }
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
  storeId: localGet("createdId"),
  incomeType: 0,
  paymentType: 1,
  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.data?.records || data.records || [],
    total: data.data?.total || data.total || 0
  };
};

// 格式化日期为 yyyy-mm-dd
const formatDate = (date: string | Date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  // 处理 createdTime 参数，转换为 startTime 和 endTime
  if (newParams.createdTime && Array.isArray(newParams.createdTime) && newParams.createdTime.length === 2) {
    newParams.startTime = formatDate(newParams.createdTime[0]);
    newParams.endTime = formatDate(newParams.createdTime[1]);
    delete newParams.createdTime;
  } else {
    // 如果没有选择日期范围，清空 startTime 和 endTime
    newParams.startTime = null;
    newParams.endTime = null;
  }
  return getPaymentCycle(newParams);
};
</script>

<style lang="scss" scoped>
.reconciled {
  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%);
  }
}
.orderInfo {
  padding-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}
.couponRow {
  padding-bottom: 20px;
}
.couponRow:last-child {
  padding-bottom: 0;
}

// 在组件样式中添加
.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;
    }
  }
}
.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>
