<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { submitCertification, getMyCertification, withdrawCertification, uploadImageToMinio } from '@/api/appointment'
import { useUserStore } from '@/store'

definePage({
  style: { navigationBarTitleText: '角色认证' },
})

const userStore = useUserStore()

// 角色切换
const roleType = ref('employee')
const roleOptions = [
  { value: 'employee', label: '员工' },
  { value: 'guard', label: '保安' },
]

// ===== 员工：自动认证 =====
const empForm = ref({ real_name: '', phone: '' })
const empLoading = ref(false)
const empSuccess = ref(false)
const empDept = ref('')
const empPos = ref('')

async function handleEmpSubmit() {
  if (!empForm.value.real_name.trim()) { uni.showToast({ title: '请输入姓名', icon: 'none' }); return }
  if (!empForm.value.phone.trim()) { uni.showToast({ title: '请输入手机号', icon: 'none' }); return }
  empLoading.value = true
  try {
    const res = await uni.request({
      url: '/v1/certification/auto-verify',
      method: 'POST',
      data: { real_name: empForm.value.real_name.trim(), phone: empForm.value.phone.trim() },
    }) as any
    const body = res.data
    if (body.code === 200) {
      empSuccess.value = true
      empDept.value = body.data?.department_name || ''
      empPos.value = body.data?.position || ''
      await userStore.fetchUserInfo()
    } else {
      uni.showModal({ title: '认证失败', content: body.msg || '认证失败', showCancel: false })
    }
  } catch (err: any) {
    uni.showModal({ title: '认证失败', content: err.message || '网络错误', showCancel: false })
  } finally { empLoading.value = false }
}

// ===== 保安：传统认证 =====
const guardForm = ref({ real_name: '', phone: '', snapshot: [] as string[] })
const guardLoading = ref(false)
const myCert = ref<any>(null)
const withdrawing = ref(false)

async function loadMyCert() {
  try {
    await userStore.fetchUserInfo()
    myCert.value = await getMyCertification()
  } catch { /* ignore */ }
}

async function handleWithdraw() {
  uni.showModal({
    title: '确认撤回', content: '确定要撤回认证申请吗？',
    success: async (res) => {
      if (res.confirm) {
        withdrawing.value = true
        try {
          await withdrawCertification(myCert.value!.id)
          uni.showToast({ title: '已撤回', icon: 'success' })
          myCert.value = null
        } catch (err: any) { uni.showToast({ title: err.message || '撤回失败', icon: 'none' }) }
        finally { withdrawing.value = false }
      }
    },
  })
}

const uploadLoading = ref(false)
async function chooseScreenshots() {
  if (uploadLoading.value) return
  const maxCount = 9 - guardForm.value.snapshot.length
  if (maxCount <= 0) { uni.showToast({ title: '最多上传9张', icon: 'none' }); return }
  uni.chooseImage({
    count: maxCount, sourceType: ['album', 'camera'],
    success: async (res) => {
      uploadLoading.value = true
      uni.showLoading({ title: '上传中...' })
      try {
        const urls = await Promise.all(res.tempFilePaths.map((f: string) => uploadImageToMinio(f)))
        guardForm.value.snapshot.push(...urls.map((r: any) => r.url))
      } catch (err: any) { uni.showToast({ title: err.message || '上传失败', icon: 'none' }) }
      finally { uni.hideLoading(); uploadLoading.value = false }
    },
  })
}
function removeScreenshot(idx: number) { guardForm.value.snapshot.splice(idx, 1) }

async function handleGuardSubmit() {
  if (!guardForm.value.real_name.trim()) { uni.showToast({ title: '请输入姓名', icon: 'none' }); return }
  if (!guardForm.value.phone.trim()) { uni.showToast({ title: '请输入手机号', icon: 'none' }); return }
  if (!guardForm.value.snapshot.length) { uni.showToast({ title: '请上传证明材料', icon: 'none' }); return }
  guardLoading.value = true
  try {
    await submitCertification({
      real_name: guardForm.value.real_name.trim(),
      phone: guardForm.value.phone.trim(),
      role: 'guard',
      snapshot: guardForm.value.snapshot,
    })
    uni.showToast({ title: '提交成功，请等待审核', icon: 'success' })
    await loadMyCert()
  } catch (err: any) { uni.showToast({ title: err.message || '提交失败', icon: 'none' }) }
  finally { guardLoading.value = false }
}

function goBack() { uni.navigateBack() }

onMounted(async () => {
  await loadMyCert()
  if (userStore.isFormalEmployee) {
    empSuccess.value = true
  }
})
</script>

<template>
  <view class="min-h-screen bg-[#f5f7fa] px-4 pt-6">
    <!-- 被拒绝提示（放在最顶部） -->
    <view v-if="myCert && myCert.status === 2" class="bg-orange-50 border border-orange-200 rounded-xl p-4 mb-4">
      <view class="flex items-start gap-2">
        <text class="text-lg shrink-0">⚠️</text>
        <view>
          <text class="text-sm font-bold text-orange-700 block mb-1">认证未通过</text>
          <text class="text-xs text-orange-600 block mb-1">审核意见：{{ myCert.comment || '无' }}</text>
          <text class="text-xs text-orange-600 block mb-1">申请类型：{{ roleOptions.find(o => o.value === myCert.role)?.label || myCert.role }}</text>
          <text class="text-xs text-orange-500">请修改后重新提交申请</text>
        </view>
      </view>
    </view>

    <!-- 角色切换 -->
    <view class="bg-white rounded-xl p-4 mb-4" v-if="!empSuccess && (!myCert || myCert.status === 2)">
      <view class="flex gap-3 mb-2">
        <view
          v-for="opt in roleOptions" :key="opt.value"
          class="flex-1 py-2 text-center text-sm font-medium rounded-lg"
          :class="roleType === opt.value ? 'bg-[#2979ff] text-white' : 'bg-gray-100 text-[#666]'"
          @click="roleType = opt.value"
        >{{ opt.label }}</view>
      </view>
    </view>

    <!-- ====== 员工 ====== -->
    <template v-if="roleType === 'employee'">
      <view v-if="empSuccess" class="text-center pt-10">
        <view class="text-5xl mb-4">✅</view>
        <view class="text-lg font-bold text-[#1a1a1a] mb-2">认证成功</view>
        <view v-if="empDept" class="text-sm text-[#666] mb-1">部门：{{ empDept }}</view>
        <view v-if="empPos" class="text-sm text-[#666] mb-6">职位：{{ empPos }}</view>
        <wd-button type="primary" @click="goBack">返回</wd-button>
      </view>
      <view v-else class="bg-white rounded-xl p-6 mt-0">
        <view class="text-base font-bold text-[#1a1a1a] mb-1">员工认证</view>
        <view class="text-xs text-[#999] mb-6">输入姓名和手机号，系统自动匹配认证</view>
        <view class="mb-4">
          <text class="text-sm text-[#333] mb-1 block">姓名</text>
          <wd-input v-model="empForm.real_name" placeholder="请输入真实姓名" :maxlength="20" />
        </view>
        <view class="mb-6">
          <text class="text-sm text-[#333] mb-1 block">手机号</text>
          <wd-input v-model="empForm.phone" placeholder="请输入手机号" type="digit" :maxlength="11" />
        </view>
        <wd-button type="primary" size="large" block :loading="empLoading" @click="handleEmpSubmit">提交认证</wd-button>
      </view>
    </template>

    <!-- ====== 保安 ====== -->
    <template v-else>
      <!-- 已提交（待审核/已通过） -->
      <view v-if="myCert && myCert.status !== 2" class="bg-white rounded-xl p-6 mb-4">
        <view class="text-base font-bold mb-4">保安认证申请</view>
        <view class="text-sm text-[#333] mb-1">姓名：{{ myCert.real_name }}</view>
        <view class="text-sm text-[#333] mb-1">手机号：{{ myCert.phone }}</view>
        <view class="text-sm text-[#333] mb-3">状态：
          <text :class="myCert.status === 0 ? 'text-orange-500' : 'text-green-500'">
            {{ myCert.status === 0 ? '待审核' : '已通过' }}
          </text>
        </view>
        <view v-if="myCert.snapshot?.length" class="flex flex-wrap gap-2 mb-3">
          <image v-for="(url, idx) in myCert.snapshot" :key="idx" :src="url" class="w-20 h-20 rounded" mode="aspectFill" @click="uni.previewImage({ urls: myCert.snapshot, current: url })" />
        </view>
        <wd-button v-if="myCert.status === 0" type="warning" size="small" :loading="withdrawing" @click="handleWithdraw">撤回申请</wd-button>
        <wd-button v-else type="primary" size="small" @click="goBack">返回</wd-button>
      </view>

      <!-- 已拒绝 → 显示原因 + 重新申请 -->
      <!-- 表单（无申请/被拒绝后可重新提交） -->
      <view v-if="!myCert || myCert.status === 2" class="bg-white rounded-xl p-6">
        <view class="text-base font-bold text-[#1a1a1a] mb-1">保安认证</view>
        <view class="text-xs text-[#999] mb-6">提交证明材料，等待管理员审核</view>
        <view class="mb-4">
          <text class="text-sm text-[#333] mb-1 block">姓名</text>
          <wd-input v-model="guardForm.real_name" placeholder="请输入真实姓名" :maxlength="20" />
        </view>
        <view class="mb-4">
          <text class="text-sm text-[#333] mb-1 block">手机号</text>
          <wd-input v-model="guardForm.phone" placeholder="请输入手机号" type="digit" :maxlength="11" />
        </view>
        <view class="mb-6">
          <text class="text-sm text-[#333] mb-1 block">证明材料</text>
          <view class="flex flex-wrap gap-2">
            <view v-for="(url, idx) in guardForm.snapshot" :key="idx" class="relative">
              <image :src="url" class="w-20 h-20 rounded" mode="aspectFill" />
              <view class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full flex items-center justify-center text-white text-xs" @click="removeScreenshot(idx)">×</view>
            </view>
            <view v-if="guardForm.snapshot.length < 9" class="w-20 h-20 bg-gray-100 rounded flex items-center justify-center text-gray-400 text-2xl" @click="chooseScreenshots">+</view>
          </view>
        </view>
        <wd-button type="primary" size="large" block :loading="guardLoading" @click="handleGuardSubmit">提交申请</wd-button>
      </view>
    </template>
  </view>
</template>
