<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`指定中奖配置 - ${goodsTitle}`"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增配置
      </el-button>
      <el-tooltip content="指定中奖功能允许将特定奖品指定给特定用户，只有该用户才能抽中该奖品">
        <el-icon class="help-icon"><QuestionFilled /></el-icon>
      </el-tooltip>
    </div>

    <!-- 配置列表 -->
    <el-table
      :data="configList"
      v-loading="loading"
      border
      stripe
      max-height="400px"
    >
      <!-- 奖品信息 -->
      <el-table-column label="奖品" min-width="200">
        <template #default="{ row }">
          <div class="prize-info">
            <el-image
              :src="row.goodsItemImgUrl"
              :preview-src-list="row.goodsItemImgUrl ? [row.goodsItemImgUrl] : []"
              fit="cover"
              style="width: 40px; height: 40px; border-radius: 4px;"
              preview-teleported
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <span class="prize-title">{{ row.goodsItemTitle || '-' }}</span>
          </div>
        </template>
      </el-table-column>

      <!-- 指定用户 -->
      <el-table-column label="指定用户" min-width="180">
        <template #default="{ row }">
          <div class="user-info">
            <div>{{ row.userNickname || '未知用户' }}</div>
            <div class="text-muted">{{ row.userPhone || '-' }}</div>
          </div>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.isActive"
            @change="(val: boolean) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>

      <!-- 备注 -->
      <el-table-column prop="remark" label="备注" min-width="120">
        <template #default="{ row }">
          <span class="text-muted">{{ row.remark || '-' }}</span>
        </template>
      </el-table-column>

      <!-- 创建时间 -->
      <el-table-column label="创建时间" width="160" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="120" fixed="right" align="center">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-if="!loading && configList.length === 0" description="暂无指定中奖配置" />

    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑指定中奖配置' : '新增指定中奖配置'"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="选择奖品" prop="goodsItemId" v-if="!isEdit">
          <el-select
            v-model="formData.goodsItemId"
            placeholder="请选择奖品"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="prize in availablePrizes"
              :key="prize.id"
              :label="prize.title"
              :value="prize.id"
            >
              <div class="prize-option">
                <el-image
                  :src="prize.imgUrl"
                  fit="cover"
                  style="width: 24px; height: 24px; border-radius: 2px; margin-right: 8px;"
                />
                <span>{{ prize.title }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="奖品" v-else>
          <span>{{ currentConfig?.goodsItemTitle || '-' }}</span>
        </el-form-item>

        <el-form-item label="选择用户" prop="userId">
          <el-select
            v-model="formData.userId"
            placeholder="输入用户ID/手机号/昵称搜索"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            style="width: 100%"
            @change="handleUserChange"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.nickname || '未知'} (ID:${user.id})`"
              :value="user.id"
            >
              <div class="user-option">
                <el-avatar :src="user.avatar || ''" :size="24">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <div class="user-option-info">
                  <span class="user-option-name">{{ user.nickname || '未知用户' }}</span>
                  <span class="user-option-detail">ID:{{ user.id }} | {{ user.mobile || '未绑定手机' }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用" prop="isActive" v-if="isEdit">
          <el-switch v-model="formData.isActive" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>


<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete, Picture, QuestionFilled, User } from '@element-plus/icons-vue'
import {
  getDesignatedPrizes,
  createDesignatedPrize,
  updateDesignatedPrize,
  deleteDesignatedPrize,
  type DesignatedPrizeItem,
  type CreateDesignatedPrizeRequest,
  type UpdateDesignatedPrizeRequest
} from '@/api/business/designatedPrize'
import { getGoodsPrizes, type PrizeItem } from '@/api/business/goods'
import { getUserList, type UserListItem } from '@/api/business/user'
import { formatDateTime } from '@/utils/format'

interface Props {
  modelValue: boolean
  goodsId: number
  goodsTitle: string
}

const props = defineProps<Props>()

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

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

// 状态
const loading = ref(false)
const configList = ref<DesignatedPrizeItem[]>([])
const prizeList = ref<PrizeItem[]>([])
const formDialogVisible = ref(false)
const isEdit = ref(false)
const currentConfig = ref<DesignatedPrizeItem | null>(null)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 用户搜索相关
const userSearchLoading = ref(false)
const userOptions = ref<UserListItem[]>([])
const selectedUser = ref<UserListItem | null>(null)

// 表单数据
const formData = reactive({
  goodsItemId: undefined as number | undefined,
  userId: undefined as number | undefined,
  isActive: true,
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  goodsItemId: [
    { required: true, message: '请选择奖品', trigger: 'change' }
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', min: 1, message: '用户ID必须大于0', trigger: 'blur' }
  ]
}

// 可选奖品列表（排除已配置的）
const availablePrizes = computed(() => {
  const configuredPrizeIds = new Set(configList.value.map(c => c.goodsItemId))
  return prizeList.value.filter(p => !configuredPrizeIds.has(p.id))
})

// 获取配置列表
const fetchConfigs = async () => {
  if (!props.goodsId) return
  
  loading.value = true
  try {
    const res = await getDesignatedPrizes(props.goodsId)
    configList.value = res.data || []
  } catch (error: any) {
    ElMessage.error(error.message || '获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 获取奖品列表
const fetchPrizes = async () => {
  if (!props.goodsId) return
  
  try {
    const res = await getGoodsPrizes(props.goodsId)
    prizeList.value = res.data || []
  } catch (error: any) {
    console.error('获取奖品列表失败:', error)
  }
}

// 搜索用户
const searchUsers = async (query: string) => {
  if (!query || query.length < 1) {
    userOptions.value = []
    return
  }
  
  userSearchLoading.value = true
  try {
    const res = await getUserList({
      keyword: query,
      page: 1,
      pageSize: 20
    })
    userOptions.value = res.data?.list || []
  } catch (error: any) {
    console.error('搜索用户失败:', error)
    userOptions.value = []
  } finally {
    userSearchLoading.value = false
  }
}

// 用户选择变更
const handleUserChange = (userId: number) => {
  selectedUser.value = userOptions.value.find(u => u.id === userId) || null
}

// 新增配置
const handleAdd = () => {
  isEdit.value = false
  currentConfig.value = null
  resetForm()
  formDialogVisible.value = true
}

// 编辑配置
const handleEdit = (row: DesignatedPrizeItem) => {
  isEdit.value = true
  currentConfig.value = row
  formData.goodsItemId = row.goodsItemId
  formData.userId = row.userId
  formData.isActive = row.isActive
  formData.remark = row.remark || ''
  formDialogVisible.value = true
}

// 删除配置
const handleDelete = async (row: DesignatedPrizeItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除奖品 "${row.goodsItemTitle}" 的指定中奖配置吗？`,
      '删除确认',
      { type: 'warning' }
    )
    await deleteDesignatedPrize(props.goodsId, row.id)
    ElMessage.success('删除成功')
    fetchConfigs()
  } catch {
    // 取消操作
  }
}

// 状态变更
const handleStatusChange = async (row: DesignatedPrizeItem, isActive: boolean) => {
  try {
    await updateDesignatedPrize(props.goodsId, row.id, { isActive })
    ElMessage.success(isActive ? '已启用' : '已禁用')
  } catch (error: any) {
    row.isActive = !isActive // 回滚
    ElMessage.error(error.message || '状态更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  
  submitting.value = true
  try {
    if (isEdit.value && currentConfig.value) {
      const updateData: UpdateDesignatedPrizeRequest = {
        userId: formData.userId,
        isActive: formData.isActive,
        remark: formData.remark || undefined
      }
      await updateDesignatedPrize(props.goodsId, currentConfig.value.id, updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateDesignatedPrizeRequest = {
        goodsItemId: formData.goodsItemId!,
        userId: formData.userId!,
        remark: formData.remark || undefined
      }
      await createDesignatedPrize(props.goodsId, createData)
      ElMessage.success('创建成功')
    }
    formDialogVisible.value = false
    fetchConfigs()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.goodsItemId = undefined
  formData.userId = undefined
  formData.isActive = true
  formData.remark = ''
  userOptions.value = []
  selectedUser.value = null
  formRef.value?.resetFields()
}

// 打开弹窗
const handleOpen = () => {
  fetchConfigs()
  fetchPrizes()
}

// 关闭弹窗
const handleClose = () => {
  configList.value = []
  prizeList.value = []
  emit('update:modelValue', false)
}
</script>

<style scoped>
.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 16px;
}

.help-icon {
  color: #909399;
  cursor: help;
}

.prize-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.prize-title {
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-info {
  line-height: 1.6;
}

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

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  background: #f5f7fa;
  color: #909399;
}

.prize-option {
  display: flex;
  align-items: center;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.user-option-info {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.user-option-name {
  font-weight: 500;
}

.user-option-detail {
  font-size: 12px;
  color: #909399;
}
</style>
