package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhentao.common.Result;
import com.zhentao.entity.Activity;
import com.zhentao.entity.ActivityRegistration;
import com.zhentao.mapper.ActivityMapper;
import com.zhentao.service.ActivityRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 活动管理控制器
 */
@RestController
@RequestMapping("/admin/activity")
@CrossOrigin(origins = "*")
public class ActivityController {
    
    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityRegistrationService activityRegistrationService;
    
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    /**
     * 创建活动
     */
    @PostMapping("/create")
    public Result<String> create(@RequestBody Activity activity) {
        try {
            System.out.println("=== 创建活动 ===");
            System.out.println("活动数据: " + activity);
            
            // 处理时间字符串（如果是字符串格式）
            processDateFields(activity);
            
            // 设置默认值
            if (activity.getActualParticipants() == null) {
                activity.setActualParticipants(0);
            }
            if (activity.getIsHot() == null) {
                activity.setIsHot(false);
            }
            activity.setCreatedTime(LocalDateTime.now());
            
            int rows = activityMapper.insert(activity);
            if (rows > 0) {
                System.out.println("✅ 活动创建成功，ID: " + activity.getId());
                return Result.success("创建成功");
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建活动失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新活动
     */
    @PutMapping("/update/{id}")
    public Result<String> update(@PathVariable Integer id, @RequestBody Activity activity) {
        try {
            System.out.println("=== 更新活动 ===");
            System.out.println("活动ID: " + id);
            System.out.println("活动数据: " + activity);
            
            // 检查活动是否存在
            Activity existingActivity = activityMapper.selectById(id);
            if (existingActivity == null) {
                return Result.error("活动不存在");
            }
            
            // 处理时间字段
            processDateFields(activity);
            
            // 设置ID
            activity.setId(id);
            
            // 保留创建时间
            activity.setCreatedTime(existingActivity.getCreatedTime());
            
            int rows = activityMapper.updateById(activity);
            if (rows > 0) {
                System.out.println("✅ 活动更新成功");
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新活动失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除活动
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Integer id) {
        try {
            int rows = activityMapper.deleteById(id);
            if (rows > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("活动不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除活动失败：" + e.getMessage());
        }
    }


    /**
     * 取消报名
     */
    @DeleteMapping("/cancel-registration")
    public Result<String> cancelRegistration(
            @RequestParam("activityId") Integer activityId,
            @RequestParam("userId") Integer userId
    ) {
        try {
            if (activityId == null || userId == null) {
                return Result.error("activityId和userId不能为空");
            }

            LambdaQueryWrapper<ActivityRegistration> queryWrapper = new LambdaQueryWrapper<ActivityRegistration>()
                    .eq(ActivityRegistration::getActivityId, activityId)
                    .eq(ActivityRegistration::getUserId, userId)
                    .orderByDesc(ActivityRegistration::getRegistrationTime)
                    .last("LIMIT 1");

            ActivityRegistration registration = activityRegistrationService.getOne(queryWrapper, false);
            if (registration == null) {
                return Result.error("报名记录不存在");
            }
            if (registration.getStatus() != null && registration.getStatus() == 2) {
                return Result.success("取消报名成功");
            }
            if (registration.getStatus() != null && registration.getStatus() == 3) {
                return Result.error("已签到，无法取消报名");
            }

            registration.setStatus(2);
            registration.setUpdatedTime(LocalDateTime.now());
            boolean updated = activityRegistrationService.updateById(registration);
            if (!updated) {
                return Result.error("取消报名失败");
            }

            UpdateWrapper<Activity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", activityId);
            updateWrapper.gt("actual_participants", 0);
            updateWrapper.setSql("actual_participants = actual_participants - 1");
            activityMapper.update(null, updateWrapper);

            return Result.success("取消报名成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("取消报名失败：" + e.getMessage());
        }
    }
    
    
    /**
     * 获取活动统计
     */
    @GetMapping("/stats/{id}")
    public Result<?> getStats(@PathVariable Integer id) {
        try {
            // TODO: 实现获取活动统计的逻辑
            return Result.success("功能开发中");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取活动统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 处理日期字段（支持字符串转LocalDateTime）
     */
    private void processDateFields(Activity activity) {
        // 时间字段由前端传入时已经是正确格式，这里只做兼容性处理
        // 如果需要额外的时间处理逻辑，可以在这里添加
    }
}

