<template>
  <div class="receiving-account-page">
    <h2 class="page-title">收款账号</h2>
    <p class="page-tip">
      请选择收款方式并填写商户信息；微信/支付宝各填写商户ID与商户ID号码，或绑定借记卡银行账户，带 * 为必填项。修改后请保存。
    </p>

    <el-card shadow="never" class="form-card">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="140px" label-position="top">
        <el-form-item label="账号类型" prop="accountType">
          <el-radio-group v-model="form.accountType">
            <el-radio value="wechat"> 微信 </el-radio>
            <el-radio value="alipay"> 支付宝 </el-radio>
            <el-radio value="bank"> 银行账号 </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.accountType !== 'bank'" label="授权指引">
          <el-button link type="primary" @click="openAuthGuide">
            查看{{ form.accountType === "wechat" ? "微信" : "支付宝" }}授权指引
          </el-button>
        </el-form-item>

        <template v-if="form.accountType === 'wechat'">
          <el-form-item label="商户ID" prop="wechatAppid">
            <el-input v-model="form.wechatAppid" placeholder="请输入商户ID" clearable />
          </el-form-item>
          <el-form-item label="商户ID号码" prop="wechatMchld">
            <el-input v-model="form.wechatMchld" placeholder="请输入商户ID号码" clearable />
          </el-form-item>
        </template>

        <template v-else-if="form.accountType === 'alipay'">
          <el-form-item label="商户ID" prop="aliAppid">
            <el-input v-model="form.aliAppid" placeholder="请输入商户ID" clearable />
          </el-form-item>
          <el-form-item label="商户ID号码" prop="aliPrivateId">
            <el-input v-model="form.aliPrivateId" placeholder="请输入商户ID号码" clearable />
          </el-form-item>
        </template>

        <template v-else-if="form.accountType === 'bank'">
          <el-form-item label="银行名称" prop="bankName">
            <el-select v-model="form.bankName" filterable clearable placeholder="请选择" style="width: 100%">
              <el-option v-for="b in bankSelectOptions" :key="b.value" :label="b.label" :value="b.value" />
            </el-select>
            <div class="form-item-tip">请选择开户银行的全称</div>
          </el-form-item>
          <el-form-item label="银行账号" prop="bankAccountNo">
            <el-input v-model="form.bankAccountNo" placeholder="请输入" clearable maxlength="23" />
            <div class="form-item-tip">请输入完整的银行卡号，仅支持借记卡，不支持信用卡</div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" :loading="saving" @click="submit"> 保存 </el-button>
          <el-button @click="fetchPayAccountConfig"> 取消 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getDict,
  getPaymentStoreUserId,
  saveWechatWithFiles,
  saveAlipayWithFiles,
  saveBankAccountConfig
} from "@/api/modules/newLoginApi";
import { localGet } from "@/utils/index";

/** 银行名称下拉：仅展示 getDict 返回的数据 */
const bankSelectOptions = ref<{ label: string; value: string }[]>([]);

const normalizeDictToOptions = (raw: unknown): { label: string; value: string }[] => {
  const list = Array.isArray(raw) ? raw : ((raw as any)?.records ?? (raw as any)?.list ?? []);
  if (!Array.isArray(list)) return [];
  return list
    .map((item: any) => {
      const label = item?.dictDetail ?? item?.dictLabel ?? item?.label ?? item?.name ?? item?.text ?? item?.bankName ?? "";
      const value = item?.dictValue ?? item?.value ?? item?.code ?? item?.dictDetail ?? item?.dictLabel ?? label;
      return { label: String(label).trim(), value: String(value).trim() };
    })
    .filter((x: { label: string; value: string }) => x.label && x.value);
};

const loadBankNameDict = async () => {
  try {
    const res: any = await getDict({ dictType: "bankName" });
    if (res?.code !== 200 && res?.code !== "200") {
      bankSelectOptions.value = [];
      return;
    }
    bankSelectOptions.value = normalizeDictToOptions(res.data);
  } catch {
    bankSelectOptions.value = [];
  }
};

const formRef = ref<FormInstance>();
const saving = ref(false);

const form = reactive({
  accountType: "wechat",
  wechatAppid: "",
  wechatMchld: "",
  aliAppid: "",
  aliPrivateId: "",
  bankName: "",
  bankAccountNo: ""
});

const wechatRules: FormRules = {
  accountType: [{ required: true, message: "请选择账号类型", trigger: "change" }],
  wechatAppid: [{ required: true, message: "请输入商户ID", trigger: "blur" }],
  wechatMchld: [{ required: true, message: "请输入商户ID号码", trigger: "blur" }]
};

const alipayRules: FormRules = {
  accountType: [{ required: true, message: "请选择账号类型", trigger: "change" }],
  aliAppid: [{ required: true, message: "请输入商户ID", trigger: "blur" }],
  aliPrivateId: [{ required: true, message: "请输入商户ID号码", trigger: "blur" }]
};

const bankRules: FormRules = {
  accountType: [{ required: true, message: "请选择账号类型", trigger: "change" }],
  bankName: [{ required: true, message: "请选择银行名称", trigger: "change" }],
  bankAccountNo: [
    { required: true, message: "请输入银行账号", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        const s = String(value || "").replace(/\s/g, "");
        if (!/^\d{16,19}$/.test(s)) {
          callback(new Error("请输入16～19位数字借记卡卡号"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const formRules = computed<FormRules>(() => {
  if (form.accountType === "alipay") return alipayRules;
  if (form.accountType === "bank") return bankRules;
  return wechatRules;
});

watch(
  () => form.accountType,
  () => {
    formRef.value?.clearValidate();
  }
);

const openAuthGuide = () => {
  const url =
    form.accountType === "wechat"
      ? "https://ossfile.ailien.shop/privacy/wechat-auth382471.html"
      : "https://ossfile.ailien.shop/privacy/alipay-auth501249.html";
  window.open(url, "_blank");
};

/** 从接口拉取收款配置，用于页面进入时初始化表单，以及「取消」时放弃本地修改并重新回填 */
const fetchPayAccountConfig = async () => {
  const storeUserId = localGet("geeker-user")?.userInfo?.id;
  if (!storeUserId) {
    ElMessage.warning("请先登录");
    return;
  }
  const res: any = await getPaymentStoreUserId({ storeUserId });
  if (res?.code !== 200 || !res.data) {
    return;
  }
  const data = res.data;

  form.wechatAppid = "";
  form.wechatMchld = "";
  form.aliAppid = "";
  form.aliPrivateId = "";
  form.bankName = "";
  form.bankAccountNo = "";

  // 后端可能同时返回三类配置，须分别回填；若用 else if 只会填到第一项，切换支付宝/银行会没有初始值
  if (data.storeWechatId || data.wechatAppId) {
    form.wechatAppid = String(data.storeWechatId ?? data.wechatAppId ?? "");
    form.wechatMchld = String(data.storeWechatName ?? data.wechatMchId ?? "");
  }
  if (data.storeAliId || data.appId) {
    form.aliAppid = String(data.storeAliId ?? data.appId ?? "");
    form.aliPrivateId = String(data.storeAliName ?? data.appSecretCert ?? "");
  }

  const bankNo = data.bankAccountNo ?? data.bankCardNo ?? data.settlementAccount;
  const bankNm = data.bankName ?? data.openingBankName ?? data.openingBank;
  if (bankNo) {
    form.bankAccountNo = String(bankNo).replace(/\s/g, "");
    form.bankName = bankNm ? String(bankNm) : "";
  }

  // 单选「当前展示哪一类」：有数据时优先微信 > 支付宝 > 银行（与保存时三选一一致）
  if (data.storeWechatId || data.wechatAppId) {
    form.accountType = "wechat";
  } else if (data.storeAliId || data.appId) {
    form.accountType = "alipay";
  } else if (bankNo) {
    form.accountType = "bank";
  }
};

const submit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async valid => {
    if (!valid) return;

    const storeUserId = localGet("geeker-user")?.userInfo?.id;
    if (!storeUserId) {
      ElMessage.warning("请先登录");
      return;
    }

    saving.value = true;
    try {
      if (form.accountType === "bank") {
        const res: any = await saveBankAccountConfig({
          storeUserId,
          bankName: form.bankName.trim(),
          bankCardNo: form.bankAccountNo.replace(/\s/g, "")
        });
        if (res?.code === 200 || res?.code === "200") ElMessage.success(res?.msg || "保存成功");
        else ElMessage.error(res?.msg || "保存失败");
        return;
      }

      if (form.accountType === "alipay") {
        const res: any = await saveAlipayWithFiles({
          storeUserId,
          storeAliId: form.aliAppid.trim(),
          storeAliName: form.aliPrivateId.trim()
        });
        if (res?.code === 200 || res?.code === "200") ElMessage.success(res?.msg || "保存成功");
        else ElMessage.error(res?.msg || "保存失败");
        return;
      }

      const res: any = await saveWechatWithFiles({
        storeUserId,
        storeWechatId: form.wechatAppid.trim(),
        storeWechatName: form.wechatMchld.trim()
      });
      if (res?.code === 200 || res?.code === "200") ElMessage.success(res?.msg || "保存成功");
      else ElMessage.error(res?.msg || "保存失败");
    } catch (e: any) {
      ElMessage.error(e?.message || "保存失败");
    } finally {
      saving.value = false;
    }
  });
};

onMounted(async () => {
  await loadBankNameDict();
  await fetchPayAccountConfig();
});
</script>

<style scoped lang="scss">
.receiving-account-page {
  min-height: 100%;
  padding: 20px;
  background: #ffffff;
  .page-title {
    margin: 0 0 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
  .page-tip {
    margin: 0 0 20px;
    font-size: 14px;
    line-height: 1.5;
    color: #909399;
  }
  .form-card {
    max-width: 720px;
  }
}
.form-item-tip {
  margin-top: 6px;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}
</style>
