<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 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, adminList, adminUpdate, normalizeAdminList, type AboutExperience, type AboutProfile } from '@/api'

const toast = useToast()
const { guardAdmin } = useAdminGuard()
const loading = ref(false)
const submitting = ref(false)
const profileId = ref<number | ''>('')
const techInput = ref('')

const form = reactive({
  name: '',
  avatar: '',
  location: '',
  email: '',
  wechat: '',
  bio: '',
  isPrimary: 1,
})
const techStack = ref<string[]>([])
const experiences = ref<AboutExperience[]>([])

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    const list = normalizeAdminList(await adminList('about')) as AboutProfile[]
    const first = list[0]
    if (first) {
      profileId.value = Number(first.id) || ''
      form.name = String(first.name || '')
      form.avatar = String(first.avatar || '')
      form.location = String(first.location || '')
      form.email = String(first.email || '')
      form.wechat = String(first.wechat || '')
      form.bio = String(first.bio || '')
      form.isPrimary = first.isPrimary === 0 || first.isPrimary === false ? 0 : 1
      techStack.value = Array.isArray(first.techStack) ? [...first.techStack] : []
      experiences.value = Array.isArray(first.experiences) ? [...first.experiences] : []
    }
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onShow(load)

function addTech() {
  const t = techInput.value.trim()
  if (!t) return
  techStack.value.push(t)
  techInput.value = ''
}

function addExp() {
  experiences.value.push({ year: '', role: '', company: '' })
}

async function onSubmit() {
  submitting.value = true
  try {
    const payload = {
      ...form,
      techStack: techStack.value,
      experiences: experiences.value,
    }
    if (profileId.value) await adminUpdate('about', profileId.value, payload)
    else {
      const created = await adminCreate('about', payload) as AboutProfile
      if (created?.id) profileId.value = Number(created.id)
    }
    toast.success('已保存')
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '保存失败')
  }
  finally {
    submitting.value = false
  }
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="关于页面" show-back />
    <view class="page-pad">
      <view class="admin-card form-card">
        <AdminFormField label="姓名" required>
          <wd-input v-model="form.name" placeholder="姓名" clearable />
        </AdminFormField>
        <AdminMediaPicker v-model="form.avatar" label="头像" />
        <AdminFormField label="地点">
          <wd-input v-model="form.location" placeholder="地点" clearable />
        </AdminFormField>
        <AdminFormField label="邮箱">
          <wd-input v-model="form.email" placeholder="邮箱" clearable />
        </AdminFormField>
        <AdminFormField label="微信">
          <wd-input v-model="form.wechat" placeholder="微信" clearable />
        </AdminFormField>
        <view class="switch-row">
          <text>主档案</text>
          <wd-switch :model-value="!!form.isPrimary" @change="(v: boolean) => form.isPrimary = v ? 1 : 0" />
        </view>
        <AdminFormField label="简介">
          <wd-textarea v-model="form.bio" placeholder="简介" />
        </AdminFormField>
        <view class="section">
          <text class="label text-art-muted">技术栈</text>
          <view class="tags">
            <view v-for="(t, i) in techStack" :key="i" class="tag" @click="techStack.splice(i, 1)">{{ t }} ×</view>
          </view>
          <view class="row-input">
            <wd-input v-model="techInput" placeholder="添加技术" clearable />
            <wd-button size="small" @click="addTech">添加</wd-button>
          </view>
        </view>
        <view class="section">
          <view class="sec-head">
            <text class="label text-art-muted">工作经历</text>
            <wd-button size="small" plain @click="addExp">添加</wd-button>
          </view>
          <view v-for="(exp, i) in experiences" :key="i" class="exp">
            <AdminFormField label="年份">
              <wd-input v-model="exp.year" placeholder="年份" clearable />
            </AdminFormField>
            <AdminFormField label="职位">
              <wd-input v-model="exp.role" placeholder="职位" clearable />
            </AdminFormField>
            <AdminFormField label="公司">
              <wd-input v-model="exp.company" placeholder="公司" clearable />
            </AdminFormField>
            <wd-button size="small" type="warning" plain @click="experiences.splice(i, 1)">删除</wd-button>
          </view>
        </view>
        <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; }
.switch-row {
  display: flex; justify-content: space-between; align-items: center;
  padding: 20rpx 0; color: rgb(var(--art-text));
}
.section { margin: 20rpx 0; }
.label { font-size: 24rpx; }
.tags { display: flex; flex-wrap: wrap; gap: 10rpx; margin: 12rpx 0; }
.tag {
  padding: 6rpx 14rpx; border-radius: 8rpx; font-size: 22rpx;
  background: rgba(212, 179, 131, 0.2); color: rgb(var(--art-accent));
}
.row-input { display: flex; gap: 12rpx; align-items: center; }
.sec-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12rpx; }
.exp {
  padding: 16rpx; margin-bottom: 16rpx; border-radius: 12rpx;
  background: rgba(255, 255, 255, 0.04);
}
</style>
