package com.yonge.cooleshow.admin.controller.coupon;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.admin.io.request.coupon.CouponIssueVo;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.CouponIssue;
import com.yonge.cooleshow.biz.dal.enums.SendTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.coupon.CouponUseStateEnum;
import com.yonge.cooleshow.biz.dal.queryInfo.CouponIssueQueryInfo;
import com.yonge.cooleshow.biz.dal.service.CouponIssueService;
import com.yonge.cooleshow.biz.dal.vo.CouponIssueUserVo;
import com.yonge.cooleshow.biz.dal.vo.coupon.CouponIssueWrapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

import static com.yonge.cooleshow.common.entity.HttpResponseResult.failed;
import static com.yonge.cooleshow.common.entity.HttpResponseResult.succeed;

/**
 * <p>
 * 优惠券发放 前端控制器
 * </p>
 *
 * @author Eric
 * @since 2022-09-02
 */
@RestController
@RequestMapping("/couponIssue")
@Api(value = "优惠券发放信息", tags = "优惠券发放信息")
@Validated
public class CouponIssueController {

    @Autowired
    private CouponIssueService couponIssueService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    /**
     * 优惠券发放分页信息
     */
    @PostMapping("/page")
    @ApiOperation(value = "查询优惠券发放分页")
    public HttpResponseResult<PageInfo<CouponIssueVo.CouponIssuePageInfo>> queryCouponIssuePageInfo(@RequestBody @Valid CouponIssueVo.PageRequest request) {

        if (request.getCouponId() == null) {
            return failed("优惠券id不能为空");
        }
        IPage<CouponIssueWrapper> couponIssueWrapperIPage = couponIssueService.queryCouponIssueInfo(
                PageUtil.getPage(request), CouponIssueQueryInfo.from(request.jsonString()));


        // 数据转换
        List<CouponIssueVo.CouponIssuePageInfo> pageInfos = JSON.parseArray(JSON.toJSONString(couponIssueWrapperIPage.getRecords()),
                                                                    CouponIssueVo.CouponIssuePageInfo.class);

        return succeed(PageUtil.getPageInfo(couponIssueWrapperIPage,pageInfos));
    }


    /**
     * 优惠券课发放用户分页信息
     */
    @PostMapping("/userPage")
    @ApiOperation(value = "优惠券发放用户分页信息")
    public HttpResponseResult<PageInfo<CouponIssueUserVo>> queryCouponIssueUserPageInfo(@RequestBody @Valid CouponIssueVo.CouponIssueUserRequest request) {

        IPage<CouponIssueUserVo> couponIssueUserVoIPage = couponIssueService.queryUser(PageUtil.getPage(request),
                                                                                       request.getCouponId(),
                                                                                       request.getClient(),
                                                                                       request.getKeyword());


        return succeed(PageUtil.pageInfo(couponIssueUserVoIPage));
    }


    @PostMapping("/issueUser")
    @ApiOperation(value = "发送优惠券")
    public HttpResponseResult<Boolean> issueCoupon(@RequestBody @Valid CouponIssueVo.CouponIssueUserParam param) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null  || sysUser.getId() == null) {
            return failed("用户信息获取失败");
        }
        couponIssueService.issueCoupon(param.getCouponId(), param.getUserParam(), sysUser.getId(), param.getRemark(),
                                       SendTypeEnum.PLATFORM, new Date());

        return succeed();
    }

    @PostMapping("/withdraw/{couponIssueId}")
    @ApiOperation(value = "撤回优惠券")
    public HttpResponseResult<Boolean> withdrawCoupon(@PathVariable Long couponIssueId) {
        CouponIssue couponIssue = couponIssueService.getById(couponIssueId);
        if (couponIssue == null) {
            return failed("未找到数据");
        }
        if (couponIssue.getUseState().equals(CouponUseStateEnum.USED)) {
            return failed("优惠券已被使用");
        }  else if(couponIssue.getEndTime().compareTo(DateTime.now().getMillis()) <0) {
            return failed("优惠券已过期");
        }
        return HttpResponseResult.status(couponIssueService.withdrawCoupon(couponIssueId));
    }


    /**
     * 优惠券发放分页信息
     */
    @PostMapping("/user/page")
    @ApiOperation(value = "查询用户（老师/学生）优惠券发放分页")
    public HttpResponseResult<PageInfo<CouponIssueVo.UserCouponIssuePageInfo>> queryCouponIssuePageInfo(@RequestBody @Valid CouponIssueVo.UserCouponIssuePageRequest request) {

        IPage<CouponIssueWrapper> couponIssueWrapperIPage = couponIssueService.queryCouponIssueInfo(
                PageUtil.getPage(request), CouponIssueQueryInfo.from(request.jsonString()));


        // 数据转换
        List<CouponIssueVo.UserCouponIssuePageInfo> pageInfos = JSON.parseArray(JSON.toJSONString(couponIssueWrapperIPage.getRecords()),
                                                                            CouponIssueVo.UserCouponIssuePageInfo.class);

        return succeed(PageUtil.getPageInfo(couponIssueWrapperIPage,pageInfos));
    }

}
