<script setup lang="ts">
/**
 * 用户表单：完整资料字段。
 */
import { computed, reactive, ref } from 'vue'
import { onLoad, onShow } 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 AdminMediaPicker from '../../components/AdminMediaPicker.vue'
import AdminFormField from '../../components/AdminFormField.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import { adminCreate, adminGet, adminUpdate, type User } from '@/api'

const toast = useToast()
const { guardAdmin } = useAdminGuard()
const mode = ref<'create' | 'edit'>('create')
const id = ref('')
const loading = ref(false)
const submitting = ref(false)

const form = reactive({
  username: '',
  email: '',
  avatar: '',
  role: 'editor',
  isActive: 1,
  bio: '',
  phone: '',
  wechat: '',
  wechatQrcode: '',
})

const pageTitle = computed(() => (mode.value === 'create' ? '新建用户' : '编辑用户'))

async function load() {
  if (!guardAdmin()) return
  if (mode.value !== 'edit' || !id.value) return
  loading.value = true
  try {
    const data = await adminGet('users', id.value) as User
    Object.assign(form, {
      username: data.username || '',
      email: data.email || '',
      avatar: data.avatar || '',
      role: data.role || 'editor',
      isActive: data.isActive === 0 ? 0 : 1,
      bio: data.bio || '',
      phone: data.phone || '',
      wechat: data.wechat || '',
      wechatQrcode: data.wechatQrcode || '',
    })
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onLoad((q) => {
  mode.value = q?.mode === 'edit' ? 'edit' : 'create'
  id.value = String(q?.id || '')
})
onShow(load)

async function onSubmit() {
  if (!form.username.trim()) {
    toast.show('请填写用户名')
    return
  }
  submitting.value = true
  try {
    if (mode.value === 'edit' && id.value) await adminUpdate('users', id.value, { ...form })
    else await adminCreate('users', { ...form })
    toast.success('已保存')
    setTimeout(() => uni.navigateBack(), 400)
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar :title="pageTitle" show-back />
    <view class="page-pad">
      <view class="admin-card form-card">
        <AdminFormField label="用户名" required>
          <wd-input v-model="form.username" placeholder="用户名" clearable />
        </AdminFormField>
        <AdminFormField label="邮箱">
          <wd-input v-model="form.email" placeholder="邮箱" clearable />
        </AdminFormField>
        <AdminMediaPicker v-model="form.avatar" label="头像" />
        <wd-picker
          :columns="[[{ label: 'admin', value: 'admin' }, { label: 'editor', value: 'editor' }, { label: 'viewer', value: 'viewer' }]]"
          @confirm="({ value }: { value: unknown[] }) => { form.role = String((value?.[0] as { value?: string })?.value ?? value?.[0] ?? 'editor') }"
        >
          <view class="picker-row"><text>角色</text><text class="val">{{ form.role }}</text></view>
        </wd-picker>
        <view class="switch-row">
          <text>启用</text>
          <wd-switch :model-value="!!form.isActive" @change="(v: boolean) => form.isActive = v ? 1 : 0" />
        </view>
        <AdminFormField label="简介">
          <wd-textarea v-model="form.bio" placeholder="简介" />
        </AdminFormField>
        <AdminFormField label="手机">
          <wd-input v-model="form.phone" placeholder="手机" clearable />
        </AdminFormField>
        <AdminFormField label="微信">
          <wd-input v-model="form.wechat" placeholder="微信" clearable />
        </AdminFormField>
        <AdminMediaPicker v-model="form.wechatQrcode" label="微信二维码" />
        <wd-button
          block
          type="primary"
          :loading="submitting"
          custom-style="margin-top:24rpx;background:#d4b383;border-color:#d4b383;"
          @click="onSubmit"
        >
          保存
        </wd-button>
      </view>
      <wd-loading v-if="loading" />
    </view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 80rpx; }
.picker-row, .switch-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 20rpx 0; color: rgb(var(--art-text));
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.val { color: rgba(255, 255, 255, 0.6); }
</style>
