<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      :pagination="true"
    >
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link @click="toDetail(scope.row)"> 查看详情 </el-button>
      </template>
    </ProTable>
    <el-dialog v-model="dialogVisible" title="提现详情" width="500px">
      <div class="withdrawal-detail">
        <!-- 提现进度 -->
        <div class="progress-section">
          <h4 class="section-title">提现进度</h4>
          <el-steps :active="currentStep" direction="vertical" :process-status="processStatus" :finish-status="finishStatus">
            <el-step>
              <template #title>
                <div class="step-title">发起提现</div>
              </template>
              <template #description>
                <div class="step-time">
                  {{ withdrawalDetail.createdTime || "2025/10/1 12:00:00" }}
                </div>
              </template>
            </el-step>
            <el-step>
              <template #title>
                <div class="step-title">等待审核</div>
              </template>
            </el-step>
            <el-step>
              <template #title>
                <div class="step-title">
                  {{ paymentName(withdrawalDetail.paymentStatus) }}
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>

        <!-- 提现详情 -->
        <div class="detail-section">
          <div class="detail-list">
            <div class="detail-item">
              <span class="detail-label">收款账户</span>
              <span class="detail-value">{{ withdrawalDetail.settlementAccount || "支付宝账户 (130****1234)" }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">提现金额</span>
              <span class="detail-value amount">¥{{ formatNumber(withdrawalDetail.money / 100) }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">发起提现时间</span>
              <span class="detail-value">{{ withdrawalDetail.createdTime || "2025/10/1 12:00:00" }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">结算账户</span>
              <span class="detail-value">{{ withdrawalDetail.settlementAccount || "重庆老火锅_钱包" }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">提现状态</span>
              <span class="detail-value status">{{ paymentName(withdrawalDetail.paymentStatus) }}</span>
            </div>
            <div class="detail-item" v-if="withdrawalDetail.approveFailReason">
              <span class="detail-label">拒绝原因</span>
              <span class="detail-value">{{ withdrawalDetail.approveFailReason }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </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 { getCashOutRecordList } from "@/api/modules/homeEntry";
import { ElMessageBox } from "element-plus/es";
import { localGet } from "@/utils";
const dialogVisible = ref(false);
const withdrawalDetail = ref<any>({});
// 格式化数字为千分位
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 paymentStatusEnum = [
  { label: "提现中", value: 0 },
  { label: "提现成功", value: 1 },
  { label: "提现失败", value: 2 },
  { label: "待审核", value: 3 },
  { label: "提现拒绝", value: 4 },
  { label: "审核通过", value: 5 }
];

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  {
    prop: "settlementAccount",
    label: "收款账号",
    render: (scope: any) => {
      return "支付宝账号" + "(" + scope.row.settlementAccount + ")";
    }
  },
  {
    prop: "money",
    label: "提现金额",
    render: (scope: any) => {
      return scope.row.money ? `￥${(scope.row.money / 100).toFixed(2)}` : "--";
    }
  },
  {
    prop: "cashOutType",
    label: "提现方式",
    render: scope => {
      return scope.row.cashOutType ? "自动提现" : "手动提现";
    }
  },
  {
    prop: "createdTime",
    label: "发起提现时间",
    search: {
      el: "date-picker",
      props: {
        type: "daterange",
        "range-separator": " - ",
        "start-placeholder": "开始日期",
        "end-placeholder": "结束日期"
      }
    }
  },
  {
    prop: "paymentStatus",
    label: "提现状态",
    render: scope => {
      return scope.row.paymentStatus === 0
        ? "进行中"
        : scope.row.paymentStatus === 1
          ? "提现成功"
          : scope.row.paymentStatus === 2
            ? "提现失败"
            : scope.row.paymentStatus === 3
              ? "待审核"
              : scope.row.paymentStatus === 4
                ? "提现拒绝"
                : "审核通过";
    },
    search: {
      el: "select",
      props: { placeholder: "请选择", clearable: true }
    },
    enum: paymentStatusEnum,
    fieldNames: { label: "label", value: "value" }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 330 }
]);

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

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

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.cashOutRecordList || data.list || [],
    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 参数，转换为 cashOutStartTime 和 cashOutEndTime
  if (newParams.createdTime && Array.isArray(newParams.createdTime) && newParams.createdTime.length === 2) {
    newParams.cashOutStartTime = formatDate(newParams.createdTime[0]);
    newParams.cashOutEndTime = formatDate(newParams.createdTime[1]);
    delete newParams.createdTime;
  } else {
    // 如果没有选择日期范围，清空 cashOutStartTime 和 cashOutEndTime
    newParams.cashOutStartTime = null;
    newParams.cashOutEndTime = null;
  }
  return getCashOutRecordList(newParams);
};

// 查看详情
const toDetail = (row: any) => {
  withdrawalDetail.value = row;
  dialogVisible.value = true;
};
const paymentName = computed(() => {
  return status => {
    switch (status) {
      case 0:
        return "提现中";
      case 1:
        return "提现成功";
      case 2:
        return "提现失败";
      case 3:
        return "提现待审核";
      case 4:
        return "提现拒绝";
      case 5:
        return "提现待审核通过";
      default:
        return "";
    }
  };
});

// 计算当前步骤
// active 表示当前激活的步骤索引（从0开始）
// 步骤0: 发起提现（总是已完成）
// 步骤1: 等待审核（根据状态判断）
// 步骤2: 提现成功/拒绝（根据状态判断）
const currentStep = computed(() => {
  const status = withdrawalDetail.value.paymentStatus;
  // 0: 提现中 -> 步骤1（发起提现已完成，等待审核进行中）
  // 1: 提现成功 -> 步骤2（所有步骤都已完成）
  // 2: 提现失败 -> 步骤1（等待审核失败）
  // 3: 提现待审核 -> 步骤1（等待审核进行中）
  // 4: 提现拒绝 -> 步骤2（审核已完成，在第三步显示拒绝状态）
  // 5: 提现待审核通过 -> 步骤2（所有步骤都已完成）
  if (status === 1 || status === 5) {
    return 2; // 提现成功，所有步骤都完成
  } else if (status === 4) {
    return 2; // 提现拒绝，在第三步显示错误状态
  } else if (status === 0 || status === 3) {
    return 1; // 等待审核进行中
  } else if (status === 2) {
    return 1; // 提现失败，在等待审核阶段失败
  }
  return 0; // 默认在第一步
});

// 处理状态（用于失败情况）
const processStatus = computed<"error" | "process" | "success" | "wait">(() => {
  const status = withdrawalDetail.value.paymentStatus;
  if (status === 1 || status === 5) {
    return "success" as const; // 提现成功，第三步显示完成状态（对号）
  } else if (status === 4) {
    return "error" as const; // 提现拒绝，在第三步显示错误状态
  } else if (status === 2) {
    return "error" as const; // 提现失败，在等待审核阶段显示错误状态
  }
  return "process" as const; // 进行中
});

// 完成状态
const finishStatus = computed<"finish">(() => {
  return "finish" as const; // 完成状态
});
</script>

<style lang="scss" scoped>
// 在组件样式中添加
.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;
      }
    }
  }
}
.withdrawal-detail {
  .section-title {
    margin: 0 0 20px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
  .progress-section {
    margin-bottom: 30px;
    :deep(.el-steps) {
      .el-step__head.is-process {
        color: #6c8ff8;
      }
      .el-step {
        margin-bottom: 24px;
        &:last-child {
          margin-bottom: 0;
        }
      }
      .el-step__head {
        .el-step__icon {
          width: 20px;
          height: 20px;
          font-size: 14px;
        }
      }
      .el-step__main {
        padding-bottom: 8px;
        .el-step__title {
          margin-bottom: 8px;
          font-size: 14px;
          line-height: 1.5;
          .step-title {
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }
        }
        .el-step__description {
          .step-time {
            margin-top: 4px;
            font-size: 12px;
            color: #909399;
          }
        }
      }

      // 等待审核步骤（第二个步骤）的文字颜色
      .el-step:nth-child(2) {
        &.is-process {
          .el-step__main {
            .el-step__title {
              .step-title {
                color: #6c8ff8;
              }
            }
          }
        }
      }
      .el-step__line {
        top: 20px;
        bottom: -24px;
        left: 9px;
        height: calc(100% + 4px);
        background-color: #6c8ff8;
        border-left: 2px dashed #6c8ff8;
      }
      .el-step__line-inner {
        height: 100%;
        border: none;
      }
      .el-step:last-child .el-step__line {
        display: none;
      }
    }
  }
  .detail-section {
    .detail-list {
      .detail-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 16px;
        &:last-child {
          margin-bottom: 0;
        }
        .detail-label {
          flex-shrink: 0;
          width: 100px;
          font-size: 14px;
          color: #606266;
        }
        .detail-value {
          flex: 1;
          font-size: 14px;
          color: #303133;
          word-break: break-word;
          &.amount {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
          }
          &.status {
            color: #6c8ff8;
          }
        }
      }
    }
  }
}
</style>
