<template>
  <div class="pc-safety-container">
    <el-card class="safety-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="back-action" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            <span class="back-text">{{ t('返回') }}</span>
          </div>

          <el-divider direction="vertical" class="header-divider" />

          <div class="decorate-bar bmc"></div>
          <span class="title">{{ t('账户安全') }}</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="safety-tabs" tab-position="left">

        <el-tab-pane :label="t('修改登录密码')" name="login_pwd">
          <div class="form-wrapper">
            <h3 class="section-title">{{ t('修改登录密码') }}</h3>
            <p class="section-desc">{{ t('定期修改密码可以保护您的账号安全。') }}</p>

            <el-form
                ref="pwdFormRef"
                :model="pwdForm"
                :rules="pwdRules"
                label-position="top"
                size="large"
                class="safety-form"
            >
              <el-form-item :label="t('旧密码')" prop="old_password">
                <el-input
                    v-model="pwdForm.old_password"
                    type="password"
                    show-password
                    :placeholder="t('请输入旧密码')"
                />
              </el-form-item>

              <el-form-item :label="t('新密码')" prop="new_password">
                <el-input
                    v-model="pwdForm.new_password"
                    type="password"
                    show-password
                    :placeholder="t('请输入新密码（至少6位）')"
                />
              </el-form-item>

              <el-form-item :label="t('确认新密码')" prop="confirmPassword">
                <el-input
                    v-model="pwdForm.confirmPassword"
                    type="password"
                    show-password
                    :placeholder="t('请再次输入新密码')"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" class="submit-btn" @click="handleResetPassword">
                  {{ t('确认修改登录密码') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <el-tab-pane :label="t('修改资金密码')" name="fund_pwd">
          <div class="form-wrapper">
            <h3 class="section-title">{{ t('修改资金密码') }}</h3>
            <p class="section-desc">{{ t('资金密码用于提现等涉及资金流转的安全验证。如果是首次设置，旧密码请留空。') }}</p>

            <el-form
                ref="fundFormRef"
                :model="fundForm"
                :rules="fundRules"
                label-position="top"
                size="large"
                class="safety-form"
            >
              <el-form-item :label="t('旧资金密码 (首次设置可为空)')" prop="old_password">
                <el-input
                    v-model="fundForm.old_password"
                    type="password"
                    show-password
                    :placeholder="t('请输入旧资金密码')"
                />
              </el-form-item>

              <el-form-item :label="t('新资金密码')" prop="password">
                <el-input
                    v-model="fundForm.password"
                    type="password"
                    show-password
                    :placeholder="t('请输入新资金密码（至少6位）')"
                />
              </el-form-item>

              <el-form-item :label="t('确认新资金密码')" prop="confirmPassword">
                <el-input
                    v-model="fundForm.confirmPassword"
                    type="password"
                    show-password
                    :placeholder="t('请再次输入新资金密码')"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" class="submit-btn" @click="handleModifyFundPassword">
                  {{ t('确认修改资金密码') }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <el-tab-pane :label="t('注销账号')" name="delete_acc">
          <div class="form-wrapper danger-zone">
            <el-icon class="warning-icon" color="#F56C6C"><WarningFilled /></el-icon>
            <h3 class="danger-title">{{ t('注销账号') }}</h3>
            <p class="danger-desc">
              {{ t('注销账户后，系统将删除并清空您的账户所有信息。此操作') }}
              <strong>{{ t('不可逆转') }}</strong>
              {{ t('，请谨慎操作！') }}
            </p>
            <el-button type="danger" size="large" plain @click="handleDeleteAccount">
              {{ t('确认注销账号') }}
            </el-button>
          </div>
        </el-tab-pane>

      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { resetPassword, modifySafeWord, deleteAccount } from '@/request/api.js'
// 引入 ArrowLeft 图标
import { WarningFilled, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()

// === 返回上一页逻辑 ===
const goBack = () => {
  router.back()
}

// 当前激活的 Tab
const activeTab = ref('login_pwd')

if(route.query.active) {
  activeTab.value = route.query.active
}

// =====================================
// === 1. 登录密码逻辑
// =====================================
const pwdFormRef = ref(null)
const pwdForm = reactive({
  old_password: '',
  new_password: '',
  confirmPassword: ''
})

// 自定义校验：登录确认密码
const validatePwdConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('请再次输入新密码')))
  } else if (value !== pwdForm.new_password) {
    callback(new Error(t('两次输入的新密码不一致')))
  } else {
    callback()
  }
}

// 登录密码表单规则
const pwdRules = reactive({
  old_password: [{ required: true, message: t('请输入旧密码'), trigger: 'blur' }],
  new_password: [
    { required: true, message: t('请输入新密码'), trigger: 'blur' },
    { min: 6, message: t('新密码长度不能少于6位'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePwdConfirm, trigger: 'blur' }
  ]
})

const handleResetPassword = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (!valid) return

    if (pwdForm.old_password === pwdForm.new_password) {
      // 触发表单字段本身的错误提示，而不是全局 Toast
      pwdFormRef.value.validateField('new_password', () => t('新密码不能与旧密码相同'))
      return
    }

    // 接口内部已包含 loading 和错误处理
    const res = await resetPassword({
      old_password: pwdForm.old_password,
      new_password: pwdForm.new_password
    })

    if (res && res.code === 1) {
      // 成功后清除本地登录态并跳回登录页
      localStorage.clear()
      sessionStorage.clear()
      router.replace({ name: 'login' })
    }
  })
}

// =====================================
// === 2. 资金密码逻辑
// =====================================
const fundFormRef = ref(null)
const fundForm = reactive({
  old_password: '',
  password: '',
  confirmPassword: ''
})

// 自定义校验：资金确认密码
const validateFundConfirm = (rule, value, callback) => {
  if (value === '') {
    callback(new Error(t('请再次输入新资金密码')))
  } else if (value !== fundForm.password) {
    callback(new Error(t('两次输入的新资金密码不一致')))
  } else {
    callback()
  }
}

// 资金密码表单规则
const fundRules = reactive({
  password: [
    { required: true, message: t('请输入新资金密码'), trigger: 'blur' },
    { min: 6, message: t('新资金密码长度不能少于6位'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateFundConfirm, trigger: 'blur' }
  ]
})

const handleModifyFundPassword = () => {
  fundFormRef.value.validate(async (valid) => {
    if (!valid) return

    if (fundForm.old_password && fundForm.old_password === fundForm.password) {
      fundFormRef.value.validateField('password', () => t('新资金密码不能与旧密码相同'))
      return
    }

    const requestData = { password: fundForm.password }
    if (fundForm.old_password) {
      requestData.old_password = fundForm.old_password
    }

    const res = await modifySafeWord(requestData)

    if (res && res.code === 1) {
      // 修改资金密码成功后，重置表单即可，无需退出登录
      fundFormRef.value.resetFields()
    }
  })
}

// =====================================
// === 3. 注销账号逻辑
// =====================================
const handleDeleteAccount = () => {
  ElMessageBox.confirm(
      t('是否注销账户？注销账户后，系统将彻底删除并清空账户所有数据。'),
      t('危险操作确认'),
      {
        confirmButtonText: t('确认注销'),
        cancelButtonText: t('取消'),
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
  ).then(async () => {
    const res = await deleteAccount()
    if (res && res.code === 1) {
      localStorage.clear()
      sessionStorage.clear()
      router.replace({ name: 'login' })
    }
  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped lang="scss">
$main-color: #f8b932;

.pc-safety-container {
  min-height: 100%;
  padding: 10px;
  box-sizing: border-box;

  .safety-card {
    border-radius: 8px;
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    min-height: 600px; /* 保证有一个舒适的基础高度 */
  }

  /* Header 样式包含返回按钮 */
  .card-header {
    display: flex;
    align-items: center;

    .back-action {
      display: flex;
      align-items: center;
      cursor: pointer;
      color: var(--el-text-color-regular);
      font-size: 14px;
      transition: color 0.2s;

      .el-icon {
        font-size: 16px;
        margin-right: 4px;
      }

      &:hover {
        color: $main-color;
      }
    }

    .header-divider {
      margin: 0 16px;
      height: 1em;
    }

    .decorate-bar {
      width: 4px;
      height: 16px;
      border-radius: 2px;
      background-color: $main-color;
      margin-right: 10px;
    }

    .title {
      font-size: 16px;
      font-weight: bold;
      color: var(--el-text-color-primary);
    }
  }

  /* 左侧 Tabs 样式调整 */
  :deep(.safety-tabs) {
    .el-tabs__header {
      margin-right: 40px; /* 拉开菜单和右侧内容的距离 */
    }
    .el-tabs__item {
      font-size: 15px;
      padding: 0 30px !important;
      height: 50px;
      line-height: 50px;
      text-align: left;

      &.is-active, &:hover {
        color: $main-color;
      }
    }
    .el-tabs__active-bar {
      background-color: $main-color;
    }
  }

  /* 内部表单区域统一样式 */
  .form-wrapper {
    max-width: 480px; /* PC端表单通常限制最大宽度，避免太长难看 */
    padding: 20px 0;

    .section-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--el-text-color-primary);
      margin-bottom: 8px;
      margin-top: 0;
    }

    .section-desc {
      font-size: 14px;
      color: var(--el-text-color-regular);
      margin-bottom: 30px;
    }

    .safety-form {
      .submit-btn {
        width: 100%;
        margin-top: 20px;
        font-weight: bold;
      }
    }
  }

  /* 注销账号专属样式 (危险区域) */
  .danger-zone {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 40px;
    background-color: var(--el-fill-color-light);
    border: 1px dashed var(--el-color-danger);
    border-radius: 8px;

    .warning-icon {
      font-size: 48px;
      margin-bottom: 20px;
    }

    .danger-title {
      font-size: 20px;
      color: var(--el-text-color-primary);
      margin-bottom: 12px;
      margin-top: 0;
    }

    .danger-desc {
      font-size: 14px;
      line-height: 1.6;
      color: var(--el-text-color-regular);
      margin-bottom: 30px;

      strong {
        color: var(--el-color-danger);
      }
    }
  }
}
</style>
