<template>
  <section class="space-y-6">
    <header class="space-y-2">
      <h1 class="mos-title text-2xl font-semibold">用户详情</h1>
      <p class="mos-muted text-sm">{{ user?.name }} · {{ user?.email }}</p>
    </header>

    <div class="grid gap-6 lg:grid-cols-3">
      <div class="mos-card p-5 space-y-3">
        <div class="text-sm font-semibold text-mosquito-ink">基本信息</div>
        <div class="text-xs text-mosquito-ink/70">角色：{{ roleLabel(user?.role) }}</div>
        <div class="text-xs text-mosquito-ink/70">状态：{{ user?.status }}</div>
        <div class="text-xs text-mosquito-ink/70">直属上级：{{ user?.managerName }}</div>
      </div>

      <div class="mos-card lg:col-span-2 p-5 space-y-4">
        <div class="text-sm font-semibold text-mosquito-ink">角色变更历史</div>
        <div class="flex flex-wrap items-center gap-2 text-xs text-mosquito-ink/70">
          <select class="mos-input !py-1 !px-2 !text-xs" v-model="statusFilter">
            <option value="">全部状态</option>
            <option value="待审批">待审批</option>
            <option value="已通过">已通过</option>
            <option value="已拒绝">已拒绝</option>
          </select>
          <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="startDate" />
          <input class="mos-input !py-1 !px-2 !text-xs" type="date" v-model="endDate" />
        </div>
        <div v-if="filteredHistory.length" class="mt-4 space-y-3">
          <div v-for="item in filteredHistory" :key="item.id" class="rounded-xl border border-mosquito-line px-4 py-3 text-xs">
            <div class="font-semibold">{{ roleLabel(item.currentRole) }} → {{ roleLabel(item.targetRole) }}</div>
            <div class="mos-muted">状态：{{ item.status }} · 申请时间：{{ formatDate(item.requestedAt) }}</div>
            <div v-if="item.status !== '待审批'" class="mos-muted">审批人：{{ item.approvedBy }} · {{ formatDate(item.decisionAt) }}</div>
            <div v-if="item.rejectReason" class="mos-muted">拒绝原因：{{ item.rejectReason }}</div>
          </div>
        </div>
        <div v-else class="mt-4 text-sm text-mosquito-ink/60">暂无变更记录</div>

        <div class="border-t border-mosquito-line pt-4">
          <div class="text-sm font-semibold text-mosquito-ink">发起角色变更申请</div>
          <div class="mt-3 flex flex-wrap items-center gap-2">
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="targetRole">
              <option value="admin">管理员</option>
              <option value="operator">运营</option>
              <option value="viewer">只读</option>
            </select>
            <input class="mos-input !py-1 !px-2 !text-xs w-56" v-model="reason" placeholder="填写申请原因" />
            <button class="mos-btn mos-btn-accent !py-1 !px-2 !text-xs" @click="submitRequest">提交申请</button>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '../stores/users'
import { useAuditStore } from '../stores/audit'

const route = useRoute()
const store = useUserStore()
const auditStore = useAuditStore()
const userId = computed(() => String(route.params.id))

const user = computed(() => store.byId(userId.value))
const history = computed(() => store.roleRequests.filter((item) => item.userId === userId.value))
const targetRole = ref('operator')
const reason = ref('')
const statusFilter = ref('')
const startDate = ref('')
const endDate = ref('')

const roleLabel = (role?: string) => {
  if (role === 'admin') return '管理员'
  if (role === 'operator') return '运营'
  return '只读'
}

const formatDate = (value?: string) => (value ? new Date(value).toLocaleString('zh-CN') : '--')

const filteredHistory = computed(() => {
  return history.value.filter((item) => {
    const matchesStatus = statusFilter.value ? item.status === statusFilter.value : true
    const startOk = startDate.value ? new Date(item.requestedAt).getTime() >= new Date(startDate.value).getTime() : true
    const endOk = endDate.value ? new Date(item.requestedAt).getTime() <= new Date(endDate.value).getTime() : true
    return matchesStatus && startOk && endOk
  })
})

const submitRequest = () => {
  if (!user.value) return
  store.requestRoleChange(user.value.id, targetRole.value as any, reason.value || '未填写原因')
  auditStore.addLog('提交角色变更申请', user.value.name)
  reason.value = ''
}
</script>
