<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getWithdrawList } from "@/api/finance";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { http } from "@/utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
import { getDictOptions, formatDict, getDictColor } from "@/utils/dict";

defineOptions({
  name: "AdminFinanceWithdraw"
});

const queryRef = ref();
const tableRef = ref();

const state = reactive({
  formQuery: {
    stationId: "",
    status: "",
    paymentStatus: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "提现站点", prop: "stationName", width: 180 },
      { label: "提现金额", prop: "withdrawnAmount", width: 100 },
      { label: "审核状态", prop: "status", width: 100 },
      { label: "打款状态", prop: "paymentStatus", width: 100 },
      { label: "审核人", prop: "reviewer", width: 120 },
      { label: "审核时间", prop: "reviewTime", width: 180 },
      { label: "打款人", prop: "payer", width: 120 },
      { label: "打款时间", prop: "paymentTime", width: 180 },
      { label: "备注", prop: "remark", width: 180 },
      { label: "申请时间", prop: "createTime", width: 180 },
      { label: "更新时间", prop: "updateTime", width: 180 }
    ]
  },
  get statusOptions() { return getDictOptions("WithdrawnRecord.status"); },
  get paymentStatusOptions() { return getDictOptions("WithdrawnRecord.paymentStatus"); }
});

onMounted(() => {
  loadData();
  nextTick(() => {
    const bodyHeight = document.body.clientHeight;
    const queryHeight = queryRef.value?.$el?.clientHeight || 0;
    state.tableData.height = bodyHeight - queryHeight - 230;
  });
});

const loadData = (refresh: boolean = false) => {
  if (refresh) {
    state.pageQuery.pageNum = 1;
  }
  state.tableData.loading = true;
  getWithdrawList({ ...state.formQuery, ...state.pageQuery })
    .then((res: any) => {
      const { list, total } = res || {};
      state.tableData.data = list || [];
      state.pageQuery.total = total || 0;
    })
    .catch(() => {
      state.tableData.data = [];
      ElMessage.error("加载提现记录失败");
    })
    .finally(() => {
      state.tableData.loading = false;
    });
};

const auditLoading = ref(false);
const confirmLoading = ref(false);

const handleWithdrawAudit = (row: any) => {
  ElMessageBox.confirm(
    `确认对站点「${row.stationName}」的提现申请执行审核通过吗？`,
    "提现审核",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    auditLoading.value = true;
    http
      .request("post", "finance/reviewWithdrawn", { data: { id: row.id, status: 1 } })
      .then(() => {
        ElMessage.success("提现审核通过");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("审核操作失败，请稍后重试");
      })
      .finally(() => {
        auditLoading.value = false;
      });
  });
};

const handleWithdrawConfirm = (row: any) => {
  ElMessageBox.confirm(
    `确认对站点「${row.stationName}」的提现执行打款确认吗？`,
    "打款确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    confirmLoading.value = true;
    http
      .request("post", "finance/confirmWithdrawnPayment", { data: { id: row.id, paymentStatus: 1 } })
      .then(() => {
        ElMessage.success("提现打款已确认");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("打款确认失败，请稍后重试");
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  });
};

const handleSizeChange = (size: number) => {
  state.pageQuery.pageSize = size;
  loadData(true);
};

const handleCurrentChange = (page: number) => {
  state.pageQuery.pageNum = page;
  loadData();
};

const handleSearch = () => {
  loadData(true);
};

const handleReset = () => {
  state.formQuery = {
    stationId: "",
    status: "",
    paymentStatus: ""
  };
  loadData(true);
};

const formatMoney = (value: number) => {
  if (value === null || value === undefined) return "¥0.00";
  return `¥${(value / 100).toFixed(2)}`;
};

</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">提现记录</span>
      </template>
      <el-form
        ref="queryRef"
        :model="state.formQuery"
        inline
        class="search-form"
      >
        <el-form-item label="审核状态">
          <el-select
            v-model="state.formQuery.status"
            placeholder="请选择审核状态"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in state.statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="打款状态">
          <el-select
            v-model="state.formQuery.paymentStatus"
            placeholder="请选择打款状态"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="item in state.paymentStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="useRenderIcon('ri/refresh-line')"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="tableRef"
        v-loading="state.tableData.loading"
        :data="state.tableData.data"
        :height="state.tableData.height"
        border
        stripe
      >
        <template #empty>
          <el-empty description="暂无提现记录" />
        </template>
        <el-table-column
          v-for="col in state.tableData.columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <template v-if="col.prop === 'withdrawnAmount'">
              {{ formatMoney(row[col.prop]) }}
            </template>
            <template v-else-if="col.prop === 'status'">
              <el-tag :type="getDictColor('WithdrawnRecord.status', row.status)" size="small">
                {{ formatDict('WithdrawnRecord.status', row.status) }}
              </el-tag>
            </template>
            <template v-else-if="col.prop === 'paymentStatus'">
              <el-tag :type="getDictColor('WithdrawnRecord.paymentStatus', row.paymentStatus)" size="small">
                {{ formatDict('WithdrawnRecord.paymentStatus', row.paymentStatus) }}
              </el-tag>
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 0"
              type="warning"
              link
              size="small"
              @click="handleWithdrawAudit(row)"
            >
              提现审核
            </el-button>
            <el-button
              v-if="row.paymentStatus === 0"
              type="danger"
              link
              size="small"
              @click="handleWithdrawConfirm(row)"
            >
              打款确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="state.pageQuery.pageNum"
          v-model:page-size="state.pageQuery.pageSize"
          :total="state.pageQuery.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.page-container {
  padding: 20px;
}

.card-header {
  font-size: 16px;
  font-weight: 600;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
