<template>
  <div class="real-name-page">
    <!-- 头部区域 -->
    <div class="header-section">
      <div class="header-content">
        <div class="shop-info">
          <el-image :src="homeIcon" class="homeIcon" />
          <span class="shop-name">{{ localGet("storeName") }}</span>
        </div>
        <div class="auth-status">
          <span class="status-badge" v-if="!userInfo.idCard">未认证</span>
          <span class="status-badge status-badge-success" v-if="userInfo.idCard">已认证</span>
        </div>
      </div>
    </div>

    <!-- 标签导航栏 -->
    <div class="tabs-section">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="实名认证" name="realName" />
        <el-tab-pane label="提现密码" name="withdrawPassword" />
        <el-tab-pane label="收款账户" name="receivingAccount" />
      </el-tabs>
    </div>

    <!-- 实名认证 -->
    <div class="content-section" v-if="activeTab === 'realName'">
      <div class="content-wrapper-realName">
        <div class="goAuthBtn" v-if="goAuth">
          <el-button type="primary" class="auth-button" @click="handleGoAuth">
            <el-icon><CirclePlus /></el-icon> &nbsp;去实名认证
          </el-button>
        </div>
        <div class="auth-div" v-if="!goAuth">
          <el-row class="auth-row">
            <el-col :span="2"> 姓名 </el-col>
            <el-col :span="12">
              {{ userInfo.name }}
            </el-col>
          </el-row>
          <el-row class="auth-row">
            <el-col :span="2"> 身份证号 </el-col>
            <el-col :span="12">
              {{ userInfo.idCard }}
            </el-col>
          </el-row>
          <el-row class="auth-row">
            <el-col :span="2"> 认证时间 </el-col>
            <el-col :span="12">
              {{ userInfo.createdTime }}
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <!-- 实名认证对话框 -->
    <el-dialog v-model="dialogVisible" title="实名认证" width="500px" :close-on-click-modal="false">
      <el-form ref="authFormRef" :model="authForm" :rules="authRules" label-width="100px" label-position="left">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="authForm.name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="身份证号码" prop="idCard">
          <el-input v-model="authForm.idCard" placeholder="请输入身份证号码" clearable maxlength="18" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现密码 -->
    <div class="content-section" v-if="activeTab === 'withdrawPassword'">
      <div class="content-wrapper">
        <div class="password-form-wrapper" v-if="withdrawPass">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
            label-position="left"
            class="form-wrapper"
          >
            <el-form-item label="设置提现密码" prop="password">
              <el-input
                v-model="passwordForm.password"
                type="password"
                placeholder="请输入6位提现密码"
                clearable
                maxlength="6"
                show-password
                class="password-input"
              />
            </el-form-item>
            <el-form-item label="请确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请输入6位提现密码"
                clearable
                maxlength="6"
                show-password
                class="password-input"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="submit-button" :loading="passwordLoading" @click="handlePasswordOneSubmit">
                确认
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <!---第二次进入此页面--->
        <div class="password-form-wrapper-step" v-if="twoEnterPage">
          <el-steps :active="currentStep" style="max-width: 600px">
            <el-step v-for="(item, index) in passList" :key="index">
              <template #title>
                <div class="step-title-wrapper">
                  <span class="step-title">{{ item.title }}</span>
                </div>
              </template>
            </el-step>
          </el-steps>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            label-position="left"
            class="form-wrapper"
            v-if="currentStep == 1"
          >
            <el-form-item label="验证原密码">
              <el-input
                v-model="oldPasswordForm.password"
                type="password"
                placeholder="请输入6位提现密码"
                clearable
                maxlength="6"
                show-password
                class="password-input"
              />
            </el-form-item>
            <div class="forget-password" @click="getForgetPassword">忘记密码</div>
            <el-button type="primary" class="submit-button" @click="nextStept"> 下一步 </el-button>
          </el-form>
          <el-form
            ref="passwordFormRef"
            :model="oldTwoPasswordForm"
            :rules="passwordRulesTwo"
            label-width="120px"
            label-position="left"
            class="form-wrapper"
            v-if="currentStep == 2"
          >
            <el-form-item label="设置提现密码">
              <el-input
                v-model="oldTwoPasswordForm.password"
                type="password"
                placeholder="请输入6位提现密码"
                clearable
                maxlength="6"
                show-password
                class="password-input"
              />
            </el-form-item>
            <el-form-item label="请确认密码">
              <el-input
                v-model="oldTwoPasswordForm.confirmPassword"
                type="password"
                placeholder="请输入6位提现密码"
                clearable
                maxlength="6"
                show-password
                class="password-input"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="submit-button" :loading="passwordLoading" @click="handlePasswordTwoSubmit">
                确认
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!--收款账户-->
    <div class="content-section" v-if="activeTab === 'receivingAccount'">
      <div class="content-wrapper">
        <el-button type="primary" class="auth-button" @click="handleGoZFB" v-if="!alipayAccount"> 添加支付宝账号 </el-button>
        <div class="zfb-wrapper" v-if="alipayAccount">
          <div style="width: 100%">
            <div style="display: flex; align-items: center; justify-content: space-between; width: 100%; margin-top: 10px">
              <div class="zfb-left">
                <el-image :src="zfbIcon" class="zfbIcon" />
                <div>
                  <div>支付宝</div>
                  <div>{{ alipayAccount }}</div>
                </div>
              </div>
              <div class="operate">
                <div @click="getEditZfb" style="cursor: pointer">编辑</div>
                <div @click="getDelZfb" style="cursor: pointer">删除</div>
              </div>
            </div>
            <!-- <el-button
              type="primary"
              @click="goToCashApply"
              class="submit-button"
              style=" position: relative; left: -10%; width: 20%;margin-top: 90px; margin-left: 50%"
            >
              去提现
            </el-button> -->
          </div>
        </div>
      </div>
    </div>
    <!--添加支付宝账号--->
    <el-dialog v-model="dialogVisibleZFB" :title="zfbTitle" width="500px" :close-on-click-modal="false">
      <el-form ref="authFormRef1" :model="authForm1" :rules="authRules1" label-width="100px" label-position="left">
        <el-form-item label="支付宝账号" prop="zfbName">
          <el-input v-model="authForm1.zfbName" placeholder="请输入支付宝账号" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelZFB">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleConfirmZFB">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 忘记密码对话框 -->
    <el-dialog v-model="forgotPasswordVisible" title="忘记密码" width="500px" draggable :close-on-click-modal="false">
      <el-form
        ref="forgotPasswordFormRef"
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="手机号码">
          <span>{{ maskedPhone }}</span>
        </el-form-item>

        <el-form-item label="验证码">
          <div style="display: flex; gap: 12px; width: 100%">
            <el-input v-model="forgotPasswordForm.verificationCode" placeholder="请输入" clearable style="flex: 1" />
            <el-button :disabled="codeCountdown > 0" @click="sendForgotCode" class="code-button">
              {{ codeCountdown > 0 ? `${codeCountdown}秒后重试` : "获取验证码" }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="输入新密码">
          <el-input
            v-model="forgotPasswordForm.newPassword"
            type="password"
            placeholder="请输入6位提现密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input
            v-model="forgotPasswordForm.confireNewPassword"
            type="password"
            placeholder="请输入6位提现密码"
            show-password
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="forgotPasswordVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="handleForgetConfirmZFB">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, ElMessageBox, type FormRules } from "element-plus";
import {
  verifyIdInfo,
  checkPayPassword,
  setPayPassword,
  getMerchantByPhone,
  addAlipayAccount,
  deleteAlipayAccount,
  getCheckPayPasswordTwo
} from "@/api/modules/homeEntry";
import { localGet, localSet } from "@/utils/index";
import homeIcon from "../../assets/images/home-icon.png";
import zfbIcon from "../../assets/financial/zfb-icon.png";
import { lo } from "element-plus/es/locale";
import { getPhoneCode, getCheckSmsCode } from "@/api/modules/newLoginApi";
// 初始化用户信息，统一处理支付宝账号字段名（兼容 aliPayAccount 和 alipayAccount）
const initUserInfo = () => {
  const cachedUserInfo = localGet("geeker-user")?.userInfo || {};
  // 统一使用 alipayAccount 字段，兼容 aliPayAccount（驼峰命名）
  if (cachedUserInfo.aliPayAccount && !cachedUserInfo.alipayAccount) {
    cachedUserInfo.alipayAccount = cachedUserInfo.aliPayAccount;
  }
  return cachedUserInfo;
};
const userInfo = ref(initUserInfo());
const router = useRouter();
const activeTab = ref("realName");
const dialogVisible = ref(false);
const loading = ref(false);
//实名认证
const goAuth = ref(!userInfo.value.idCard);
const authFormRef = ref<FormInstance>();
const authForm = reactive({
  name: "",
  idCard: ""
});
// 实名认证表单验证规则
const authRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  zfbName: [{ required: true, message: "请输入支付宝账号", trigger: "blur" }],
  idCard: [
    { required: true, message: "请输入身份证号码", trigger: "blur" },
    {
      pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
      message: "请输入正确的身份证号码",
      trigger: "blur"
    }
  ]
});
//去实名认证
const handleGoAuth = () => {
  // 打开实名认证对话框
  dialogVisible.value = true;
  // 重置表单
  if (authFormRef.value) {
    authFormRef.value.resetFields();
  }
};
//实名认证 确认
const shimingInfo = ref(null);
const handleConfirm = async () => {
  if (!authFormRef.value) return;

  // 表单验证
  await authFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const params = {
          name: authForm.name,
          idCard: authForm.idCard,
          appType: 1
        };
        const res: any = await verifyIdInfo(params);
        console.log(res);
        if (res && res.code == 200) {
          ElMessage.success(res.msg || "实名认证提交成功");
          let param = {
            phone: userInfo.value.phone
          };
          const res1: any = await getMerchantByPhone(param);
          if (res1.code == 200) {
            // 统一处理支付宝账号字段名
            const updatedData = res1.data || {};
            if (updatedData.aliPayAccount && !updatedData.alipayAccount) {
              updatedData.alipayAccount = updatedData.aliPayAccount;
            }
            dialogVisible.value = false;
            goAuth.value = false;
            // 重置表单
            authFormRef.value?.resetFields();
            shimingInfo.value = updatedData;
            userInfo.value = { ...userInfo.value, ...updatedData };
            // 更新本地存储
            const geekerUser = localGet("geeker-user");
            if (geekerUser) {
              geekerUser.userInfo = { ...geekerUser.userInfo, ...updatedData };
              if (updatedData.alipayAccount) {
                geekerUser.userInfo.alipayAccount = updatedData.alipayAccount;
                geekerUser.userInfo.aliPayAccount = updatedData.alipayAccount;
              }
              localSet("geeker-user", geekerUser);
            }
            // 这里可以更新认证状态或刷新页面数据
          }
        } else {
          ElMessage.error(res.msg || "实名认证失败，请重试");
        }
      } catch (error) {
        console.error("实名认证失败:", error);
        ElMessage.error("实名认证失败，请重试");
      } finally {
        loading.value = false;
      }
    }
  });
};

//提现密码
const withdrawPass = ref(true);
const passwordFormRef = ref<FormInstance>();
const passwordForm = reactive({
  password: "",
  confirmPassword: ""
});
// 提现密码表单验证规则
const passwordRules = reactive<FormRules>({
  password: [
    { required: true, message: "请输入6位提现密码", trigger: "blur" },
    {
      pattern: /^\d{6}$/,
      message: "请输入6位数字密码",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
// 第二步修改密码的验证规则
const passwordRulesTwo = reactive<FormRules>({
  password: [
    { required: true, message: "请输入6位提现密码", trigger: "blur" },
    {
      pattern: /^\d{6}$/,
      message: "请输入6位数字密码",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== oldTwoPasswordForm.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
//提现密码 确认
const passwordLoading = ref(false);
const handlePasswordOneSubmit = async () => {
  if (!passwordFormRef.value) return;

  // 表单验证
  await passwordFormRef.value.validate(async valid => {
    if (valid) {
      passwordLoading.value = true;
      try {
        const res: any = await setPayPassword({
          payPassword: passwordForm.password,
          id: userInfo.value.id
        });
        if (res.code == 200) {
          ElMessage.success(res.msg || "提现密码设置成功");

          // 更新本地存储中的提现密码
          try {
            const geekerUser = localGet("geeker-user");
            if (geekerUser && geekerUser.userInfo) {
              geekerUser.userInfo.payPassword = passwordForm.password;
              localSet("geeker-user", geekerUser);
            }
          } catch (error) {
            console.error("更新本地存储失败:", error);
          }

          // 重置表单
          passwordFormRef.value?.resetFields();
          // 如果是在修改密码流程中（twoEnterPage为true），设置状态为已设置
          if (twoEnterPage.value) {
            twoEnterPage.value = true;
            withdrawPass.value = false;
            currentStep.value = 1; // 重置步骤
          } else {
            // 首次设置密码，跳转到收款账户
            activeTab.value = "receivingAccount";
          }
        } else {
          ElMessage.error(res.msg || "提现密码设置失败");
        }
      } catch (error) {
        console.error("设置提现密码失败:", error);
        ElMessage.error("提现密码设置失败，请重试");
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};
//二次进入显示
const twoEnterPage = ref(false);
//提现密码    验证原密码
const currentStep = ref(1);
const passList = [
  {
    title: "验证原密码"
  },
  {
    title: "设置新密码"
  }
];
//忘记密码

const forgotPasswordVisible = ref(false);
const forgotPasswordFormRef = ref<FormInstance>();
// 验证码倒计时
const codeCountdown = ref(0);
let countdownTimer: NodeJS.Timeout | null = null;
const forgotPasswordForm = reactive({
  newPassword: "",
  confireNewPassword: "",
  verificationCode: ""
});
const getForgetPassword = async () => {
  forgotPasswordVisible.value = true;
};
// 发送短信验证码
const sendForgotCode = async () => {
  let phoneCode: any = await getPhoneCode({ phone: userInfo.value.phone, appType: "2", businessType: "7" });
  if (phoneCode.code === 200) {
    ElMessage.success("验证码已发送");
    // 开始倒计时
    codeCountdown.value = 60;
    countdownTimer = setInterval(() => {
      codeCountdown.value--;
      if (codeCountdown.value <= 0) {
        if (countdownTimer) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
      }
    }, 1000);
  }
};
//下一步

const oldPasswordForm = reactive({
  password: ""
});

const oldTwoPasswordForm = reactive({
  password: "",
  confirmPassword: ""
});

const nextStept = async () => {
  const res: any = await getCheckPayPasswordTwo({
    password: oldPasswordForm.password,
    storeUserId: userInfo.value.id
  });
  if (res.data.data == "false") {
    ElMessage.error(res.data.message);
  } else {
    ElMessage.success(res.msg);
    currentStep.value = 2;
    // 更新本地存储中的提现密码
    try {
      const geekerUser = localGet("geeker-user");
      if (geekerUser && geekerUser.userInfo) {
        geekerUser.userInfo.payPassword = oldTwoPasswordForm.password;
        localSet("geeker-user", geekerUser);
      }
    } catch (error) {
      console.error("更新本地存储失败:", error);
    }
  }
};

const handlePasswordTwoSubmit = async () => {
  if (!passwordFormRef.value) return;

  // 表单验证
  await passwordFormRef.value.validate(async valid => {
    if (valid) {
      passwordLoading.value = true;
      try {
        const res: any = await setPayPassword({
          payPassword: oldTwoPasswordForm.password,
          id: userInfo.value.id
        });
        if (res.code == 200) {
          ElMessage.success(res.msg || "提现密码修改成功");
          activeTab.value = "receivingAccount";
          // 更新本地存储中的提现密码
          try {
            const geekerUser = localGet("geeker-user");
            if (geekerUser && geekerUser.userInfo) {
              geekerUser.userInfo.payPassword = oldTwoPasswordForm.password;
              localSet("geeker-user", geekerUser);
            }
          } catch (error) {
            console.error("更新本地存储失败:", error);
          }

          // 重置表单
          passwordFormRef.value?.resetFields();
          oldPasswordForm.password = "";
          oldTwoPasswordForm.password = "";
          oldTwoPasswordForm.confirmPassword = "";
          // 重置步骤
          currentStep.value = 1;
        } else {
          ElMessage.error(res.msg || "提现密码修改失败");
        }
      } catch (error) {
        console.error("修改提现密码失败:", error);
        ElMessage.error("提现密码修改失败，请重试");
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};

//收款账户
const authFormRef1 = ref<FormInstance>();
const authRules1 = reactive<FormRules>({
  zfbName: [{ required: true, message: "请输入支付宝账号", trigger: "blur" }]
});
const authForm1 = reactive({
  zfbName: ""
});
const zfbShow = ref(false);
const zfbTitle = ref("");
const dialogVisibleZFB = ref(false);
const handleGoZFB = async () => {
  zfbTitle.value = "添加支付宝账号";
  dialogVisibleZFB.value = true;
};
const handleConfirmZFB = async () => {
  if (!authFormRef1.value) return;
  await authFormRef1.value.validate(async valid => {
    if (valid) {
      loading.value = true;
      try {
        const params = {
          alipayAccount: authForm1.zfbName
        };
        const res: any = await addAlipayAccount(params);
        if (res && res.code == 200) {
          ElMessage.success(res.msg || "添加支付宝账号成功");
          // 更新本地存储中的支付宝账号（统一使用 alipayAccount 字段）
          try {
            const geekerUser = localGet("geeker-user");
            if (geekerUser && geekerUser.userInfo) {
              geekerUser.userInfo.alipayAccount = authForm1.zfbName;
              geekerUser.userInfo.aliPayAccount = authForm1.zfbName; // 兼容旧字段名
              localSet("geeker-user", geekerUser);
              // 更新响应式的 userInfo
              userInfo.value.alipayAccount = authForm1.zfbName;
            }
          } catch (error) {
            console.error("更新本地存储失败:", error);
          }

          dialogVisibleZFB.value = false;
          zfbShow.value = true;
          // 重置表单
          authFormRef1.value?.resetFields();
        } else {
          ElMessage.error(res.msg || "添加支付宝账号失败，请重试");
        }
      } catch (error) {
        console.error("添加支付宝账号失败:", error);
        ElMessage.error("添加支付宝账号失败，请重试");
      } finally {
        loading.value = false;
      }
    }
  });
};
const getEditZfb = async () => {
  zfbTitle.value = "编辑支付宝账号";
  dialogVisibleZFB.value = true;
  // 兼容两种字段名：alipayAccount 和 aliPayAccount
  authForm1.zfbName = userInfo.value.alipayAccount || userInfo.value.aliPayAccount || userInfo.value.phone;
};
const getDelZfb = async () => {
  ElMessageBox.confirm("确定要删除该账号,删除后无法进行提现操作", "删除账号", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        loading.value = true;
        const res: any = await deleteAlipayAccount();
        if (res && res.code == 200) {
          ElMessage.success(res.msg || "删除成功");
          // 立即更新响应式的 userInfo，清空支付宝账号
          userInfo.value.alipayAccount = null;
          userInfo.value.aliPayAccount = null;
          // 更新本地存储中的支付宝账号
          try {
            const geekerUser = localGet("geeker-user");
            if (geekerUser && geekerUser.userInfo) {
              geekerUser.userInfo.alipayAccount = null;
              geekerUser.userInfo.aliPayAccount = null;
              localSet("geeker-user", geekerUser);
            }
          } catch (error) {
            console.error("更新本地存储失败:", error);
          }
          // 重新获取用户信息
          try {
            const param = {
              phone: userInfo.value.phone
            };
            const res1: any = await getMerchantByPhone(param);
            if (res1.code == 200) {
              // 统一处理支付宝账号字段名
              const updatedData = res1.data || {};
              // 如果后端返回的支付宝账号为空或null，确保两个字段都是null
              if (!updatedData.alipayAccount && !updatedData.aliPayAccount) {
                updatedData.alipayAccount = null;
                updatedData.aliPayAccount = null;
              } else if (updatedData.aliPayAccount && !updatedData.alipayAccount) {
                updatedData.alipayAccount = updatedData.aliPayAccount;
              }
              // 更新响应式数据
              userInfo.value = { ...userInfo.value, ...updatedData };
              // 确保支付宝账号字段正确
              userInfo.value.alipayAccount = updatedData.alipayAccount || null;
              userInfo.value.aliPayAccount = updatedData.aliPayAccount || null;
              // 更新本地存储
              const geekerUser = localGet("geeker-user");
              if (geekerUser) {
                geekerUser.userInfo = { ...geekerUser.userInfo, ...updatedData };
                // 确保两个字段名都保存（如果为null也要保存）
                geekerUser.userInfo.alipayAccount = updatedData.alipayAccount || null;
                geekerUser.userInfo.aliPayAccount = updatedData.aliPayAccount || null;
                localSet("geeker-user", geekerUser);
              }
            }
          } catch (error) {
            console.error("获取用户信息失败:", error);
          }
        } else {
          ElMessage.error(res.msg || "删除失败，请重试");
        }
      } catch (error) {
        console.error("删除支付宝账号失败:", error);
        ElMessage.error("删除失败，请重试");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 跳转到提现申请页面
// const goToCashApply = () => {
//   router.push("/financialManagement/cashApply");
// };

// 忘记密码表单验证规则
const forgotPasswordRules: FormRules = {
  verificationCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { pattern: /^\d{6}$/, message: "提现密码必须为6位数字", trigger: "blur" }
  ],
  confireNewPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== forgotPasswordForm.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 检查提现密码状态
const checkPasswordStatus = async () => {
  try {
    if (userInfo.value.idCard && userInfo.value.id) {
      const param = {
        storeUserId: userInfo.value.id
      };
      const res: any = await checkPayPassword(param as any);
      if (res.code == 200) {
        // 如果已设置提现密码，显示修改密码界面
        if (res.data.data == "true") {
          twoEnterPage.value = true;
          withdrawPass.value = false;
          currentStep.value = 1; // 重置步骤
        } else {
          // 如果未设置提现密码，显示首次设置界面
          twoEnterPage.value = false;
          withdrawPass.value = true;
        }
      }
    }
  } catch (error) {
    console.error("检查提现密码状态失败:", error);
  }
};

// 检查提现密码并自动跳转
const checkWithdrawPassword = async () => {
  try {
    // 如果已实名认证，检查是否设置了提现密码
    if (userInfo.value.idCard) {
      const param = {
        storeUserId: userInfo.value.id
      };
      const res: any = await checkPayPassword(param as any);
      if (res.code == 200) {
        // 如果未设置提现密码，自动跳转到提现密码标签页
        if (res.data.data == "false") {
          activeTab.value = "withdrawPassword";
        } else {
          activeTab.value = "receivingAccount";
        }
      }
    }
  } catch (error) {
    console.error("检查提现密码失败:", error);
  }
};

// 页面加载时检查
onMounted(() => {
  checkWithdrawPassword();
});

// 获取用户手机号
const userPhone = computed(() => {
  return localGet("iphone") || localGet("geeker-user")?.userInfo?.phone || "";
});
// 掩码显示手机号
const maskedPhone = computed(() => {
  if (!userPhone.value || userPhone.value.length !== 11) {
    return "";
  }
  return userPhone.value.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
});
// 获取支付宝账号（兼容两种字段名）
const alipayAccount = computed(() => {
  return userInfo.value.alipayAccount || userInfo.value.aliPayAccount || null;
});

const handleTabClick = async (tab: any) => {
  // 根据不同的标签页可以跳转到不同的页面或显示不同的内容
  console.log("切换到标签:", tab.props.name);
  // 如果切换到提现密码标签页，检查提现密码状态
  if (tab.props.name === "withdrawPassword") {
    await checkPasswordStatus();
  }
};

const handleCancel = () => {
  dialogVisible.value = false;
  // 重置表单
  if (authFormRef.value) {
    authFormRef.value.resetFields();
  }
};

const handleForgetConfirmZFB = async () => {
  if (!forgotPasswordFormRef.value) return;

  // 表单验证
  await forgotPasswordFormRef.value.validate(async valid => {
    if (valid) {
      // 验证新密码和确认密码是否一致
      if (forgotPasswordForm.newPassword !== forgotPasswordForm.confireNewPassword) {
        ElMessage.error("两次输入的密码不一致");
        return;
      }

      // 验证密码长度
      if (forgotPasswordForm.newPassword.length !== 6) {
        ElMessage.error("提现密码必须为6位数字");
        return;
      }

      loading.value = true;
      try {
        // 第一步：验证短信验证码
        const checkCodeRes: any = await getCheckSmsCode({
          phone: userInfo.value.phone,
          appType: "2",
          businessType: "7",
          code: forgotPasswordForm.verificationCode
        });

        if (checkCodeRes.code !== 200) {
          ElMessage.error(checkCodeRes.msg || "验证码验证失败");
          loading.value = false;
          return;
        }

        // 第二步：设置提现密码
        const res: any = await setPayPassword({
          payPassword: forgotPasswordForm.newPassword,
          id: userInfo.value.id
        });

        if (res.code == 200) {
          ElMessage.success(res.msg || "提现密码设置成功");

          // 更新本地存储中的提现密码
          try {
            const geekerUser = localGet("geeker-user");
            if (geekerUser && geekerUser.userInfo) {
              geekerUser.userInfo.payPassword = forgotPasswordForm.newPassword;
              localSet("geeker-user", geekerUser);
            }
          } catch (error) {
            console.error("更新本地存储失败:", error);
          }

          // 关闭对话框并重置表单
          forgotPasswordVisible.value = false;
          forgotPasswordFormRef.value?.resetFields();

          // 重置表单数据
          forgotPasswordForm.newPassword = "";
          forgotPasswordForm.confireNewPassword = "";
          forgotPasswordForm.verificationCode = "";

          // 刷新密码状态
          await checkPasswordStatus();
        } else {
          ElMessage.error(res.msg || "设置提现密码失败");
        }
      } catch (error: any) {
        console.error("设置提现密码失败:", error);
        ElMessage.error(error?.response?.data?.msg || error?.message || "设置提现密码失败，请稍后重试");
      } finally {
        loading.value = false;
      }
    }
  });
};

const handleCancelZFB = () => {
  dialogVisibleZFB.value = false;
  // 重置表单
  if (authFormRef1.value) {
    authFormRef1.value.resetFields();
  }
};
</script>

<style scoped lang="scss">
.real-name-page {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 100px);
  background-color: #f5f7fa;
}

// 头部区域
.header-section {
  padding: 16px 24px;
  background: linear-gradient(90deg, #7f9dff 0%, rgb(255 255 255 / 0%) 100%);
  border-bottom: 1px solid #e4e7ed;
  border-radius: 10px;
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 100%;
    margin: 0 auto;
    .shop-info {
      display: flex;
      gap: 12px;
      align-items: center;
      .homeIcon {
        width: 76px;
        height: 76px;
        margin-right: 8px;
        margin-left: 25px;
      }
      .shop-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 32px;
        background-color: #ffffff;
        border-radius: 6px;
        box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
      }
      .shop-name {
        font-size: 16px;
        font-weight: 500;
        color: #ffffff;
      }
    }
    .auth-status {
      .status-badge {
        display: inline-block;
        padding: 3px 20px;
        font-size: 14px;
        font-weight: 500;
        color: #ffffff;
        background: #f81515;
        border-radius: 39px;
      }
      .status-badge-success {
        background: #7f9dff;
      }
    }
  }
}

// 标签导航栏
.tabs-section {
  padding: 0 24px;
  background-color: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  :deep(.el-tabs) {
    max-width: 100%;
    margin: 0 auto;
    .el-tabs__header {
      margin: 0;
      border-bottom: none;
    }
    .el-tabs__nav-wrap::after {
      height: 1px;
      background-color: #e4e7ed;
    }
    .el-tabs__item {
      height: 48px;
      padding: 0 20px;
      font-size: 15px;
      font-weight: 400;
      line-height: 48px;
      color: #606266;
      &.is-active {
        font-weight: 500;
        color: #409eff;
        &::after {
          position: absolute;
          bottom: 0;
          left: 50%;
          width: 40px;
          height: 3px;
          content: "";
          background-color: #409eff;
          border-radius: 2px 2px 0 0;
          transform: translateX(-50%);
        }
      }
      &:hover {
        color: #409eff;
      }
    }
  }
}
.auth-button {
  padding: 22px 35px;
  font-size: 16px;
  font-weight: 500;
  background-color: #7f9dff;
  border: none;
  border-radius: 6px;
  transition: all 0.3s;
}

// 主内容区
.content-section {
  display: flex;
  flex: 1;
  justify-content: center;
  min-height: 400px;
  background-color: #ffffff;
  .content-wrapper-realName {
    width: 100%;
    .goAuthBtn {
      display: flex;
      justify-content: center;
      padding: 180px 0 0;
    }
    .auth-div {
      padding-top: 10px;
      padding-left: 41px;
      .auth-row {
        padding: 10px 0;
      }
    }
  }
  .content-wrapper {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 40px 24px;
    .zfb-wrapper {
      display: flex;
      justify-content: space-between;
      width: 100%;
      height: 80px;
      padding: 0 20px;
      border: 1px solid #dddddd;
      border-radius: 8px;
      .operate {
        display: flex;
        align-items: center;
        color: #7f9dff;
        div {
          margin-left: 20px;
        }
      }
      .zfb-left {
        display: flex;
        align-items: center;
      }
      .zfbIcon {
        width: 60px;
        height: 60px;
        margin-right: 10px;
      }
    }
  }
  .password-form-wrapper {
    width: 100%;
    padding-left: 15px;
    background-color: #ffffff;
    border-radius: 8px;
    .form-wrapper {
      width: 400px;
      margin: 30px auto;
    }
    .password-input {
      width: 100%;
    }
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #303133;
    }
  }
  .submit-button {
    width: 100%;
    padding: 22px 35px;
    margin-top: 20px;
    font-size: 16px;
    font-weight: 500;
    background-color: #7f9dff;
    border: none;
    border-radius: 6px;
  }
  .password-form-wrapper-step {
    width: 480px;
    .form-wrapper {
      width: 400px;
      margin-top: 40px;
    }
    .forget-password {
      font-size: 14px;
      color: #7f9dff;
      text-align: right;
      cursor: pointer;
    }
    :deep(.el-step__head.is-process .el-step__icon) {
      color: #909399;
      border-color: #909399 !important; /* 设置圆圈边框为灰色 */
    }
    :deep(.el-steps) {
      .el-step__head {
        .el-step__icon {
          width: 30px;
          height: 30px;
          font-size: 16px;
          font-weight: 600;
        }
      }
    }
  }
}
</style>
