<script setup lang="ts">
/**
 * 独立管理员登录 / 合并账号页（content 分包）。
 * mode=merge：校验管理员密码，绑定微信并注销当前游客。
 * 默认 mode：普通账号密码登录。
 */
import { computed, reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import ContentPageHeader from '../../components/ContentPageHeader.vue'
import StaffLoginForm from '../../components/StaffLoginForm.vue'
import { useAuth } from '@/composables/useAuth'
import { useAppMode } from '@/composables/useAppMode'
import { loginApi, mergeAccountApi } from '@/api'

const toast = useToast()
const { login, isAuthenticated } = useAuth()
const { setLoginType } = useAppMode()

const submitting = ref(false)
const form = reactive({ username: '', password: '' })
/** merge = 合并账号；login = 普通登录 */
const mode = ref<'login' | 'merge'>('login')

const isMerge = computed(() => mode.value === 'merge')
const pageTitle = computed(() => (isMerge.value ? '合并账号' : '登录'))
const headerTitle = computed(() => (isMerge.value ? '合并到管理员' : '管理员登录'))
const headerDesc = computed(() => (
  isMerge.value
    ? '验证管理员账号密码后，当前游客微信将绑定到该账号，游客账号逻辑删除。'
    : '使用账号密码进入员工身份，仅管理员与编辑者可切换后台。'
))
const headerEyebrow = computed(() => (isMerge.value ? 'Merge Account' : 'Staff Login'))
const hintText = computed(() => (
  isMerge.value
    ? '合并需要已通过微信静默登录的游客身份。'
    : '账号仅用于站点管理，与微信静默登录相互独立。'
))

onLoad((q) => {
  const m = String(q?.mode || '').toLowerCase()
  mode.value = m === 'merge' ? 'merge' : 'login'
})

/** 成功后写 token 并返回「我的」 */
const finishAuth = (res: { token: string, user: { role?: string, [k: string]: unknown }, expire: number }, okMsg: string) => {
  login(res.token, { ...res.user }, res.expire)
  const role = (res.user.role || '').toLowerCase()
  const staff = role === 'admin' || role === 'editor' || role.includes('admin') || role.includes('editor')
  setLoginType(staff ? 'staff' : 'guest')
  toast.success(okMsg)
  form.password = ''
  const pages = getCurrentPages()
  if (pages.length > 1) {
    uni.navigateBack()
  }
  else {
    uni.reLaunch({ url: '/pages/mine/index' })
  }
}

/**
 * 提交：按 mode 分流普通登录 / 合并账号。
 */
const onSubmit = async (payload: { username: string, password: string }) => {
  form.username = payload.username
  form.password = payload.password
  if (!form.username || !form.password) {
    toast.show('请输入账号密码')
    return
  }
  if (isMerge.value && !isAuthenticated()) {
    toast.error('请先完成微信静默登录后再合并')
    return
  }
  submitting.value = true
  try {
    if (isMerge.value) {
      const res = await mergeAccountApi(form.username, form.password)
      finishAuth(res, '合并成功')
    }
    else {
      const res = await loginApi(form.username, form.password)
      finishAuth(res, '登录成功')
    }
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : (isMerge.value ? '合并失败' : '登录失败'))
  }
  finally {
    submitting.value = false
  }
}
</script>

<template>
  <AppPageShell>
    <AppNavbar :title="pageTitle" show-back />
    <view class="page-pad">
      <ContentPageHeader
        :eyebrow="headerEyebrow"
        :title="headerTitle"
        :desc="headerDesc"
      />
      <view class="login-card art-card animate-reveal">
        <StaffLoginForm
          v-model:username="form.username"
          v-model:password="form.password"
          :loading="submitting"
          :submit-label="isMerge ? '确认合并' : '登录'"
          @submit="onSubmit"
        />
        <view class="hint text-art-muted">{{ hintText }}</view>
      </view>
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad {
  padding: 32rpx 32rpx 80rpx;
}
.login-card {
  padding: 40rpx 32rpx;
}
.hint {
  margin-top: 28rpx;
  font-size: 24rpx;
  line-height: 1.6;
}
</style>
