<template>
  <div class="page-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <UserSearchForm @search="handleSearch" @reset="handleReset" />

      <!-- 用户表格 -->
      <UserTable
        :data="userList"
        :loading="loading"
        :total="total"
        :page="queryParams.page"
        :page-size="queryParams.pageSize"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
        @command="handleCommand"
      />
    </el-card>

    <!-- 资金变动对话框 -->
    <MoneyChangeDialog
      v-model="moneyDialogVisible"
      :user="currentUser"
      :type="moneyDialogType"
      :action="moneyDialogAction"
      @success="fetchData"
    />

    <!-- 赠送优惠券对话框 -->
    <GiftCouponDialog
      v-model="giftCouponDialogVisible"
      :user="currentUser"
      @success="fetchData"
    />

    <!-- 赠送卡牌对话框 -->
    <GiftCardDialog
      v-model="giftCardDialogVisible"
      :user="currentUser"
      @success="fetchData"
    />

    <!-- 用户盒柜对话框 -->
    <UserBoxDialog
      v-model="userBoxDialogVisible"
      :user="currentUser"
    />

    <!-- 用户订单对话框 -->
    <UserOrderDialog
      v-model="userOrderDialogVisible"
      :user="currentUser"
    />

    <!-- 下级用户对话框 -->
    <UserTeamDialog
      v-model="userTeamDialogVisible"
      :user="currentUser"
    />

    <!-- 流水明细对话框 -->
    <MoneyDetailDialog
      v-model="moneyDetailDialogVisible"
      :user="currentUser"
      :type="moneyDetailType"
    />

    <!-- IP登录历史对话框 -->
    <IpLogDialog
      v-model="ipLogDialogVisible"
      :user="currentUser"
    />

    <!-- 绑定手机号对话框 -->
    <el-dialog v-model="bindMobileDialogVisible" title="绑定手机号" width="400px">
      <el-form :model="bindMobileForm" label-width="80px">
        <el-form-item label="手机号" required>
          <el-input v-model="bindMobileForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindMobileDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindMobileSubmit" :loading="bindMobileLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserSearchForm from './components/UserSearchForm.vue'
import UserTable from './components/UserTable.vue'
import MoneyChangeDialog from './components/MoneyChangeDialog.vue'
import GiftCouponDialog from './components/GiftCouponDialog.vue'
import GiftCardDialog from './components/GiftCardDialog.vue'
import UserBoxDialog from './components/UserBoxDialog.vue'
import UserOrderDialog from './components/UserOrderDialog.vue'
import UserTeamDialog from './components/UserTeamDialog.vue'
import MoneyDetailDialog from './components/MoneyDetailDialog.vue'
import IpLogDialog from './components/IpLogDialog.vue'
import {
  getUserList,
  setUserStatus,
  setTestAccount,
  clearMobile,
  clearWeChat,
  bindMobile,
  type UserListQuery,
  type UserListItem
} from '@/api/business/user'

// 列表数据
const loading = ref(false)
const userList = ref<UserListItem[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<UserListQuery>({
  page: 1,
  pageSize: 20
})

// 当前操作的用户
const currentUser = ref<UserListItem | null>(null)

// 资金变动对话框
const moneyDialogVisible = ref(false)
const moneyDialogType = ref<number>(1)
const moneyDialogAction = ref<'add' | 'sub'>('add')

// 赠送优惠券对话框
const giftCouponDialogVisible = ref(false)

// 赠送卡牌对话框
const giftCardDialogVisible = ref(false)

// 用户盒柜对话框
const userBoxDialogVisible = ref(false)

// 用户订单对话框
const userOrderDialogVisible = ref(false)

// 下级用户对话框
const userTeamDialogVisible = ref(false)

// 流水明细对话框
const moneyDetailDialogVisible = ref(false)
const moneyDetailType = ref<'money' | 'integral' | 'diamond'>('money')

// IP登录历史对话框
const ipLogDialogVisible = ref(false)

// 绑定手机号对话框
const bindMobileDialogVisible = ref(false)
const bindMobileLoading = ref(false)
const bindMobileForm = reactive({
  mobile: ''
})

// 获取用户列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getUserList(queryParams)
    userList.value = res.data.list
    total.value = res.data.total
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (params: Partial<UserListQuery>) => {
  // 先清除所有搜索参数，再合并新参数
  queryParams.userId = undefined
  queryParams.parentId = undefined
  queryParams.mobile = undefined
  queryParams.nickname = undefined
  queryParams.lastLoginIp = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  // 合并新的搜索参数
  Object.assign(queryParams, params)
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.userId = undefined
  queryParams.parentId = undefined
  queryParams.mobile = undefined
  queryParams.nickname = undefined
  queryParams.lastLoginIp = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  queryParams.page = 1
  fetchData()
}

// 分页
const handlePageChange = (page: number) => {
  queryParams.page = page
  fetchData()
}

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.page = 1
  fetchData()
}

// 处理操作命令
const handleCommand = async (command: string, row: UserListItem) => {
  currentUser.value = row

  // 资金变动
  if (command.startsWith('money:') || command.startsWith('integral:') || command.startsWith('diamond:')) {
    const [typeStr, action] = command.split(':')
    const typeMap: Record<string, number> = { money: 1, integral: 2, diamond: 3 }
    
    moneyDialogType.value = typeMap[typeStr]
    // change 命令默认为充值，弹窗内可切换
    moneyDialogAction.value = action === 'sub' ? 'sub' : 'add'
    moneyDialogVisible.value = true
    return
  }

  // 状态管理
  if (command === 'status:ban') {
    await handleBan(row)
    return
  }
  if (command === 'status:unban') {
    await handleUnban(row)
    return
  }
  if (command === 'status:test') {
    await handleSetTest(row)
    return
  }
  if (command === 'status:clearMobile') {
    await handleClearMobile(row)
    return
  }
  if (command === 'status:clearWechat') {
    await handleClearWechat(row)
    return
  }
  if (command === 'status:bindMobile') {
    bindMobileForm.mobile = ''
    bindMobileDialogVisible.value = true
    return
  }

  // 赠送功能
  if (command === 'gift:coupon') {
    giftCouponDialogVisible.value = true
    return
  }
  if (command === 'gift:card') {
    giftCardDialogVisible.value = true
    return
  }

  // 查看详情
  if (command === 'view:team') {
    userTeamDialogVisible.value = true
    return
  }
  if (command === 'view:box') {
    userBoxDialogVisible.value = true
    return
  }
  if (command === 'view:orders') {
    userOrderDialogVisible.value = true
    return
  }
  if (command === 'view:moneyDetail') {
    moneyDetailType.value = 'money'
    moneyDetailDialogVisible.value = true
    return
  }
  if (command === 'view:integralDetail') {
    moneyDetailType.value = 'integral'
    moneyDetailDialogVisible.value = true
    return
  }
  if (command === 'view:diamondDetail') {
    moneyDetailType.value = 'diamond'
    moneyDetailDialogVisible.value = true
    return
  }
  if (command === 'view:ipLogs') {
    ipLogDialogVisible.value = true
    return
  }
}

// 封号
const handleBan = async (row: UserListItem) => {
  try {
    await ElMessageBox.confirm(`确定要封禁用户 "${row.nickname || row.id}" 吗？`, '提示', { type: 'warning' })
    await setUserStatus(row.id, 0)
    ElMessage.success('封禁成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 解封
const handleUnban = async (row: UserListItem) => {
  try {
    await ElMessageBox.confirm(`确定要解封用户 "${row.nickname || row.id}" 吗？`, '提示', { type: 'warning' })
    await setUserStatus(row.id, 1)
    ElMessage.success('解封成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 设为测试账号
const handleSetTest = async (row: UserListItem) => {
  try {
    const isTest = row.isTest === 1 ? 0 : 1
    const action = isTest === 1 ? '设为测试账号' : '取消测试账号'
    await ElMessageBox.confirm(`确定要${action} "${row.nickname || row.id}" 吗？`, '提示', { type: 'warning' })
    await setTestAccount(row.id, isTest)
    ElMessage.success('操作成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 清空手机号
const handleClearMobile = async (row: UserListItem) => {
  try {
    await ElMessageBox.confirm(`确定要清空用户 "${row.nickname || row.id}" 的手机号吗？`, '提示', { type: 'warning' })
    await clearMobile(row.id)
    ElMessage.success('清空成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 重置微信登录
const handleClearWechat = async (row: UserListItem) => {
  try {
    await ElMessageBox.confirm(`确定要重置用户 "${row.nickname || row.id}" 的微信登录吗？`, '提示', { type: 'warning' })
    await clearWeChat(row.id)
    ElMessage.success('重置成功')
    fetchData()
  } catch {
    // 取消操作
  }
}

// 绑定手机号提交
const handleBindMobileSubmit = async () => {
  if (!currentUser.value) return
  if (!bindMobileForm.mobile) {
    ElMessage.warning('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(bindMobileForm.mobile)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }

  bindMobileLoading.value = true
  try {
    await bindMobile(currentUser.value.id, bindMobileForm.mobile)
    ElMessage.success('绑定成功')
    bindMobileDialogVisible.value = false
    fetchData()
  } finally {
    bindMobileLoading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
