<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <div class="user-info" v-if="user">
      <el-avatar :src="user.avatar" :size="40">
        <el-icon><User /></el-icon>
      </el-avatar>
      <div class="user-detail">
        <div class="nickname">{{ user.nickname || '-' }}</div>
        <div class="uid">UID: {{ user.id }}</div>
      </div>
      <div class="current-balance">
        <span class="label">当前{{ typeLabel }}：</span>
        <span class="value">{{ currentValueDisplay }}</span>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="变动方向">
        <el-select v-model="queryParams.changeType" placeholder="全部" clearable style="width: 120px">
          <el-option label="增加" value="add" />
          <el-option label="减少" value="sub" />
        </el-select>
      </el-form-item>
      <el-form-item label="变动说明">
        <el-input v-model="queryParams.content" placeholder="关键字" clearable style="width: 150px" />
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
          @change="handleDateChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 流水列表 -->
    <el-table :data="detailList" v-loading="loading" border stripe max-height="400">
      <el-table-column prop="id" label="ID" width="80" />

      <el-table-column label="变动金额" width="120" align="right">
        <template #default="{ row }">
          <span :class="['change-money', row.changeMoney >= 0 ? 'positive' : 'negative']">
            {{ row.changeMoney >= 0 ? '+' : '' }}{{ formatValue(row.changeMoney) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="变动后余额" width="120" align="right">
        <template #default="{ row }">
          <span class="balance">{{ formatValue(row.money) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="变动说明" min-width="200" show-overflow-tooltip />

      <el-table-column prop="other" label="备注" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.other || '-' }}
        </template>
      </el-table-column>

      <el-table-column label="变动类型" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.changeMoney >= 0 ? 'success' : 'danger'" size="small">
            {{ row.changeMoney >= 0 ? '增加' : '减少' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="addtime" label="变动时间" width="170" />
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[20, 50, 100, 200]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="fetchData"
      @current-change="fetchData"
      class="pagination"
    />

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { User } from '@element-plus/icons-vue'
import {
  getUserMoneyDetail,
  getUserIntegralDetail,
  getUserMoney2Detail,
  type UserListItem,
  type MoneyDetailQuery,
  type MoneyDetailItem
} from '@/api/business/user'

interface Props {
  modelValue: boolean
  user: UserListItem | null
  type: 'money' | 'integral' | 'diamond'  // 流水类型
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const loading = ref(false)
const detailList = ref<MoneyDetailItem[]>([])
const total = ref(0)
const dateRange = ref<[string, string] | null>(null)

const queryParams = reactive<MoneyDetailQuery>({
  type: undefined,
  changeType: undefined,
  content: undefined,
  startTime: undefined,
  endTime: undefined,
  page: 1,
  pageSize: 50
})

// 类型标签
const typeLabel = computed(() => {
  const labels: Record<string, string> = {
    money: '钻石',
    integral: 'HH币',
    diamond: '哈尼券'
  }
  return labels[props.type] || '钻石'
})

// 对话框标题
const dialogTitle = computed(() => `${typeLabel.value}流水明细`)

// 当前值
const currentValue = computed(() => {
  if (!props.user) return 0
  const valueMap: Record<string, number> = {
    money: props.user.balance || 0,
    integral: props.user.integral || 0,
    diamond: props.user.diamond || 0
  }
  return valueMap[props.type] || 0
})

// 当前值显示
const currentValueDisplay = computed(() => {
  if (props.type === 'money') {
    return `¥${currentValue.value.toFixed(2)}`
  }
  return currentValue.value.toString()
})

// 格式化值
const formatValue = (value: number) => {
  if (props.type === 'money') {
    return `¥${value?.toFixed(2) || '0.00'}`
  }
  return value?.toString() || '0'
}

// 日期范围变化
const handleDateChange = (val: [string, string] | null) => {
  if (val) {
    queryParams.startTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.startTime = undefined
    queryParams.endTime = undefined
  }
}

// 获取数据
const fetchData = async () => {
  if (!props.user) return

  loading.value = true
  try {
    let res
    switch (props.type) {
      case 'money':
        res = await getUserMoneyDetail(props.user.id, queryParams)
        break
      case 'integral':
        res = await getUserIntegralDetail(props.user.id, queryParams)
        break
      case 'diamond':
        res = await getUserMoney2Detail(props.user.id, queryParams)
        break
      default:
        res = await getUserMoneyDetail(props.user.id, queryParams)
    }
    detailList.value = res.data?.list || []
    total.value = res.data?.total || 0
  } catch (error) {
    console.error('获取流水明细失败', error)
    detailList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  queryParams.type = undefined
  queryParams.changeType = undefined
  queryParams.content = undefined
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  dateRange.value = null
  queryParams.page = 1
  fetchData()
}

// 对话框打开时
const handleOpen = () => {
  handleReset()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 16px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.nickname {
  font-weight: 500;
  font-size: 14px;
}

.uid {
  font-size: 12px;
  color: #909399;
}

.current-balance {
  padding: 8px 16px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.current-balance .label {
  color: #606266;
}

.current-balance .value {
  color: #e6a23c;
  font-weight: 600;
  font-size: 16px;
}

.search-form {
  margin-bottom: 16px;
}

.change-money {
  font-weight: 500;
}

.change-money.positive {
  color: #67c23a;
}

.change-money.negative {
  color: #f56c6c;
}

.balance {
  color: #606266;
}

.pagination {
  margin-top: 16px;
  justify-content: flex-end;
}
</style>
