<template>
  <div class="promotion-management">
    <a-page-header title="推广管理" sub-title="管理推广活动和奖励">
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('promotion:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon><PlusOutlined /></template>
            新建活动
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="activities" tab="推广活动">
        <a-card>
          <div class="search-container">
            <a-form layout="inline" :model="searchForm">
              <a-form-item label="活动名称">
                <a-input v-model:value="searchForm.name" placeholder="输入活动名称" allow-clear />
              </a-form-item>
              
              <a-form-item label="状态">
                <a-select v-model:value="searchForm.status" placeholder="全部状态" style="width: 120px" allow-clear>
                  <a-select-option value="active">进行中</a-select-option>
                  <a-select-option value="upcoming">未开始</a-select-option>
                  <a-select-option value="ended">已结束</a-select-option>
                  <a-select-option value="paused">已暂停</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="活动时间">
                <a-range-picker v-model:value="searchForm.activityTime" :placeholder="['开始时间', '结束时间']" />
              </a-form-item>
              
              <a-form-item>
                <a-button type="primary" @click="handleSearch">
                  <template #icon><SearchOutlined /></template>
                  搜索
                </a-button>
                <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              </a-form-item>
            </a-form>
          </div>

          <a-table
            :columns="activityColumns"
            :data-source="activityList"
            :loading="loading"
            :pagination="pagination"
            :row-key="record => record.id"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
              </template>
              
              <template v-else-if="column.key === 'reward_type'">
                <span>{{ getRewardTypeText(record.reward_type) }}</span>
              </template>
              
              <template v-else-if="column.key === 'reward_amount'">
                <span v-if="record.reward_type === 'cash'">¥{{ record.reward_amount }}</span>
                <span v-else-if="record.reward_type === 'points'">{{ record.reward_amount }}积分</span>
                <span v-else-if="record.reward_type === 'coupon'">{{ record.reward_amount }}元券</span>
              </template>
              
              <template v-else-if="column.key === 'participants'">
                <a-progress
                  :percent="record.current_participants / record.max_participants * 100"
                  size="small"
                  :show-info="false"
                />
                <div style="font-size: 12px; text-align: center;">
                  {{ record.current_participants }}/{{ record.max_participants }}
                </div>
              </template>
              
              <template v-else-if="column.key === 'actions'">
                <a-space :size="8">
                  <a-button size="small" @click="handleViewActivity(record)">
                    <EyeOutlined />详情
                  </a-button>
                  
                  <a-button 
                    v-if="hasPermission('promotion:write')" 
                    size="small" 
                    @click="handleEditActivity(record)"
                  >
                    <EditOutlined />编辑
                  </a-button>
                  
                  <template v-if="record.status === 'active' && hasPermission('promotion:write')">
                    <a-button size="small" danger @click="handlePauseActivity(record)">
                      <PauseOutlined />暂停
                    </a-button>
                  </template>
                  
                  <template v-if="record.status === 'paused' && hasPermission('promotion:write')">
                    <a-button size="small" type="primary" @click="handleResumeActivity(record)">
                      <PlayCircleOutlined />继续
                    </a-button>
                  </template>
                  
                  <a-button 
                    v-if="hasPermission('promotion:write')" 
                    size="small" 
                    danger 
                    @click="handleDeleteActivity(record)"
                  >
                    <DeleteOutlined />删除
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="rewards" tab="奖励记录">
        <a-card>
          <div class="search-container">
            <a-form layout="inline" :model="rewardSearchForm">
              <a-form-item label="用户">
                <a-input v-model:value="rewardSearchForm.user" placeholder="用户名/手机号" allow-clear />
              </a-form-item>
              
              <a-form-item label="奖励类型">
                <a-select v-model:value="rewardSearchForm.reward_type" placeholder="全部类型" style="width: 120px" allow-clear>
                  <a-select-option value="cash">现金</a-select-option>
                  <a-select-option value="points">积分</a-select-option>
                  <a-select-option value="coupon">优惠券</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="状态">
                <a-select v-model:value="rewardSearchForm.status" placeholder="全部状态" style="width: 120px" allow-clear>
                  <a-select-option value="pending">待发放</a-select-option>
                  <a-select-option value="issued">已发放</a-select-option>
                  <a-select-option value="failed">发放失败</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item>
                <a-button type="primary" @click="handleRewardSearch">
                  <template #icon><SearchOutlined /></template>
                  搜索
                </a-button>
                <a-button style="margin-left: 8px" @click="handleRewardReset">重置</a-button>
              </a-form-item>
            </a-form>
          </div>

          <a-table
            :columns="rewardColumns"
            :data-source="rewardList"
            :loading="rewardLoading"
            :pagination="rewardPagination"
            :row-key="record => record.id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'reward_type'">
                <span>{{ getRewardTypeText(record.reward_type) }}</span>
              </template>
              
              <template v-else-if="column.key === 'reward_amount'">
                <span v-if="record.reward_type === 'cash'">¥{{ record.reward_amount }}</span>
                <span v-else-if="record.reward_type === 'points'">{{ record.reward_amount }}积分</span>
                <span v-else-if="record.reward_type === 'coupon'">{{ record.reward_amount }}元券</span>
              </template>
              
              <template v-else-if="column.key === 'status'">
                <a-tag :color="getRewardStatusColor(record.status)">{{ getRewardStatusText(record.status) }}</a-tag>
              </template>
              
              <template v-else-if="column.key === 'actions'">
                <a-space :size="8">
                  <template v-if="record.status === 'pending' && hasPermission('promotion:write')">
                    <a-button size="small" type="primary" @click="handleIssueReward(record)">
                      <CheckOutlined />发放
                    </a-button>
                  </template>
                  
                  <a-button size="small" @click="handleViewReward(record)">
                    <EyeOutlined />详情
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 创建/编辑推广活动模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="promotionFormRef"
        :model="currentActivity"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="活动名称" name="name">
          <a-input v-model:value="currentActivity.name" placeholder="请输入活动名称" />
        </a-form-item>
        
        <a-form-item label="活动描述" name="description">
          <a-textarea
            v-model:value="currentActivity.description"
            placeholder="请输入活动描述"
            :rows="3"
          />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="奖励类型" name="reward_type">
              <a-select v-model:value="currentActivity.reward_type" placeholder="请选择奖励类型">
                <a-select-option value="cash">现金</a-select-option>
                <a-select-option value="points">积分</a-select-option>
                <a-select-option value="coupon">优惠券</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="奖励金额" name="reward_amount">
              <a-input-number
                v-model:value="currentActivity.reward_amount"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="最大参与人数" name="max_participants">
              <a-input-number
                v-model:value="currentActivity.max_participants"
                :min="1"
                :max="10000"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="currentActivity.status" placeholder="请选择状态">
                <a-select-option value="active">进行中</a-select-option>
                <a-select-option value="upcoming">未开始</a-select-option>
                <a-select-option value="ended">已结束</a-select-option>
                <a-select-option value="paused">已暂停</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="活动时间" required>
          <a-range-picker
            v-model:value="activityTimeRange"
            format="YYYY-MM-DD HH:mm"
            show-time
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  ReloadOutlined,
  SearchOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  PauseOutlined,
  PlayCircleOutlined,
  CheckOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'

import { 
  getPromotionActivities, 
  deletePromotionActivity, 
  pausePromotionActivity, 
  resumePromotionActivity,
  getRewardRecords,
  issueReward,
  createPromotionActivity,
  updatePromotionActivity,
  getPromotionActivity
} from '@/api/promotion'
import type { PromotionActivity, RewardRecord } from '@/api/promotion'

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

interface SearchForm {
  name: string
  status: string
  activityTime: any[]
}

interface RewardSearchForm {
  user: string
  reward_type: string
  status: string
}

const activeTab = ref('activities')
const loading = ref(false)
const rewardLoading = ref(false)

const searchForm = reactive<SearchForm>({
  name: '',
  status: '',
  activityTime: []
})

const rewardSearchForm = reactive<RewardSearchForm>({
  user: '',
  reward_type: '',
  status: ''
})

const activityList = ref<PromotionActivity[]>([])
const rewardList = ref<RewardRecord[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const rewardPagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const activityColumns = [
  { title: '活动名称', dataIndex: 'name', key: 'name', width: 150 },
  { title: '奖励类型', key: 'reward_type', width: 100, align: 'center' },
  { title: '奖励金额', key: 'reward_amount', width: 100, align: 'center' },
  { title: '状态', key: 'status', width: 100, align: 'center' },
  { title: '活动时间', key: 'time', width: 200, 
    customRender: ({ record }: { record: PromotionActivity }) => 
      `${record.start_time} 至 ${record.end_time}`
  },
  { title: '参与人数', key: 'participants', width: 120, align: 'center' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 120 },
  { title: '操作', key: 'actions', width: 200, align: 'center' }
]

const rewardColumns = [
  { title: '用户', dataIndex: 'user_name', key: 'user_name', width: 100 },
  { title: '联系电话', dataIndex: 'user_phone', key: 'user_phone', width: 120 },
  { title: '活动名称', dataIndex: 'activity_name', key: 'activity_name', width: 150 },
  { title: '奖励类型', key: 'reward_type', width: 100, align: 'center' },
  { title: '奖励金额', key: 'reward_amount', width: 100, align: 'center' },
  { title: '状态', key: 'status', width: 100, align: 'center' },
  { title: '发放时间', dataIndex: 'issued_at', key: 'issued_at', width: 150 },
  { title: '申请时间', dataIndex: 'created_at', key: 'created_at', width: 150 },
  { title: '操作', key: 'actions', width: 120, align: 'center' }
]

const getStatusColor = (status: string) => {
  const colors = {
    active: 'green',
    upcoming: 'blue',
    ended: 'default',
    paused: 'orange'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    active: '进行中',
    upcoming: '未开始',
    ended: '已结束',
    paused: '已暂停'
  }
  return texts[status as keyof typeof texts] || '未知'
}

const getRewardTypeText = (type: string) => {
  const texts = {
    cash: '现金',
    points: '积分',
    coupon: '优惠券'
  }
  return texts[type as keyof typeof texts] || '未知'
}

const getRewardStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    issued: 'green',
    failed: 'red'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getRewardStatusText = (status: string) => {
  const texts = {
    pending: '待发放',
    issued: '已发放',
    failed: '发放失败'
  }
  return texts[status as keyof typeof texts] || '未知'
}

onMounted(() => {
  loadActivities()
  loadRewards()
})

const loadActivities = async () => {
  loading.value = true
  try {
    const response = await getPromotionActivities({
      page: pagination.current,
      pageSize: pagination.pageSize,
      name: searchForm.name,
      status: searchForm.status
    })
    
    activityList.value = response.data
    pagination.total = response.pagination?.total || 0
  } catch (error) {
    message.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const loadRewards = async () => {
  rewardLoading.value = true
  try {
    const response = await getRewardRecords({
      page: rewardPagination.current,
      pageSize: rewardPagination.pageSize,
      user: rewardSearchForm.user,
      reward_type: rewardSearchForm.reward_type,
      status: rewardSearchForm.status
    })
    
    rewardList.value = response.data
    rewardPagination.total = response.pagination?.total || 0
  } catch (error) {
    message.error('加载奖励记录失败')
  } finally {
    rewardLoading.value = false
  }
}

const handleTabChange = (key: string) => {
  if (key === 'activities') {
    loadActivities()
  } else if (key === 'rewards') {
    loadRewards()
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadActivities()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: '',
    activityTime: []
  })
  pagination.current = 1
  loadActivities()
}

const handleRewardSearch = () => {
  rewardPagination.current = 1
  loadRewards()
}

const handleRewardReset = () => {
  Object.assign(rewardSearchForm, {
    user: '',
    reward_type: '',
    status: ''
  })
  rewardPagination.current = 1
  loadRewards()
}

const handleRefresh = () => {
  if (activeTab.value === 'activities') {
    loadActivities()
  } else {
    loadRewards()
  }
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadActivities()
}

const handleViewActivity = (record: PromotionActivity) => {
  message.info(`查看活动: ${record.name}`)
}

const handleEditActivity = async (record: PromotionActivity) => {
  try {
    modalLoading.value = true
    modalTitle.value = '编辑活动'
    isEditing.value = true
    
    // 获取活动详情
    const response = await getPromotionActivity(record.id)
    currentActivity.value = response.data
    
    // 设置时间范围
    activityTimeRange.value = [
      new Date(response.data.start_time),
      new Date(response.data.end_time)
    ]
    
    modalVisible.value = true
  } catch (error) {
    message.error('获取活动详情失败')
  } finally {
    modalLoading.value = false
  }
}

const handlePauseActivity = async (record: PromotionActivity) => {
  Modal.confirm({
    title: '确认暂停',
    content: `确定要暂停活动 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        await pausePromotionActivity(record.id)
        message.success('活动已暂停')
        loadActivities()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleResumeActivity = async (record: PromotionActivity) => {
  Modal.confirm({
    title: '确认继续',
    content: `确定要继续活动 "${record.name}" 吗？`,
    onOk: async () => {
      try {
        await resumePromotionActivity(record.id)
        message.success('活动已继续')
        loadActivities()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleDeleteActivity = async (record: PromotionActivity) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除活动 "${record.name}" 吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        await deletePromotionActivity(record.id)
        message.success('活动已删除')
        loadActivities()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

const handleIssueReward = async (record: RewardRecord) => {
  Modal.confirm({
    title: '确认发放',
    content: `确定要发放奖励给用户 "${record.user_name}" 吗？`,
    onOk: async () => {
      try {
        await issueReward(record.id)
        message.success('奖励已发放')
        loadRewards()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleViewReward = (record: RewardRecord) => {
  message.info(`查看奖励记录: ${record.user_name}`)
}

const showCreateModal = () => {
  modalTitle.value = '新增活动'
  isEditing.value = false
  currentActivity.value = {
    reward_amount: 0,
    max_participants: 100,
    status: 'upcoming'
  }
  activityTimeRange.value = []
  modalVisible.value = true
}

const handleModalOk = () => {
  promotionFormRef.value
    ?.validate()
    .then(() => {
      // 检查时间范围是否已设置
      if (!activityTimeRange.value || activityTimeRange.value.length !== 2) {
        message.error('请选择活动时间')
        return
      }
      
      // 设置时间范围到当前活动数据
      currentActivity.value.start_time = activityTimeRange.value[0].toISOString()
      currentActivity.value.end_time = activityTimeRange.value[1].toISOString()
      
      if (isEditing.value) {
        handleUpdateActivity()
      } else {
        handleCreateActivity()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

const handleModalCancel = () => {
  modalVisible.value = false
  promotionFormRef.value?.resetFields()
}

const handleCreateActivity = async () => {
  try {
    modalLoading.value = true
    await createPromotionActivity(currentActivity.value)
    message.success('创建活动成功')
    modalVisible.value = false
    loadActivities()
  } catch (error) {
    message.error('创建活动失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdateActivity = async () => {
  try {
    modalLoading.value = true
    await updatePromotionActivity(currentActivity.value.id!, currentActivity.value)
    message.success('更新活动成功')
    modalVisible.value = false
    loadActivities()
  } catch (error) {
    message.error('更新活动失败')
  } finally {
    modalLoading.value = false
  }
}

</script>

<style scoped lang="less">
.promotion-management {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}
</style>