<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from "vue";
import { getRefundList } from "@/api/finance";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { http } from "@/utils/http";
import { ElMessage, ElMessageBox } from "element-plus";
import { ExtDLabel, ExtDSelect } from "@/components/ExtForm";

defineOptions({
  name: "AdminFinanceRefund"
});

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

const state = reactive({
  formQuery: {
    mobilePhone: "",
    status: ""
  },
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    total: 0
  },
  tableData: {
    height: 500,
    data: [] as Array<any>,
    loading: false,
    columns: [
      { label: "手机号", prop: "mobilePhone", width: 120 },
      { label: "微信支付退款单号", prop: "refundLogId", width: 180 },
      { label: "商户支付单号", prop: "outTradeNo", width: 210 },
      { label: "商户退款单号", prop: "outRefundNo", width: 210 },
      { label: "原充值金额", prop: "total", width: 110 },
      { label: "退款金额", prop: "refund", width: 120 },
      { label: "申请时间", prop: "createTime", width: 180 },
      { label: "退款成功时间", prop: "successTime", width: 180 },
      { label: "退款状态", prop: "status", width: 100 },
      { label: "退款原因", prop: "reason", width: 180 },
      { label: "退款人", prop: "adminUsername", width: 180 }
    ]
  }
});

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;
  getRefundList({ ...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 refundLoading = ref(false);

const handleRefundDeal = (row: any) => {
  ElMessageBox.confirm(
    `确认对退款单「${row.refundLogId}」执行退款处理吗？`,
    "退款处理",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(() => {
    refundLoading.value = true;
    http
      .request("get", `finance/customWxRefund/${row.refundLogId}`)
      .then(() => {
        ElMessage.success("退款系统处理中，请稍后查看结果");
        loadData(true);
      })
      .catch(() => {
        ElMessage.error("退款处理失败，请联系管理员");
      })
      .finally(() => {
        refundLoading.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 = {
    mobilePhone: "",
    status: ""
  };
  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-input
            v-model="state.formQuery.mobilePhone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="退款状态">
          <ExtDSelect
            v-model="state.formQuery.status"
            type="Refund.status"
            placeholder="请选择状态"
            @on-change="handleSearch"
          />
        </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 === 'total' || col.prop === 'refund'">
              {{ formatMoney(row[col.prop]) }}
            </template>
            <template v-else-if="col.prop === 'status'">
              <ExtDLabel type="Refund.status" :model-value="row.status" />
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'NEW'"
              type="warning"
              link
              size="small"
              @click="handleRefundDeal(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>
