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.vo.*;
import com.starry.admin.modules.shop.service.IPlayCouponDetailsService;
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 org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 优惠券信息Controller
 *
 * @author admin
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/shop/coupon")
public class PlayCouponInfoController {
    @Resource
    private IPlayCouponInfoService playCouponInfoService;

    @Resource
    private IPlayCouponDetailsService playCouponDetailsService;

    @Resource
    private IPlayCustomUserInfoService playCustomUserInfoService;

    /**
     * 查询优惠券信息列表
     */
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:list')")
    @PostMapping("/listByPage")
    public R list(PlayCouponInfoQueryVo vo) {
        IPage<PlayCouponInfoReturnVo> list = playCouponInfoService.selectByPage(vo);
        return R.ok(list);
    }

    /**
     * 修改优惠券上下架状态
     *
     * @param vo 优惠券上下架对象
     */
    @PostMapping("/updateOnLineState")
    public R updateOnLineState(@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 优惠券发放对象
     */
    @PostMapping("/sendCoupon")
    public R sendCoupon(@Validated @RequestBody PlayCouponInfoSendVo vo) {
        PlayCustomUserInfoEntity customUserInfo = playCustomUserInfoService.selectById(vo.getCustomId());
        playCouponDetailsService.create(customUserInfo.getId(), customUserInfo.getNickname(), customUserInfo.getLevelId(), vo.getId(), "2", "1");
        return R.ok();
    }


    /**
     * 获取优惠券信息详细信息
     */
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") String id) {
        return R.ok(playCouponInfoService.selectPlayCouponInfoById(id));
    }

    /**
     * 新增优惠券信息
     */
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:create')")
    @Log(title = "优惠券信息", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@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");
        }
        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");
        boolean success = playCouponInfoService.create(entity);
        if (success) {
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改优惠券信息
     */
    // @PreAuthorize("@customSs.hasPermission('shop:coupon:edit')")
    @Log(title = "优惠券信息", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/{id}")
    public R update(@PathVariable String id, @RequestBody PlayCouponInfoEntity playCouponInfo) {
        playCouponInfo.setId(id);
        boolean success = playCouponInfoService.update(playCouponInfo);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除优惠券信息
     */
    // @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));
    }
}
