package com.qs.mp.web.controller.api.channel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qs.mp.channel.domain.ChannelCouponVerifyLog;
import com.qs.mp.channel.service.IChannelCouponVerifyLogService;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.page.TableDataInfo;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.common.enums.UserCouponStatusEnum;
import com.qs.mp.user.domain.UserCoupon;
import com.qs.mp.user.domain.UserCouponChannel;
import com.qs.mp.user.domain.vo.UserCouponVO;
import com.qs.mp.user.service.IUserCouponChannelService;
import com.qs.mp.user.service.IUserCouponService;
import com.qs.mp.utils.SecurityUtils;
import com.qs.mp.web.controller.common.BaseApiController;
import io.swagger.annotations.Api;
import java.util.Date;
import java.util.List;
import ma.glasnost.orika.MapperFacade;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther zhongcp
 * @create 2022-02-28 16:17:48
 * @describe 渠道优惠券核销前端控制器
 */
@Api("渠道管理API")
@RestController
@RequestMapping("/api/v1/mp/channel/*")
@Component
public class ChannelCouponVerifyController extends BaseApiController {

  @Autowired
  private IChannelService channelService;

  @Autowired
  private IUserCouponService userCouponService;

  @Autowired
  private IUserCouponChannelService userCouponChannelService;

  @Autowired
  private IChannelCouponVerifyLogService channelCouponVerifyLogService;

  @Autowired
  private MapperFacade mapperFacade;

  /**
   * 优惠券查询
   *
   * @param
   * @return
   */
  @PostMapping(value = "coupon/query")
  public AjaxResult query(@RequestBody JSONObject param) {
    String verifyCode = param.getString("verifyCode");
    Long channelId = SecurityUtils.getLoginUser().getChannelId();
    UserCoupon userCoupon = userCouponService.getOne(new LambdaQueryWrapper<UserCoupon>()
        .eq(UserCoupon::getVerifyCode, verifyCode));
    if (null == userCoupon) {
      return error("券码非法");
    }
    AjaxResult result = checkCoupon(verifyCode, channelId, userCoupon);
    if (null != result) {
      return result;
    }
    List<UserCouponVO> userCouponVOList = userCouponService.listUserCouponVO(
        new QueryWrapper<UserCoupon>()
            .eq("t1.verify_code", verifyCode));

    return AjaxResult.success(userCouponVOList.get(0));
  }

  private AjaxResult checkCoupon(String verifyCode, Long channelId, UserCoupon userCoupon) {
    AjaxResult result = null;

    if (StringUtils.isBlank(verifyCode)) {
      result = error(ErrorCodeEnum.ERROR_CODE_1001);
    }
    if (null == userCoupon) {
      result = error("该券不存在！");
    }
    if (userCoupon.getStatus() == UserCouponStatusEnum.USED) {
      result = error("该券已使用！");
    }
    if (userCoupon.getValidEnd().before(new Date())) {
      result = error("该券已过期！");
    }
    UserCouponChannel couponChannel = userCouponChannelService.getOne(
        new LambdaQueryWrapper<UserCouponChannel>()
            .eq(UserCouponChannel::getUserCouponId, userCoupon.getId())
            .eq(UserCouponChannel::getChannelId, channelId));
    if (null == couponChannel) {
      result = error("无权核销该券");
    }
    return result;
  }

  /**
   * 优惠券核销
   *
   * @param
   * @return
   */
  @PostMapping(value = "coupon/verify")
  public AjaxResult verify(@RequestBody JSONObject param) {
    String verifyCode = param.getString("verifyCode");
    Long channelId = SecurityUtils.getLoginUser().getChannelId();
    UserCoupon userCoupon = userCouponService.getOne(new LambdaQueryWrapper<UserCoupon>()
        .eq(UserCoupon::getVerifyCode, verifyCode));
    if (null == userCoupon) {
      return error("券码非法");
    }
    AjaxResult result = checkCoupon(verifyCode, channelId, userCoupon);
    if (null != result) {
      return result;
    }
    channelCouponVerifyLogService.verify(channelId, userCoupon);
    return AjaxResult.success("核销成功");
  }

  /**
   * 获取我的核销记录
   *
   * @return
   */
  @PostMapping("coupon/verify/log/list")
  public TableDataInfo list(@RequestBody JSONObject jsonObject) {
    Long channelId = SecurityUtils.getLoginUser().getChannelId();
    startPage();
    List<ChannelCouponVerifyLog> verifyLogList = channelCouponVerifyLogService.list(
        new LambdaQueryWrapper<ChannelCouponVerifyLog>()
            .eq(ChannelCouponVerifyLog::getChannelId, channelId)
            .orderByDesc(ChannelCouponVerifyLog::getVerifyTime));
    return getDataTable(verifyLogList);
  }

	/**
	 * 优惠券核销记录详情
	 *
	 * @param
	 * @return
	 */
	@PostMapping(value = "coupon/verify/log/detail")
	public AjaxResult detail(@RequestBody JSONObject param) {
		Long logId = param.getLong("logId");
		if (null == logId || 0 == logId) {
			return error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		ChannelCouponVerifyLog verifyLog = channelCouponVerifyLogService.getById(logId);
		return AjaxResult.success(verifyLog);
	}

}
