<script setup lang="ts">
/**
 * 后台个人中心：资料编辑（头像/联系方式）+ 修改密码。
 */
import { reactive, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppFloatingTabbar from '@/components/layout/AppFloatingTabbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import AdminMediaPicker from '../../components/AdminMediaPicker.vue'
import AdminFormField from '../../components/AdminFormField.vue'
import { useAuth } from '@/composables/useAuth'
import { useAppMode } from '@/composables/useAppMode'
import { useTheme } from '@/composables/useTheme'
import { getCurrentUser, updateMe, updatePassword } from '@/api'
import { resolveMediaUrl } from '@/utils/request'

const toast = useToast()
const { isAuthenticated, getUser, setUser } = useAuth()
const { canEnterAdmin } = useAppMode()
const { apply } = useTheme()

const loading = ref(false)
const submitting = ref(false)
const pwdSubmitting = ref(false)
const user = ref(getUser())
const profile = reactive({
  email: '',
  bio: '',
  phone: '',
  wechat: '',
  avatar: '',
  wechatQrcode: '',
})
const form = reactive({ oldPassword: '', newPassword: '', confirm: '' })

function guardAdmin() {
  if (!isAuthenticated() || !canEnterAdmin.value) {
    uni.reLaunch({ url: '/pages/mine/index' })
    return false
  }
  return true
}

async function load() {
  apply()
  if (!guardAdmin()) return
  loading.value = true
  try {
    const me = await getCurrentUser()
    user.value = { ...me } as typeof user.value
    profile.email = me.email || ''
    profile.bio = me.bio || ''
    profile.phone = me.phone || ''
    profile.wechat = me.wechat || ''
    profile.avatar = me.avatar || ''
    profile.wechatQrcode = me.wechatQrcode || ''
  }
  catch {
    user.value = getUser()
  }
  finally {
    loading.value = false
  }
}

onShow(load)

async function saveProfile() {
  submitting.value = true
  try {
    const updated = await updateMe({ ...profile })
    if (updated) setUser(updated as never)
    toast.success('资料已保存')
    load()
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}

const onSubmit = async () => {
  if (!form.oldPassword || !form.newPassword) {
    toast.show('请填写原密码与新密码')
    return
  }
  if (form.newPassword !== form.confirm) {
    toast.show('两次新密码不一致')
    return
  }
  pwdSubmitting.value = true
  try {
    await updatePassword(form.oldPassword, form.newPassword)
    toast.success('密码已更新')
    form.oldPassword = ''
    form.newPassword = ''
    form.confirm = ''
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '更新失败')
  }
  finally {
    pwdSubmitting.value = false
  }
}
</script>

<template>
  <AppPageShell admin with-tab-pad>
    <AppNavbar title="个人中心" show-back />
    <view class="page-pad">
      <view class="avatar-row">
        <image
          class="avatar"
          :src="resolveMediaUrl(profile.avatar || user.avatar) || '/static/logo.svg'"
          mode="aspectFill"
        />
        <view class="meta">
          <text class="name">{{ user.username }}</text>
          <text class="role text-art-accent font-mono-label">{{ user.role || 'staff' }}</text>
        </view>
      </view>

      <view class="admin-card form-card">
        <view class="section-title" style="font-size: 34rpx; margin-bottom: 24rpx;">个人资料</view>
        <AdminMediaPicker v-model="profile.avatar" label="头像" />
        <AdminFormField label="邮箱">
          <wd-input v-model="profile.email" placeholder="邮箱" clearable />
        </AdminFormField>
        <AdminFormField label="简介">
          <wd-textarea v-model="profile.bio" placeholder="简介" />
        </AdminFormField>
        <AdminFormField label="手机">
          <wd-input v-model="profile.phone" placeholder="手机" clearable />
        </AdminFormField>
        <AdminFormField label="微信">
          <wd-input v-model="profile.wechat" placeholder="微信" clearable />
        </AdminFormField>
        <AdminMediaPicker v-model="profile.wechatQrcode" label="微信二维码" />
        <wd-button
          block
          type="primary"
          :loading="submitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="saveProfile"
        >
          保存资料
        </wd-button>
      </view>

      <view class="admin-card form-card" style="margin-top: 24rpx;">
        <view class="section-title" style="font-size: 34rpx; margin-bottom: 24rpx;">修改密码</view>
        <AdminFormField label="原密码">
          <wd-input v-model="form.oldPassword" placeholder="原密码" show-password clearable />
        </AdminFormField>
        <AdminFormField label="新密码">
          <wd-input v-model="form.newPassword" placeholder="新密码" show-password clearable />
        </AdminFormField>
        <AdminFormField label="确认新密码">
          <wd-input v-model="form.confirm" placeholder="确认新密码" show-password clearable />
        </AdminFormField>
        <wd-button
          block
          type="primary"
          :loading="pwdSubmitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="onSubmit"
        >
          更新密码
        </wd-button>
      </view>
      <wd-loading v-if="loading" />
    </view>
    <AppFloatingTabbar />
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 48rpx; }
.avatar-row {
  display: flex;
  align-items: center;
  gap: 24rpx;
  margin-bottom: 28rpx;
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.06);
}
.meta { display: flex; flex-direction: column; gap: 8rpx; }
.name { font-size: 36rpx; color: rgb(var(--art-text)); font-weight: 600; }
.role { font-size: 22rpx; }
</style>
