package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.CouponTemplate;
import com.haha.entity.UserCoupon;
import com.haha.entity.dto.CouponCreateDTO;
import com.haha.entity.dto.CouponQueryDTO;
import com.haha.entity.dto.CouponDistributeDTO;
import com.haha.service.CouponTemplateService;
import com.haha.service.UserCouponService;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/marketing/coupon")
@RequiredArgsConstructor
public class CouponController {

    private final CouponTemplateService templateService;
    private final UserCouponService userCouponService;

    @RequirePermission("marketing:coupon:read")
    @GetMapping("/list")
    public Result<PageResult<CouponTemplate>> list(CouponQueryDTO queryDTO) {
        IPage<CouponTemplate> page = templateService.getPage(queryDTO);
        return Result.success("查询成功", PageResult.of(page));
    }

    @RequirePermission("marketing:coupon:read")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getById(@PathVariable Long id) {
        CouponTemplate template = templateService.getDetail(id);
        List<Long> shopIds = templateService.getCouponShopIds(id);
        List<Long> productIds = templateService.getCouponProductIds(id);

        Map<String, Object> result = new HashMap<>();
        result.put("template", template);
        result.put("shopIds", shopIds);
        result.put("productIds", productIds);

        return Result.success("查询成功", result);
    }

    @RequirePermission("marketing:coupon:create")
    @Log(module = "营销管理", operation = OperationType.INSERT, summary = "创建优惠券")
    @PostMapping
    public Result<CouponTemplate> create(@RequestBody CouponCreateDTO dto) {
        Long creatorId = StpUtil.getLoginIdAsLong();
        String creatorName = (String) StpUtil.getSession().get("name");

        CouponTemplate template = templateService.create(dto, creatorId, creatorName);
        return Result.success("创建成功", template);
    }

    @RequirePermission("marketing:coupon:edit")
    @Log(module = "营销管理", operation = OperationType.UPDATE, summary = "更新优惠券状态")
    @PutMapping("/{id}/status")
    public Result<String> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        templateService.updateStatus(id, status);
        return Result.success("更新成功");
    }

    @RequirePermission("marketing:coupon:delete")
    @Log(module = "营销管理", operation = OperationType.DELETE, summary = "删除优惠券")
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        templateService.deleteTemplate(id);
        return Result.success("删除成功");
    }

    @RequirePermission("marketing:coupon:distribute")
    @Log(module = "营销管理", operation = OperationType.INSERT, summary = "发放优惠券")
    @PostMapping("/distribute")
    public Result<String> distribute(@RequestBody CouponDistributeDTO dto) {
        log.info("发放优惠券请求: templateId={}, targetType={}, userIds={}", 
                dto.getTemplateId(), dto.getTargetType(), dto.getUserIds());
        
        Long operatorId = StpUtil.getLoginIdAsLong();
        String operatorName = (String) StpUtil.getSession().get("name");

        userCouponService.distributeCoupon(dto, operatorId, operatorName);
        return Result.success("发放成功");
    }

    @RequirePermission("marketing:coupon:read")
    @GetMapping("/{id}/statistics")
    public Result<Map<String, Object>> getStatistics(@PathVariable Long id) {
        Map<String, Object> stats = templateService.getStatistics(id);
        return Result.success("查询成功", stats);
    }

    @RequirePermission("marketing:coupon:read")
    @GetMapping("/available")
    public Result<List<CouponTemplate>> getAvailableTemplates() {
        List<CouponTemplate> templates = templateService.getAvailableTemplates();
        return Result.success("查询成功", templates);
    }

    @RequirePermission("marketing:coupon:read")
    @GetMapping("/user/list")
    public Result<PageResult<UserCoupon>> getUserCouponList(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String couponCode,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        IPage<UserCoupon> pageResult = userCouponService.getUserCouponList(userId, couponCode, status, page, pageSize);
        return Result.success("查询成功", PageResult.of(pageResult));
    }
}
