<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { useTokenStore } from '@/store/token'
import { useUserStore } from '@/store'
import { uploadImage, bindPhone, updateAvatar } from '@/api/appointment'
import type { ICertificationInfo } from '@/api/types/appointment'

definePage({
  style: { navigationBarTitleText: '个人中心' },
})

const tokenStore = useTokenStore()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const { isFormalEmployee } = storeToRefs(userStore)

// 编辑姓名
const showEditDialog = ref(false)
const editName = ref('')

function openEdit() {
  editName.value = userInfo.value.real_name || ''
  showEditDialog.value = true
}

async function saveName() {
  if (!editName.value.trim()) {
    uni.showToast({ title: '姓名不能为空', icon: 'none' })
    return
  }
  try {
    await userStore.updateUserInfo({ real_name: editName.value.trim() })
    showEditDialog.value = false
    uni.showToast({ title: '修改成功', icon: 'success' })
  } catch {
    uni.showToast({ title: '修改失败', icon: 'error' })
  }
}

// 微信头像选择
async function onChooseAvatar(e: any) {
  const { avatarUrl } = e.detail
  uni.showLoading({ title: '上传头像...' })
  try {
    const result = await uploadImage(avatarUrl)
    await updateAvatar(userInfo.value.id, result.url)
    userInfo.value.avatar_url = result.url
    uni.hideLoading()
    uni.showToast({ title: '头像更新成功', icon: 'success' })
  } catch (err: any) {
    uni.hideLoading()
    uni.showToast({ title: err.message || '头像上传失败', icon: 'none' })
  }
}

// 微信昵称输入
const showNicknameInput = ref(false)
const nicknameValue = ref('')

function openNicknameEdit() {
  nicknameValue.value = userInfo.value.nickname || ''
  showNicknameInput.value = true
}

async function onNicknameBlur(e: any) {
  const nickname = e.detail.value
  showNicknameInput.value = false
  if (!nickname || nickname === userInfo.value.nickname) return
  try {
    await userStore.updateUserInfo({ nickname })
    uni.showToast({ title: '昵称更新成功', icon: 'success' })
  } catch {
    uni.showToast({ title: '昵称更新失败', icon: 'error' })
  }
}

function handleLogin() {
  const redirectUrl = encodeURIComponent('/pages/me/me')
  uni.navigateTo({ url: `/pages/auth/login?redirect=${redirectUrl}` })
}

// ==================== 角色认证 ====================
const certification = computed(() => userStore.userInfo.certification)

function goCertApply() {
  uni.navigateTo({ url: '/subpackages/system/certification-apply' })
}

const certStatusText = computed(() => {
  if (!certification.value) return '未认证'
  const map: Record<number, string> = { 0: '待审核', 1: '已通过', 2: '已拒绝' }
  return map[certification.value.status] || '未认证'
})

// ==================== 手机号绑定 ====================
const showPhoneDialog = ref(false)
const bindingPhone = ref(false)

function handlePhoneTap() {
  if (!userInfo.value.phone) {
    showPhoneDialog.value = true
  }
}

async function onGetPhoneNumber(e: any) {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({ title: '请授权手机号', icon: 'none' })
    return
  }
  bindingPhone.value = true
  try {
    const loginRes = await uni.login()
    await bindPhone({
      code: loginRes.code!,
      encrypted_data: e.detail.encryptedData,
      iv: e.detail.iv,
    })
    await userStore.fetchUserInfo()
    showPhoneDialog.value = false
    uni.showToast({ title: '手机号绑定成功', icon: 'success' })
  } catch (err: any) {
    uni.showToast({ title: err.message || '手机号绑定失败', icon: 'error' })
  } finally {
    bindingPhone.value = false
  }
}

// ==================== 常用 ====================
function handleOpenSetting() {
  uni.openSetting({
    success: (res) => console.log('打开设置成功', res),
  })
}

function handleOpenPrivacy() {
  // #ifdef MP-WEIXIN
  wx.openPrivacyContract({
    success: () => console.log('打开隐私政策成功'),
    fail: (err) => {
      console.error('打开隐私政策失败:', err)
      uni.showToast({ title: '隐私政策加载失败', icon: 'none' })
    },
  })
  // #endif
}

onShow(async () => {
  if (tokenStore.hasLogin) {
    try {
      await userStore.fetchUserInfo()
    } catch (err) {
      console.error('获取用户信息失败:', err)
    }
  }
})
</script>

<template>
  <view class="min-h-screen bg-gray-50">

    <!-- ============ 未登录 ============ -->
    <view v-if="!tokenStore.hasLogin" class="flex flex-col items-center pt-20">
      <image src="/static/images/default-avatar.png" class="w-24 h-24 rounded-full" mode="aspectFill" />
      <text class="mt-5 text-lg font-bold text-gray-800" @click="handleLogin">立即登录</text>
      <text class="mt-1 text-sm text-gray-400">登录后享受更多服务</text>
    </view>

    <!-- ============ 已登录 ============ -->
    <template v-if="tokenStore.hasLogin">
      <!-- 头部：头像 + 信息 -->
      <view class="bg-gradient-to-b from-blue-500 to-blue-400 px-5 pt-12 pb-10">
        <view class="flex items-center gap-4">
          <button class="w-16 h-16 rounded-full overflow-hidden border-2 border-white/40 bg-transparent p-0 shrink-0" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image :src="userInfo.avatar_url || '/static/images/default-avatar.png'" class="w-full h-full" mode="aspectFill" />
          </button>
          <view class="flex-1">
            <text class="text-lg font-bold text-white">{{ userInfo.nickname || userInfo.real_name || '未设置昵称' }}</text>
            <view class="flex items-center gap-2 mt-1">
              <view class="rounded-full px-2.5 py-0.5 text-xs font-medium"
                :class="(userInfo.role || 'visitor') === 'employee' ? 'bg-green-200 text-green-800' : (userInfo.role || 'visitor') === 'guard' ? 'bg-yellow-200 text-yellow-800' : 'bg-white/30 text-white'">
                {{ userInfo.role_name || '访客' }}
              </view>
              <text v-if="isFormalEmployee && userInfo.department_name" class="text-xs text-white/80">{{ userInfo.department_name }}</text>
              <text v-if="isFormalEmployee && userInfo.position" class="text-xs text-white/80">{{ userInfo.position }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 信息卡片 -->
      <view class="-mt-4 mx-4 rounded-xl bg-white shadow-sm px-4 py-3">
        <view class="flex items-center justify-between py-3">
          <text class="text-sm text-gray-500">账号ID</text>
          <text class="text-sm text-gray-400">{{ userInfo.id || '' }}</text>
        </view>
        <view class="flex items-center justify-between py-3 border-b border-gray-50" @click="openNicknameEdit">
          <text class="text-sm text-gray-500">昵称</text>
          <view class="flex items-center gap-1">
            <text class="text-sm text-gray-800">{{ userInfo.nickname || '未设置' }}</text>
            
          </view>
        </view>
        <view class="flex items-center justify-between py-3 border-b border-gray-50" @click="openEdit">
          <text class="text-sm text-gray-500">姓名</text>
          <view class="flex items-center gap-1">
            <text class="text-sm text-gray-800">{{ userInfo.real_name || '未设置' }}</text>
            
          </view>
        </view>
        <view class="flex items-center justify-between py-3 border-b border-gray-50" @click="handlePhoneTap">
          <text class="text-sm text-gray-500">手机号</text>
          <view class="flex items-center gap-1">
            <text :class="userInfo.phone ? 'text-gray-800' : 'text-orange-500'" class="text-sm">{{ userInfo.phone || '未绑定' }}</text>
            
          </view>
        </view>
      </view>

      <!-- 角色认证（仅访客） -->
      <view v-if="userInfo.role === 'visitor'" class="mx-4 mt-3 rounded-xl bg-white shadow-sm">
        <view class="flex items-center justify-between px-4 py-3.5" @click="goCertApply">
          <view class="flex items-center gap-3">
            <view class="w-8 h-8 rounded-lg bg-blue-50 flex items-center justify-center">
              <text class="text-blue-500 text-sm">📜</text>
            </view>
            <text class="text-sm text-gray-800 font-medium">申请角色认证</text>
          </view>
          <view class="flex items-center gap-2">
            <text class="text-xs text-gray-400">{{ certStatusText }}</text>
            
          </view>
        </view>
      </view>
    </template>

    <!-- ============ 常用功能 ============ -->
    <view class="mx-4 mt-3 rounded-xl bg-white shadow-sm">
      <view class="px-4 py-3 border-b border-gray-50">
        <text class="text-xs text-gray-400 font-medium">常用功能</text>
      </view>
      <button class="w-full bg-transparent border-none p-0 m-0 text-left" open-type="contact">
        <view class="flex items-center gap-3 px-4 py-3.5 border-b border-gray-50">
          <view class="w-8 h-8 rounded-lg bg-green-50 flex items-center justify-center">
            <text class="text-green-500 text-sm">💬</text>
          </view>
          <text class="text-sm text-gray-800 flex-1">联系客服</text>
          
        </view>
      </button>
      <view class="flex items-center gap-3 px-4 py-3.5 border-b border-gray-50" @click="handleOpenSetting">
        <view class="w-8 h-8 rounded-lg bg-purple-50 flex items-center justify-center">
          <text class="text-purple-500 text-sm">⚙️</text>
        </view>
        <text class="text-sm text-gray-800 flex-1">权限管理</text>
        
      </view>
      <view class="flex items-center gap-3 px-4 py-3.5" @click="handleOpenPrivacy">
        <view class="w-8 h-8 rounded-lg bg-gray-50 flex items-center justify-center">
          <text class="text-gray-500 text-sm">📄</text>
        </view>
        <text class="text-sm text-gray-800 flex-1">隐私政策</text>
        
      </view>
    </view>

    <!-- ============ 弹窗 ============ -->

    <!-- 昵称 -->
    <wd-popup v-model="showNicknameInput" position="center" custom-style="width: 300px; border-radius: 12px; padding: 20px;">
      <view class="text-center"><text class="text-lg font-bold">设置昵称</text></view>
      <view class="mt-4">
        <input type="nickname" class="w-full rounded-lg border border-gray-200 px-3 py-2.5 text-center text-sm" placeholder="点击获取微信昵称" :value="nicknameValue" @blur="onNicknameBlur" @confirm="onNicknameBlur" />
      </view>
      <view class="mt-4 flex justify-center">
        <wd-button @click="showNicknameInput = false">取消</wd-button>
      </view>
    </wd-popup>

    <!-- 姓名 -->
    <wd-popup v-model="showEditDialog" position="center" custom-style="width: 300px; border-radius: 12px; padding: 20px;">
      <view class="text-center"><text class="text-lg font-bold">修改姓名</text></view>
      <view class="mt-4"><wd-input v-model="editName" placeholder="请输入真实姓名" clearable /></view>
      <view class="mt-4 flex justify-center gap-3">
        <wd-button @click="showEditDialog = false">取消</wd-button>
        <wd-button type="primary" @click="saveName">确定</wd-button>
      </view>
    </wd-popup>

    <!-- 手机号 -->
    <wd-popup v-model="showPhoneDialog" position="center" custom-style="width: 300px; border-radius: 12px; padding: 20px;">
      <view class="text-center"><text class="text-lg font-bold">绑定手机号</text></view>
      <view class="mt-2 text-sm text-gray-500 text-center">绑定手机号</view>
      <view class="mt-5 flex flex-col items-center gap-3">
        <button class="w-full bg-transparent border-none p-0 m-0" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
          <wd-button type="primary" size="large" :loading="bindingPhone" block>微信手机号一键获取</wd-button>
        </button>
        <wd-button plain @click="showPhoneDialog = false">暂不绑定</wd-button>
      </view>
    </wd-popup>

    <!-- 底部安全区 -->
    <view class="h-[env(safe-area-inset-bottom,16px)]" />

  </view>
</template>

<style lang="scss" scoped>
button {
  &::after { border: none; }
}
.contact-btn-style {
  width: 100%;
  background: transparent;
  border: none;
  padding: 0;
  margin: 0;
  line-height: inherit;
  text-align: left;
  display: block;
}
</style>

