package com.iformall.controller;

import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxCoupon;
import com.iformall.domain.vo.WxCouponCVo;
import com.iformall.enums.EnumCouponChannelActivityStatus;
import com.iformall.enums.EnumCouponChannelType;
import com.iformall.service.WxCouponChannelService;
import com.iformall.service.WxCouponService;
import com.iformall.utils.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/wxCoupon")
@Api(description = "券类型相关接口")
public class WxCouponController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponChannelService wxCouponChannelService;
    @Autowired
    private WxCouponService couponService;

    @Autowired
    @Qualifier("couponDetailRedisTemplate")
    RedisTemplate<String, WxCouponCVo> cdRedisTemplate;

    @ApiOperation("根据id(couponChannel)查询接口")
    @GetMapping("/detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponChannelId", value = "couponChannelId", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "couponId", value = "couponId", dataType = "String", paramType = "query", required = false)})
    public ResultData detailC(String couponChannelId, String couponId) {
        if (StringUtils.isBlank(couponChannelId) || couponChannelId.equalsIgnoreCase(Constant.UNDEFINED)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId/couponId为空");
        }
        Long couponChannelIdL = 0L, couponIdL = 0L;
        try {
            couponChannelIdL = Long.valueOf(couponChannelId);
            if (StringUtils.isNotBlank(couponId) && !couponId.equalsIgnoreCase(Constant.UNDEFINED)) {
                couponIdL = Long.valueOf(couponId);
            }
        } catch (NumberFormatException e) {
            logger.error("id转换失败" + couponChannelId);
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "couponChannelId转换失败" + couponChannelId);
        }

        String key = "cc:" + couponChannelId;

        ValueOperations<String, WxCouponCVo> operations = cdRedisTemplate.opsForValue();
        // 缓存
        boolean hasKey = cdRedisTemplate.hasKey(key);
        if (hasKey) {
            // 从缓存获取用户信息
            WxCouponCVo wxCouponCVo = operations.get(key);
            if (couponIdL > 0L) {
                // 更新状态
                WxCouponCVo couponCVo = couponService.getVoStatusById(couponIdL);
                if (wxCouponCVo == null) {
                    return new ResultData(ErrorCode.COUPON_IS_EMPTY);
                }
                wxCouponCVo.setRemainInventory(couponCVo.getRemainInventory());
                wxCouponCVo.setStatus(couponCVo.getStatus());
            } else {
                // 更新状态
                WxCouponCVo couponCVo = wxCouponChannelService.findVoStatusDetail(couponChannelIdL);
                if (wxCouponCVo == null) {
                    return new ResultData(ErrorCode.COUPON_IS_EMPTY);
                }
                wxCouponCVo.setRemainInventory(couponCVo.getRemainInventory());
                wxCouponCVo.setStatus(couponCVo.getStatus());
            }
            // end of 更新状态
            updateActivityStatus(wxCouponCVo);
            return new ResultData(wxCouponCVo);
        }

        WxCouponCVo wxCouponCVo = wxCouponChannelService.findDetailVo(couponChannelIdL);
        if (wxCouponCVo == null) {
            return new ResultData(ErrorCode.COUPON_IS_EMPTY);
        }

        // 插入缓存
        operations.set(key, wxCouponCVo, 3600, TimeUnit.SECONDS);

        updateActivityStatus(wxCouponCVo);

        return new ResultData(wxCouponCVo);
    }

    private void updateActivityStatus(WxCouponCVo wxCouponCVo) {
        if (wxCouponCVo.getTargetAd() != null &&
                wxCouponCVo.getTargetAd().equals(EnumCouponChannelType.COUPON_CHANNEL_ID_TIMED.getCode())) {
            Date now = new Date();

            if (wxCouponCVo.getBeginTime().getTime() > now.getTime()) {
                wxCouponCVo.setActivityStatus(EnumCouponChannelActivityStatus.PREPARED.getCode());
            } else if (wxCouponCVo.getEndTime().getTime() < now.getTime()) {
                wxCouponCVo.setActivityStatus(EnumCouponChannelActivityStatus.ENDED.getCode());
            } else {
                wxCouponCVo.setActivityStatus(EnumCouponChannelActivityStatus.STARTED.getCode());
            }
        }
    }

}
