<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>

        <!-- PRD要求：用户详情操作按钮 -->
        <div class="border-t border-mosquito-line pt-4 space-y-2">
          <div class="text-sm font-semibold text-mosquito-ink">用户操作</div>
          <div class="flex flex-wrap gap-2">
            <!-- 冻结/解冻按钮 - 需要 freeze 或 unfreeze 权限 -->
            <button
              v-if="user?.status === '冻结' ? hasPermission('user.index.unfreeze.ALL') : hasPermission('user.index.freeze.ALL')"
              class="mos-btn !py-1 !px-2 !text-xs"
              :class="user?.status === '冻结' ? 'mos-btn-secondary' : 'mos-btn-secondary'"
              @click="toggleFreeze"
            >
              {{ user?.status === '冻结' ? '解冻' : '冻结' }}
            </button>
            <!-- 白名单按钮 - 需要 whitelist.add 或 whitelist.remove 权限 -->
            <button
              v-if="isInWhitelist ? hasPermission('user.whitelist.remove.ALL') : hasPermission('user.whitelist.add.ALL')"
              class="mos-btn !py-1 !px-2 !text-xs"
              :class="isInWhitelist ? 'mos-btn-primary' : 'mos-btn-secondary'"
              @click="toggleWhitelist"
            >
              {{ isInWhitelist ? '取消白名单' : '加入白名单' }}
            </button>
            <!-- 黑名单按钮 - 需要 user.index.update.ALL 权限 -->
            <button
              v-if="hasPermission('user.index.update.ALL')"
              class="mos-btn !py-1 !px-2 !text-xs"
              :class="isInBlacklist ? 'mos-btn-accent' : 'mos-btn-secondary'"
              @click="toggleBlacklist"
            >
              {{ isInBlacklist ? '取消黑名单' : '加入黑名单' }}
            </button>
            <!-- 积分调整按钮 - 需要 user.points.adjust.ALL 权限 -->
            <button
              v-if="hasPermission('user.points.adjust.ALL')"
              class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs"
              @click="showPointsModal = true"
            >
              积分调整
            </button>
            <!-- 投诉记录按钮 -->
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="openComplaintModal">
              投诉记录
            </button>
          </div>
        </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 v-for="opt in roleOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</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>

    <!-- 积分调整弹窗 -->
    <div v-if="showPointsModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="mos-card p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">积分调整</h3>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">调整类型</label>
            <select v-model="pointsAction" class="mos-input w-full">
              <option value="add">增加积分</option>
              <option value="subtract">扣减积分</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">积分数量</label>
            <input v-model.number="pointsAmount" type="number" class="mos-input w-full" placeholder="请输入积分数量" />
          </div>
          <div>
            <label class="block text-sm font-medium text-mosquito-ink mb-1">调整原因</label>
            <textarea v-model="pointsReason" class="mos-input w-full h-20" placeholder="请说明调整原因"></textarea>
          </div>
        </div>
        <div class="flex gap-3 mt-6">
          <button class="mos-btn mos-btn-primary flex-1" @click="confirmPointsAdjust">确认</button>
          <button class="mos-btn mos-btn-secondary flex-1" @click="showPointsModal = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 投诉记录弹窗 -->
    <div v-if="showComplaintModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="mos-card p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4">投诉记录</h3>
        <div class="space-y-3 max-h-64 overflow-y-auto">
          <div v-for="complaint in complaints" :key="complaint.id" class="rounded-lg border border-mosquito-line p-3 text-sm">
            <div class="font-medium">{{ complaint.title }}</div>
            <div class="text-xs text-mosquito-ink/70 mt-1">{{ complaint.content }}</div>
            <div class="text-xs text-mosquito-ink/50 mt-1">{{ complaint.time }}</div>
          </div>
          <div v-if="!complaints.length" class="text-center text-mosquito-ink/60 py-4">暂无投诉记录</div>
        </div>
        <div class="flex gap-3 mt-4">
          <button class="mos-btn mos-btn-primary flex-1" @click="addComplaint">添加投诉</button>
          <button class="mos-btn mos-btn-secondary flex-1" @click="showComplaintModal = false">关闭</button>
        </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'
import { usePermission } from '../composables/usePermission'
import { userService } from '../services/user'
import { RoleLabels, type AdminRole, type Permission } from '../auth/roles'

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

// 白名单/黑名单状态
const isInWhitelist = ref(false)
const isInBlacklist = ref(false)

// 积分调整弹窗
const showPointsModal = ref(false)
const pointsAction = ref('add')
const pointsAmount = ref(0)
const pointsReason = ref('')

// 投诉记录弹窗
const showComplaintModal = ref(false)
const complaints = ref<{ id: string; title: string; content: string; time: string }[]>([])

const toggleFreeze = async () => {
  if (!user.value) return
  try {
    const action = user.value.status === '冻结' ? '解冻' : '冻结'
    if (action === '冻结') {
      await userService.freezeUser(Number(user.value.id))
    } else {
      await userService.unfreezeUser(Number(user.value.id))
    }
    auditStore.addLog(`${action}用户`, user.value.name)
    // 刷新用户数据
    await store.fetchUsers()
  } catch (error) {
    console.error('Failed to toggle freeze:', error)
    alert((error instanceof Error ? error.message : '操作失败'))
  }
}

const toggleWhitelist = async () => {
  const adding = !isInWhitelist.value
  const previousState = isInWhitelist.value
  isInWhitelist.value = adding
  auditStore.addLog(adding ? '加入白名单' : '取消白名单', user.value?.name || '')
  try {
    if (adding) {
      await userService.addToWhitelist(Number(user.value!.id))
    } else {
      await userService.removeFromWhitelist(Number(user.value!.id))
    }
  } catch (error) {
    // 失败时回滚UI状态
    isInWhitelist.value = previousState
    console.error('白名单操作失败:', error)
    alert(error instanceof Error ? error.message : '白名单操作失败')
  }
}

const toggleBlacklist = async () => {
  const adding = !isInBlacklist.value
  const previousState = isInBlacklist.value
  isInBlacklist.value = adding
  auditStore.addLog(adding ? '加入黑名单' : '取消黑名单', user.value?.name || '')
  try {
    if (adding) {
      await userService.addToBlacklist(Number(user.value!.id))
    } else {
      await userService.removeFromBlacklist(Number(user.value!.id))
    }
  } catch (error) {
    // 失败时回滚UI状态
    isInBlacklist.value = previousState
    console.error('黑名单操作失败:', error)
    alert(error instanceof Error ? error.message : '黑名单操作失败')
  }
}

const confirmPointsAdjust = async () => {
  if (!user.value || pointsAmount.value <= 0) return
  try {
    // 转换动作：add为正数，reduce为负数
    const amount = pointsAction.value === 'add' ? pointsAmount.value : -pointsAmount.value
    const newPoints = await userService.adjustPoints(Number(user.value.id), amount, pointsReason.value)
    auditStore.addLog(
      `${pointsAction.value === 'add' ? '增加' : '扣减'}积分`,
      `${user.value.name}: ${pointsAmount.value}分 - ${pointsReason.value}，新积分: ${newPoints}`
    )
    showPointsModal.value = false
    pointsAmount.value = 0
    pointsReason.value = ''
  } catch (error) {
    console.error('Failed to adjust points:', error)
    alert((error instanceof Error ? error.message : '积分调整失败'))
  }
}

const addComplaint = async () => {
  const title = prompt('请输入投诉标题')
  if (!title) return
  const content = prompt('请输入投诉内容')
  if (!content) return

  try {
    await userService.addComplaint(Number(user.value!.id), { title, content })
    // 刷新投诉列表
    await loadComplaints()
    auditStore.addLog('添加投诉记录', `${user.value?.name}: ${title}`)
  } catch (error) {
    console.error('添加投诉记录失败:', error)
    alert(error instanceof Error ? error.message : '添加投诉记录失败')
  }
}

const loadComplaints = async () => {
  if (!user.value) return
  try {
    const data = await userService.getComplaints(Number(user.value.id))
    complaints.value = data.map((c: any) => ({
      id: c.id?.toString() || '',
      title: c.title || '',
      content: c.content || '',
      time: c.createdAt ? new Date(c.createdAt).toLocaleString('zh-CN') : ''
    }))
  } catch (error) {
    console.error('加载投诉记录失败:', error)
    complaints.value = []
  }
}

const openComplaintModal = async () => {
  await loadComplaints()
  showComplaintModal.value = true
}

const user = computed(() => store.byId(userId.value))
const history = computed(() => store.roleRequests.filter((item) => item.userId === userId.value))

// 角色选项（15个角色）
const roleOptions: { value: AdminRole; label: string }[] = [
  { value: 'super_admin', label: '超级管理员' },
  { value: 'system_admin', label: '系统管理员' },
  { value: 'operation_director', label: '运营总监' },
  { value: 'operation_manager', label: '运营经理' },
  { value: 'operation_specialist', label: '运营专员' },
  { value: 'marketing_director', label: '市场总监' },
  { value: 'marketing_manager', label: '市场经理' },
  { value: 'marketing_specialist', label: '市场专员' },
  { value: 'finance_manager', label: '财务经理' },
  { value: 'finance_specialist', label: '财务专员' },
  { value: 'risk_manager', label: '风控经理' },
  { value: 'risk_specialist', label: '风控专员' },
  { value: 'cs_manager', label: '客服主管' },
  { value: 'cs_agent', label: '客服专员' },
  { value: 'auditor', label: '审计员' },
  { value: 'viewer', label: '只读' }
]

const targetRole = ref<AdminRole>('operation_manager')
const reason = ref('')
const statusFilter = ref('')
const startDate = ref('')
const endDate = ref('')

const roleLabel = (role?: string) => {
  return RoleLabels[role as AdminRole] || role || '未知'
}

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>
