package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.po.WxCouponOrder;
import com.iformall.domain.vo.WxCardCVo;
import com.iformall.domain.vo.WxCouponOrderCVo;
import com.iformall.enums.EnumCouponChannelActivityStatus;
import com.iformall.enums.EnumCouponOrderStatus;
import com.iformall.enums.EnumCouponOrderValidStatus;
import com.iformall.service.WxCouponOrderService;
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.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/api/couponOrder")
@Api(description = "用户卡券查询接口")
public class WxCouponOrderController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCouponOrderService wxCouponOrderService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @ApiOperation("券包分页列表接口")
    @GetMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    public ResultData list(@ModelAttribute WxCouponOrder wxCouponOrder, Integer pageNum, Integer pageSize) {

        if (pageNum == null || pageSize == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        if (wxCouponOrder == null) wxCouponOrder = new WxCouponOrderCVo();
        wxCouponOrder.setCUserId(getUserId());
        if (wxCouponOrder.getCouponOrderStatus() == null)
            wxCouponOrder.setSortColumns(BaseEntity.SortField.CreateDate_DESC, BaseEntity.SortField.Id_DESC);
        else if (wxCouponOrder.getCouponOrderStatus() == EnumCouponOrderStatus.COUPON_ORDER_USE_WAIT.getCode())
            wxCouponOrder.setSortColumns(BaseEntity.SortField.CreateDate_DESC, BaseEntity.SortField.Id_DESC);
        else
            wxCouponOrder.setSortColumns(BaseEntity.SortField.UpdateDate_DESC, BaseEntity.SortField.Id_DESC);

        PageInfo<WxCouponOrderCVo> page = wxCouponOrderService.listCUserVoAsPage(wxCouponOrder, pageNum, pageSize);

        Date now = new Date();
        page.getList().stream().forEach(co->{
            if (co.getValidStartDate() != null && co.getValidEndDate() != null ) {
                if (co.getValidStartDate().getTime() > now.getTime()) {
                    co.setValidStatus(EnumCouponOrderValidStatus.PREPARED.getCode());
                } else if (co.getValidEndDate().getTime() < now.getTime()) {
                    co.setValidStatus(EnumCouponOrderValidStatus.ENDED.getCode());
                } else {
                    co.setValidStatus(EnumCouponChannelActivityStatus.STARTED.getCode());
                }
            }
        });

        return new ResultData(page);
    }

    @ApiOperation(value = "券详情接口")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponOrderId", value = "券ID", dataType = "string", paramType = "query", required = true)
    })
    public ResultData detail(String couponOrderId) {

        if (couponOrderId == null || couponOrderId.equalsIgnoreCase(Constant.UNDEFINED)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }

        WxCouponOrderCVo wxCouponOrderCVo = wxCouponOrderService.detailCUserVo(couponOrderId);

        if (wxCouponOrderCVo == null) {
            return new ResultData(ErrorCode.COUPON_ORDER_IS_NULL);
        }

        if (!wxCouponOrderCVo.getCUserId().equals(getUserId())) {
            return new ResultData(ErrorCode.COUPON_ORDER_IS_NULL);
        }
        Date now = new Date();
        if (wxCouponOrderCVo.getValidStartDate() != null && wxCouponOrderCVo.getValidEndDate() != null ) {
            if (wxCouponOrderCVo.getValidStartDate().getTime() > now.getTime()) {
                wxCouponOrderCVo.setValidStatus(EnumCouponOrderValidStatus.PREPARED.getCode());
            } else if (wxCouponOrderCVo.getValidEndDate().getTime() < now.getTime()) {
                wxCouponOrderCVo.setValidStatus(EnumCouponOrderValidStatus.ENDED.getCode());
            } else {
                wxCouponOrderCVo.setValidStatus(EnumCouponChannelActivityStatus.STARTED.getCode());
            }
        }

        return new ResultData(wxCouponOrderCVo);
    }

    @ApiOperation(value = "卡券状态接口")
    @GetMapping("getStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponOrderId", value = "券ID", dataType = "string", paramType = "query", required = true)
    })
    public ResultData getStatus(String couponOrderId) {

        if (couponOrderId == null || couponOrderId.equalsIgnoreCase(Constant.UNDEFINED)) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }

        Map res = new HashMap();

        res.put("CouponOrderStatus", wxCouponOrderService.getById(Long.valueOf(couponOrderId)).getCouponOrderStatus());

        return new ResultData(res);
    }

    //// ------ 卡相关接口
    @ApiOperation("卡包分页列表接口")
    @GetMapping("cardList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    public ResultData cardList(@ModelAttribute WxCardCVo cardCVo, Integer pageNum, Integer pageSize) {

        if (pageNum == null || pageSize == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }
        if (cardCVo == null) cardCVo = new WxCardCVo();
        cardCVo.setTenantId(getTenantId());
        cardCVo.setOwnerId(getUserId());
        if(StringUtils.isNotBlank(cardCVo.getStatusStr())) {
            String [] statusAttr = cardCVo.getStatusStr().split(",");
            List<Integer> tmpList = new ArrayList<Integer>();
            for(String status: statusAttr) {
                tmpList.add(Integer.valueOf(status));
            }
            if(!tmpList.isEmpty()) {
                cardCVo.setStatusS(tmpList);
            }
        }
        if (cardCVo.getCouponOrderStatus() == null)
            cardCVo.setSortColumns(BaseEntity.SortField.CreateDate_DESC);
        else if (cardCVo.getCouponOrderStatus() == EnumCouponOrderStatus.CARD_USING.getCode())
            cardCVo.setSortColumns(BaseEntity.SortField.CreateDate_DESC);
        else
            cardCVo.setSortColumns(BaseEntity.SortField.UpdateDate_DESC);
        return wxCouponOrderService.listCardVoAsPage(cardCVo, pageNum, pageSize);
    }

    @ApiOperation(value = "卡券详情接口")
    @GetMapping("cardDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "couponOrderId", value = "券ID", dataType = "string", paramType = "query", required = true)
    })
    public ResultData cardDetail(String couponOrderId) {

        if (couponOrderId == null || couponOrderId.equalsIgnoreCase(Constant.UNDEFINED) ) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL);
        }

        return wxCouponOrderService.cardDetailCUserVo(getUserId(), couponOrderId);
    }

    @ApiOperation(value = "卡转赠领取")
    @PostMapping("cardAccept")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "coupon_order_id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "cUserId", value = "转赠者", dataType = "Long", paramType = "query", required = true),
    })
    public ResultData cardAccept(@RequestBody WxCouponOrder wxCouponOrder) {
        //coupon_order_id判断
        Long id = wxCouponOrder.getId();
        if (id == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "id不能为空");
        }
        //转赠人判断
        Long cUserId = wxCouponOrder.getCUserId();
        if (cUserId == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "cUserId不能为空");
        }
        //当前领取人
        wxCouponOrder.setOwnerId(getUserId());
        //转赠者与当前领取人是否为同一个
        if (cUserId.equals(wxCouponOrder.getOwnerId())) {
            logger.info("转赠人与卡所有者相同");
            return new ResultData(ErrorCode.CARD_TRANSFER_INVALID.getCode(), "转赠人与卡所有者相同");
        }

        return wxCouponOrderService.cardAccept(wxCouponOrder);

    }

    @ApiOperation(value = "查询转赠卡状态")
    @GetMapping("queryCardStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "coupon_order_id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "cUserId", value = "转赠者", dataType = "Long", paramType = "query", required = true),
    })
    public ResultData queryCardStatus(@ModelAttribute WxCouponOrder wxCouponOrder) {

        //coupon_order_id判断
        Long id = wxCouponOrder.getId();
        if (id == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "id不能为空");
        }
        //转赠人判断
        Long cUserId = wxCouponOrder.getCUserId();
        if (cUserId == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "cUserId不能为空");
        }
        // update_date判断
        if(wxCouponOrder.getUpdateDate() == null) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "updateDate不能为空");
        }
        //当前领取人
        wxCouponOrder.setOwnerId(getUserId());
        return wxCouponOrderService.queryCardStatus(wxCouponOrder);
    }

}
