package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.storePlatform.vo.*;
import shop.alien.store.dto.StoreOperationalActivityAchievementDto;
import shop.alien.store.dto.StoreOperationalActivityCaseQueryDto;
import shop.alien.store.dto.StoreOperationalActivitySignupDto;
import shop.alien.store.service.StoreOperationalActivityAchievementService;
import shop.alien.store.service.StoreOperationalActivityService;

import java.util.List;

/**
 * 运营活动详情控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"用户端-运营活动详情"})
@ApiSort(11)
@CrossOrigin
@RestController
@RequestMapping("/storeOperationalActivity")
@RequiredArgsConstructor
public class StoreOperationalActivityController {

    private final StoreOperationalActivityService operationalActivityService;
    private final StoreOperationalActivityAchievementService achievementService;

    @ApiOperation(value = "查询活动详情", notes = "返回活动详细信息，包括优惠券和代金券的名称、ID、数量等信息")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @GetMapping("/detail")
    public R<StoreOperationalActivityDetailVo> getActivityDetail(@RequestParam("id") Integer id,
                                                                 @RequestParam("userId") Integer userId) {
        /*
         * 活动详情接口：
         * 1. id 与 userId 必传，分别用于活动查询与用户报名状态判断。
         * 2. 业务计算在服务层完成，控制器仅做参数透传与异常转换。
         */
        log.info("StoreOperationalActivityController.getActivityDetail id={}, userId={}", id, userId);
        try {
            StoreOperationalActivityDetailVo result = operationalActivityService.getActivityDetail(id, userId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.getActivityDetail ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "服务中台-查询活动详情", notes = "返回活动详细信息，包括优惠券和代金券的名称、ID、数量等信息")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @GetMapping("/platform/detail")
    public R<StoreOperationalActivityDetailVo> getActivityDetailForPlatform(@RequestParam("id") Integer id,
                                                                             @RequestParam("userId") Integer userId) {
        /*
         * 服务中台活动详情接口：
         * 1. id 与 userId 必传，分别用于活动查询与用户报名状态判断。
         * 2. 业务计算在服务层完成，控制器仅做参数透传与异常转换。
         */
        log.info("StoreOperationalActivityController.getActivityDetailForPlatform id={}, userId={}", id, userId);
        try {
            StoreOperationalActivityDetailVo result = operationalActivityService.getActivityDetailForPlatform(id, userId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.getActivityDetailForPlatform ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }


    @ApiOperation("报名校验（用户端）")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @GetMapping("/signup/check")
    public R<StoreOperationalActivitySignupCheckVo> checkSignup(@RequestParam("activityId") Integer activityId,
                                                                @RequestParam("userId") Integer userId) {
        log.info("StoreOperationalActivityController.checkSignup activityId={}, userId={}", activityId, userId);
        try {
            StoreOperationalActivitySignupCheckVo result = operationalActivityService.checkSignup(activityId, userId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.checkSignup ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("活动报名（用户端）")
    @ApiOperationSupport(order = 3)
    @PostMapping("/signup")
    public R<String> signup(@RequestBody StoreOperationalActivitySignupDto dto) {
        log.info("StoreOperationalActivityController.signup dto={}", dto);
        try {
            boolean result = operationalActivityService.signup(dto);
            return result ? R.success("你已成功参与，请耐心等待报名结果") : R.fail("报名失败");
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.signup ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("新增成果（用户端）")
    @ApiOperationSupport(order = 4)
    @PostMapping("/achievement/add")
    public R<String> addAchievement(@RequestBody StoreOperationalActivityAchievementDto dto) {
        log.info("StoreOperationalActivityController.addAchievement dto={}", dto);
        try {
            boolean result = achievementService.addAchievement(dto);
            return result ? R.success("新增成功") : R.fail("新增失败");
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.addAchievement ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("成果详情（用户端）")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParam(name = "id", value = "成果ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    @GetMapping("/achievement/detail")
    public R<StoreOperationalActivityAchievementVo> getAchievementDetail(@RequestParam("id") Integer id) {
        log.info("StoreOperationalActivityController.getAchievementDetail id={}", id);
        try {
            StoreOperationalActivityAchievementVo result = achievementService.getAchievementDetail(id);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.getAchievementDetail ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("成果列表（用户端）")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动ID", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "signupId", value = "报名ID", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataTypeClass = Integer.class, paramType = "query")
    })
    @GetMapping("/achievement/list")
    public R<IPage<StoreOperationalActivityAchievementVo>> listAchievements(
            @RequestParam(value = "activityId", required = false) Integer activityId,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "signupId", required = false) Integer signupId,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        log.info("StoreOperationalActivityController.listAchievements activityId={}, userId={}, signupId={}, pageNum={}, pageSize={}",
                activityId, userId, signupId, pageNum, pageSize);
        try {
            IPage<StoreOperationalActivityAchievementVo> result =
                    achievementService.listAchievements(activityId, userId, signupId, pageNum, pageSize);
            return R.data(result);
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.listAchievements ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("案例列表（用户端）")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "店铺ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "activityStatus", value = "活动状态", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataTypeClass = Integer.class, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataTypeClass = Integer.class, paramType = "query")
    })
    @GetMapping("/achievement/case/list")
    public R<IPage<StoreOperationalActivityAchievementCaseVo>> listCasePage(
            @RequestParam("storeId") Integer storeId,
            @RequestParam(value = "activityStatus", required = false) Integer activityStatus,
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        log.info("StoreOperationalActivityController.listCasePage storeId={}, activityStatus={}, pageNum={}, pageSize={}",
                storeId, activityStatus, pageNum, pageSize);
        try {
            IPage<StoreOperationalActivityAchievementCaseVo> result =
                    achievementService.listCasePage(storeId, activityStatus, pageNum, pageSize);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.listCasePage ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("案例卡片概览（用户端，列表默认一条，含总数）")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParam(name = "storeId", value = "店铺ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    @GetMapping("/achievement/case/preview")
    public R<StoreOperationalActivityCasePreviewVo> listCasePreview(@RequestParam("storeId") Integer storeId) {
        log.info("StoreOperationalActivityController.listCasePreview storeId={}", storeId);
        try {
            StoreOperationalActivityCasePreviewVo result = achievementService.listCasePreview(storeId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.listCasePreview ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("案例详情（用户端）")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @GetMapping("/achievement/case/detail")
    public R<StoreOperationalActivityAchievementCaseDetailVo> getCaseDetail(@RequestParam("activityId") Integer activityId,
                                                                            @RequestParam("userId") Integer userId) {
        log.info("StoreOperationalActivityController.getCaseDetail activityId={}, userId={}", activityId, userId);
        try {
            StoreOperationalActivityAchievementCaseDetailVo result =
                    achievementService.getCaseDetail(activityId, userId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.getCaseDetail ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("我的报名列表（用户端）")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    @GetMapping("/signup/my")
    public R<List<StoreOperationalActivityMySignupVo>> listMySignups(@RequestParam("userId") Integer userId) {
        /*
         * 我的报名列表接口：
         * 1. userId 必传，作为报名列表与状态计算的唯一依据。
         * 2. 由服务层负责聚合活动信息、报名审核状态、成果状态等字段。
         * 3. 接口仅做参数透传与异常转换，避免在控制器重复业务判断。
         */
        try {
            List<StoreOperationalActivityMySignupVo> result = operationalActivityService.listMySignups(userId);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.listMySignups ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("删除报名及成果（用户端）")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "signupId", value = "报名ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping("/signup/delete")
    public R<String> deleteSignup(@RequestParam("activityId") Integer activityId,
                                  @RequestParam("signupId") Integer signupId) {
        /*
         * 删除报名及成果接口：
         * 1. 入参为活动ID与报名ID，必须匹配同一条报名记录。
         * 2. 服务层校验报名是否存在且未删除。
         * 3. 同时逻辑删除报名与关联成果记录。
         */
        try {
            boolean result = operationalActivityService.deleteSignup(activityId, signupId);
            return result ? R.success("删除成功") : R.fail("删除失败");
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.deleteSignup ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("商家端案例列表")
    @ApiOperationSupport(order = 12)
    @PostMapping("/achievement/case/store/list")
    public R<IPage<StoreOperationalActivityAchievementCaseVo>> listStoreCasePage(
            @RequestBody StoreOperationalActivityCaseQueryDto dto) {
        log.info("StoreOperationalActivityController.listStoreCasePage dto={}", dto);
        try {
            if (dto == null || dto.getStoreId() == null || dto.getStoreId() <= 0) {
                return R.fail("商户ID不能为空");
            }
            IPage<StoreOperationalActivityAchievementCaseVo> result = achievementService.listStoreCasePage(
                    dto.getStoreId(), dto.getActivityStatus(), dto.getActivityName(), dto.getPageNum(), dto.getPageSize());
            return R.data(result);
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("StoreOperationalActivityController.listStoreCasePage ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }
}
