package com.starry.admin.modules.shop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.IPlayCustomUserInfoService;
import com.starry.admin.modules.shop.module.entity.PlayCouponInfoEntity;
import com.starry.admin.modules.shop.module.enums.CouponObtainChannel;
import com.starry.admin.modules.shop.module.vo.*;
import com.starry.admin.modules.shop.service.IPlayCouponInfoService;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import com.starry.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 优惠券信息Controller
 *
 * @author admin
 * @since 2024-07-04
 */
@Api(tags = "优惠券管理", description = "优惠券信息管理相关接口，包括查询、新增、修改、发放和删除等操作")
@RestController
@RequestMapping("/shop/coupon")
public class PlayCouponInfoController {
    @Resource
    private IPlayCouponInfoService playCouponInfoService;

    @Resource
    private IPlayCustomUserInfoService playCustomUserInfoService;

    /**
     * 查询优惠券信息列表
     */
    @ApiOperation(value = "分页查询优惠券列表", notes = "分页查询优惠券信息列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功", response = PlayCouponInfoReturnVo.class, responseContainer = "Page")})
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:list')")
    @PostMapping("/listByPage")
    public R list(@ApiParam(value = "查询条件") PlayCouponInfoQueryVo vo) {
        IPage<PlayCouponInfoReturnVo> list = playCouponInfoService.selectByPage(vo);
        return R.ok(list);
    }

    /**
     * 修改优惠券上下架状态
     *
     * @param vo 优惠券上下架对象
     */
    @ApiOperation(value = "更新优惠券上下架状态", notes = "修改优惠券上下架状态")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "更新失败，包含详细错误信息")})
    @PostMapping("/updateOnLineState")
    public R updateOnLineState(
            @ApiParam(value = "状态更新信息", required = true) @Validated @RequestBody PlayCouponInfoOnLineStateUpdateVo vo) {
        playCouponInfoService.selectPlayCouponInfoById(vo.getId());
        PlayCouponInfoEntity entity = new PlayCouponInfoEntity();
        entity.setId(vo.getId());
        entity.setCouponOnLineState(vo.getCouponOnLineState());
        playCouponInfoService.update(entity);
        return R.ok();
    }

    /**
     * 发放优惠券
     *
     * @param vo 优惠券发放对象
     */
    @ApiOperation(value = "发放优惠券", notes = "向指定用户发放优惠券")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "发放失败，包含详细错误信息")})
    @PostMapping("/sendCoupon")
    public R sendCoupon(@ApiParam(value = "优惠券发放信息", required = true) @Validated @RequestBody PlayCouponInfoSendVo vo) {
        PlayCustomUserInfoEntity customUserInfo = playCustomUserInfoService.selectById(vo.getCustomId());
        for (int i = 0; i < vo.getSendNumber(); i++) {
            playCouponInfoService.claimCouponForCustom(
                    vo.getId(), customUserInfo, CouponObtainChannel.BACKEND_GRANT);
        }
        return R.ok();
    }

    /**
     * 获取优惠券信息详细信息
     */
    @ApiOperation(value = "获取优惠券详情", notes = "根据ID获取优惠券详细信息")
    @ApiImplicitParam(name = "id", value = "优惠券ID", required = true, paramType = "path", dataType = "String", example = "1")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = PlayCouponInfoEntity.class)})
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playCouponInfoService.selectPlayCouponInfoById(id));
    }

    /**
     * 新增优惠券信息
     */
    @ApiOperation(value = "新增优惠券", notes = "新增优惠券信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "添加失败，包含详细错误信息")})
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:create')")
    @Log(title = "优惠券信息", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@ApiParam(value = "优惠券信息", required = true) @Validated @RequestBody PlayCouponInfoAddVo vo) {
        PlayCouponInfoEntity entity = ConvertUtil.entityToVo(vo, PlayCouponInfoEntity.class);
        if ("1".equals(vo.getValidityPeriodType())) {
            if (vo.getProductiveTime() == null || vo.getProductiveTime().size() != 2) {
                throw new CustomException("用券时间输入错误");
            }
            LocalDateTime startTime = LocalDateTime.parse(vo.getProductiveTime().get(0),
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime endTime = LocalDateTime.parse(vo.getProductiveTime().get(1),
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            if (endTime.isBefore(startTime)) {
                throw new CustomException("用券时间输入错误，结束时间大于开始时间");
            }
            entity.setProductiveTime(startTime);
            entity.setExpirationTime(endTime);
        }
        if ("2".equals(vo.getValidityPeriodType()) && vo.getEffectiveDay() <= 0) {
            throw new CustomException("用券时间输入错误，有效天数不能为0");
        }

        boolean unlimitedInventory = "1".equals(vo.getCouponQuantityType());
        if (unlimitedInventory) {
            entity.setCouponQuantity(null);
            entity.setRemainingQuantity(null);
        } else {
            Integer totalQuantity = vo.getCouponQuantity();
            if (totalQuantity == null || totalQuantity <= 0) {
                throw new CustomException("优惠券总数必须大于0");
            }
            entity.setCouponQuantity(totalQuantity);
            entity.setRemainingQuantity(totalQuantity);
        }

        boolean unlimitedPerUser = "1".equals(vo.getClerkObtainedMaxQuantityType());
        if (unlimitedPerUser) {
            entity.setClerkObtainedMaxQuantity(null);
        } else {
            Integer perUserLimit = vo.getClerkObtainedMaxQuantity();
            if (perUserLimit == null || perUserLimit <= 0) {
                throw new CustomException("每人限领数量必须大于0");
            }
            entity.setClerkObtainedMaxQuantity(perUserLimit);
        }

        String discountContent = "";
        if (BigDecimal.ZERO.compareTo(vo.getUseMinAmount()) == 0) {
            discountContent = "无门槛";
        } else {
            discountContent = "满" + vo.getUseMinAmount() + "船票";
        }
        if ("0".equals(vo.getDiscountType())) {
            discountContent += ("减" + vo.getDiscountAmount() + "船票");
        } else {
            discountContent += ("打" + vo.getDiscountAmount() + "折");
        }
        entity.setDiscountContent(discountContent);
        entity.setCouponOnLineState("1");
        // 领取白名单校验：当为2时必须配置白名单
        if ("2".equals(vo.getClaimConditionType()) && (vo.getCustomWhitelist() == null || vo.getCustomWhitelist().isEmpty())) {
            throw new CustomException("领取条件为白名单时，必须设置领取白名单");
        }
        boolean success = playCouponInfoService.create(entity);
        if (success) {
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改优惠券信息
     */
    @ApiOperation(value = "修改优惠券", notes = "修改优惠券信息")
    @ApiImplicitParam(name = "id", value = "优惠券ID", required = true, paramType = "path", dataType = "String", example = "1")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功"), @ApiResponse(code = 500, message = "修改失败，包含详细错误信息")})
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:edit')")
    @Log(title = "优惠券信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/{id}")
    public R update(@PathVariable String id,
                    @ApiParam(value = "优惠券信息", required = true) @RequestBody PlayCouponInfoEntity playCouponInfo) {
        playCouponInfo.setId(id);
        boolean success = playCouponInfoService.update(playCouponInfo);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除优惠券信息
     */
    @ApiOperation(value = "删除优惠券", notes = "根据ID批量删除优惠券信息")
    @ApiImplicitParam(name = "ids", value = "优惠券ID数组", required = true, paramType = "path", dataType = "String[]", example = "1,2,3")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:remove')")
    @Log(title = "优惠券信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids) {
        return R.ok(playCouponInfoService.deletePlayCouponInfoByIds(ids));
    }
}
