package shop.alien.storeplatform.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.OperationalActivityUpdateResultVo;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityDTO;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityVO;
import shop.alien.storeplatform.service.OperationalActivityService;

import java.util.Optional;

import static shop.alien.storeplatform.service.impl.OperationalActivityServiceImpl.failureReasonHolder;

/**
 * 运营活动管理控制器
 *
 * @author system
 * @since 2025-11-26
 */
@Slf4j
@Api(tags = {"商家端-运营活动管理"})
@ApiSort(10)
@CrossOrigin
@RestController
@RequestMapping("/operationalActivity")
@RequiredArgsConstructor
public class OperationalActivityController {

    private final OperationalActivityService activityService;

    @ApiOperation(value = "AI生成运营活动海报图片", notes = "仅调用 AI 生成横版/竖版图片 URL，不入库。uploadImgType 须为 2；入参与创建活动一致（活动名称、时间、规则、imgDescribe 等）。生成后请将返回的 activityTitleImg、activityDetailImg 中的 imgUrl 随创建接口一并提交。")
    @ApiOperationSupport(order = 1)
    @PostMapping("/generatePromotionImages")
    public R<StoreOperationalActivityDTO> generatePromotionImages(@RequestBody StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityController.generatePromotionImages: dto={}", dto);
        try {
            StoreOperationalActivityDTO result = activityService.generateActivityPromotionImages(dto);
            return R.data(result, "图片生成成功");
        } catch (Exception e) {
            log.error("OperationalActivityController.generatePromotionImages ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "创建运营活动（提交保存）", notes = "内容审核后入库；AI 生图请先发 /generatePromotionImages，再将返回的图片 URL 填入 dto 后调用本接口。支持配置优惠券和代金券作为奖励。")
    @ApiOperationSupport(order = 2)
    @PostMapping("/create")
    public R<String> createActivity(@RequestBody StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityController.createActivity: dto={}", dto);
        try {
            log.warn("用户输入的图片描述{}",dto.getImgDescribe());
            int result = activityService.createActivity(dto);
            if (1 == result) {
                return R.success("活动创建成功");
            } else if (2 == result) {
                try {
                    return R.fail("活动创建失败,原因:审核未通过"+
                            Optional.ofNullable(failureReasonHolder.get()));
                }finally {
                    failureReasonHolder.remove();
                }
            }else {
                return R.fail("活动创建失败");
            }
        } catch (Exception e) {
            log.error("OperationalActivityController.createActivity ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "更新运营活动", notes = "支持更新优惠券和代金券配置")
    @ApiOperationSupport(order = 3)
    @PostMapping("/update")
    public R<OperationalActivityUpdateResultVo> updateActivity(@RequestBody StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityController.updateActivity: dto={}", dto);
        try {
            int result = activityService.updateActivity(dto);
            if (result > 0) {
                StoreOperationalActivityVO vo = activityService.queryActivityById(dto.getId());
                Integer couponType = (vo != null) ? vo.getCouponType() : null;
                return R.data(new OperationalActivityUpdateResultVo("活动更新成功", couponType));
            }
            return R.fail("活动更新失败");
        } catch (Exception e) {
            log.error("OperationalActivityController.updateActivity ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("删除运营活动")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/delete")
    public R<String> deleteActivity(@RequestParam("id") Integer id) {
        log.info("OperationalActivityController.deleteActivity: id={}", id);
        try {
            int result = activityService.deleteActivity(id);
            if (result > 0) {
                return R.success("活动删除成功");
            }
            return R.fail("活动删除失败");
        } catch (Exception e) {
            log.error("OperationalActivityController.deleteActivity ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "根据ID获取活动详情", notes = "返回活动详细信息，包括优惠券和代金券的名称、ID、数量等信息")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/queryActivityById")
    public R<StoreOperationalActivityVO> queryActivityById(@RequestParam("id") Integer id) {
        log.info("OperationalActivityController.getActivityById: id={}", id);
        try {
            StoreOperationalActivityVO result = activityService.queryActivityById(id);
            return R.data(result);
        } catch (Exception e) {
            log.error("OperationalActivityController.getActivityById ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "根据商户ID获取活动列表", notes = "分页查询活动列表，返回活动基本信息、优惠券和代金券信息、活动图片等")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId", value = "商户ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/queryActivityList")
    public R<IPage<StoreOperationalActivityVO>> queryActivityList(@RequestBody StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityController.queryActivityList: storeId={}, status={}, activityName={}", dto.getStoreId(), dto.getStatus(), dto.getActivityName());
        try {
            if (dto.getStoreId() == null || dto.getStoreId() <= 0) {
                 return R.data(null, "暂无承载数据！！！");
            }
            IPage<StoreOperationalActivityVO> result = activityService.queryActivityList( dto.getStoreId(), dto.getStatus(), dto.getActivityType(), dto.getActivityName(), dto.getPageNum(), dto.getPageSize());
            return R.data(result);
        } catch (Exception e) {
            log.error("OperationalActivityController.qeryActivityList ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }


    @ApiOperation("启用/禁用活动")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "活动ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "status", value = "状态：0-禁用, 1-启用", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/updateStatus")
    public R<String> updateActivityStatus(
            @RequestParam("id") Integer id,
            @RequestParam("status") Integer status) {
        log.info("OperationalActivityController.updateActivityStatus: id={}, status={}", id, status);
        try {
            int result = activityService.updateActivityStatus(id, status);
            if (result > 0) {
                return R.success("状态更新成功");
            }
            return R.fail("状态更新失败");
        } catch (Exception e) {
            log.error("OperationalActivityController.updateActivityStatus ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("上传活动结果")
    @ApiOperationSupport(order = 8)
    @PostMapping("/uploadResult")
    public R<String> uploadActivityResult(@RequestBody StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityController.uploadActivityResult: dto={}", dto);
        try {
            int result = activityService.uploadActivityResult(dto);
            if (result > 0) {
                return R.success("活动结果上传成功");
            }
            return R.fail("活动结果上传失败");
        } catch (Exception e) {
            log.error("OperationalActivityController.uploadActivityResult ERROR: {}", e.getMessage(), e);
            return R.fail(e.getMessage());
        }
    }
}

