<script setup lang="ts">
import { reactive, ref } from "vue";
import { offlineRecharge, searchUserByPhone } from "@/api/finance";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({ name: "AdminOfflineRecharge" });

const formRef = ref();

const state = reactive({
  form: {
    mobilePhone: "",
    amountYuan: null as number | null,
    grantsAmountYuan: 0,
    remark: ""
  },
  userInfo: null as any,
  searching: false,
  submitting: false
});

const rules = {
  mobilePhone: [{ required: true, message: "请输入用户手机号", trigger: "blur" }],
  amountYuan: [{ required: true, message: "请输入充值金额", trigger: "blur" }]
};

const fmtMoney = (money: number) => {
  if (!money) return "0.00";
  return (money / 100).toFixed(2);
};

const handleSearchUser = () => {
  if (!state.form.mobilePhone) {
    ElMessage.warning("请输入手机号");
    return;
  }
  state.searching = true;
  state.userInfo = null;
  searchUserByPhone({ mobilePhone: state.form.mobilePhone, pageNum: 1, pageSize: 1 })
    .then((res: any) => {
      const list = res?.records || [];
      if (list.length === 0) {
        ElMessage.warning("未找到该用户");
      } else {
        state.userInfo = list[0];
      }
    })
    .catch(() => {
      ElMessage.error("查询失败");
    })
    .finally(() => {
      state.searching = false;
    });
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;
  if (!state.userInfo) {
    ElMessage.warning("请先查询用户");
    return;
  }

  const amount = Math.round((state.form.amountYuan || 0) * 100);
  const grantsAmount = state.form.grantsAmountYuan ? Math.round(state.form.grantsAmountYuan * 100) : 0;
  const confirmMsg = `确认为用户 ${state.form.mobilePhone} 充值 ${fmtMoney(amount)} 元${grantsAmount > 0 ? "（赠送 " + fmtMoney(grantsAmount) + " 元）" : ""}？`;

  ElMessageBox.confirm(confirmMsg, "线下充值确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.submitting = true;
    offlineRecharge({
      userId: state.userInfo.id,
      amount,
      grantsAmount,
      remark: state.form.remark
    })
      .then(() => {
        ElMessage.success("充值成功");
        handleReset();
      })
      .catch(() => {
        ElMessage.error("充值失败");
      })
      .finally(() => {
        state.submitting = false;
      });
  }).catch(() => {});
};

const handleReset = () => {
  state.form = { mobilePhone: "", amountYuan: null, grantsAmountYuan: 0, remark: "" };
  state.userInfo = null;
  formRef.value?.clearValidate();
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <span class="card-header">线下充值</span>
      </template>
      <el-form ref="formRef" :model="state.form" :rules="rules" label-width="120px" style="max-width: 600px">
        <el-form-item label="用户手机号" prop="mobilePhone">
          <div style="display: flex; gap: 10px; width: 100%">
            <el-input v-model="state.form.mobilePhone" placeholder="请输入用户手机号" style="flex: 1" />
            <el-button type="primary" :loading="state.searching" @click="handleSearchUser">
              <template #icon>
                <i class="ri-search-line" />
              </template>
              查询
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="用户信息" v-if="state.userInfo">
          <div style="color: #409eff">
            用户ID: {{ state.userInfo.id }} &nbsp;|&nbsp;
            昵称: {{ state.userInfo.nickname || "-" }} &nbsp;|&nbsp;
            当前余额: {{ fmtMoney(state.userInfo.balance || 0) }} 元
          </div>
        </el-form-item>

        <el-form-item label="充值金额(元)" prop="amountYuan">
          <el-input-number
            v-model="state.form.amountYuan"
            :min="0.01"
            :precision="2"
            :step="10"
            placeholder="请输入充值金额"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="赠送金额(元)">
          <el-input-number
            v-model="state.form.grantsAmountYuan"
            :min="0"
            :precision="2"
            :step="5"
            placeholder="请输入赠送金额（可选）"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="state.form.remark"
            type="textarea"
            :rows="3"
            placeholder="转账凭证信息、微信流水号等"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="success" :loading="state.submitting" @click="handleSubmit">
            确认充值
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

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

.card-header {
  font-size: 16px;
  font-weight: 600;
}
</style>
