package com.xxfc.platform.activity.biz;

import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.activity.constant.CouponUsed;
import com.xxfc.platform.activity.entity.Coupon;
import com.xxfc.platform.activity.entity.UserCoupon;
import com.xxfc.platform.activity.vo.UserCouponVo;
import com.xxfc.platform.universal.weixin.util.Snowflake;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xxfc.platform.activity.mapper.UserCouponMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 我的优惠卷
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-06-21 14:34:49
 */
@Service
@Slf4j
public class UserCouponBiz extends BaseBiz<UserCouponMapper, UserCoupon> {


    @Autowired
    private  CouponBiz couponBiz;

    private  static  final  Long  DAY=86400000L;

    //自动发送优惠卷
    public String authledCoupon(Integer userId){
        if (userId==null||userId==0){
            log.error("----参数不能为空");
            return  null;
        }
        Coupon coupon=couponBiz.getCouponByUsed(CouponUsed.ALLNEW.getCode());
        if (coupon==null){
            log.error(userId+"----无可领取优惠卷");
            return  null;
        }
        Integer couponId=coupon.getId();
        boolean falg=checkUserLed(userId,couponId);
        if(falg){
            log.error(userId+"----已领优惠卷");
            return  null;
        }
        return  led(coupon,userId);
    }

    //用户领劵
    public String userLedCoupon(Integer userId,Integer couponId){
        Coupon coupon=couponBiz.selectById(couponId);
        if (coupon==null||coupon.getIsDel()!=0||coupon.getStatus()!=1){
            log.error(userId+"----无可领取优惠卷");
            return null;
        }
        boolean falg=checkUserLed(userId,couponId);
        if(falg){
            log.error(userId+"----已领优惠卷");
            return null;
        }
        return  led(coupon,userId);
    }

    //领取动作
    public  String  led( Coupon coupon,Integer userId ){
        int type=coupon.getValidType();
        Integer couponId=coupon.getId();
        Long expireTime=System.currentTimeMillis();
        Long startTime=0L;
        if(type==1){
            startTime=coupon.getStartTime();
            expireTime=coupon.getValidEndTime();
        }else {
            startTime=expireTime;
            expireTime+=DAY*coupon.getValidDays();
        }
        String ticker_no=Snowflake.build()+"";
        UserCoupon userCoupon=new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setTickerNo(ticker_no);
        userCoupon.setStartTime(startTime);
        userCoupon.setExpireTime(expireTime);
        insertSelective(userCoupon);
        return  ticker_no;
    }

    //检查用户是否领卷
    public  boolean checkUserLed(Integer userId,Integer id){
        Example example=new Example(UserCoupon.class);
        example.createCriteria().andEqualTo("userId",userId).andEqualTo("couponId",id);
        List<UserCoupon> list=selectByExample(example);
        if(list.size()>0){
            log.error(userId+"----已领优惠卷");
            return  true;
        }
        return false;
    }

    //获取我的优惠卷
    public ObjectRestResponse getCouponList(Integer userId,int type,Integer channel,BigDecimal amout){
        if (userId==null||userId==0){
            log.error("----参数不能为空");
            return  ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE,"参数不能为空");
        }
        Long time=System.currentTimeMillis();
        List<UserCouponVo> list=mapper.getUserCouponsByType(userId,type,time,channel);
        if(amout.compareTo(new BigDecimal("0.00"))>0&&list.size()>0){
            for (UserCouponVo couponVo:list){
                    Integer status=2;
                    if(couponVo.getType()==1){
                        if (amout.compareTo(couponVo.getWithAmount())>=0){
                            status=1;
                        }
                    }else if (couponVo.getType()==3){
                        status=1;
                    }

                couponVo.setStatus(status);
            }

        }
        list.sort(Comparator.comparing(UserCouponVo::getStatus));
        return  ObjectRestResponse.succ(list);
    }


    //获取单个优惠卷
    public UserCouponVo getUserCoupon(String tickerNo){
        if (StringUtils.isBlank(tickerNo)){
            log.error("----参数不能为空");
            return  null;
        }
        return  mapper.getUserCoupon(tickerNo);
    }

    //支付后更新优惠卷状态
    public BigDecimal useTickerNo(Integer userId, String TickerNo, String orderNo,Integer channel,BigDecimal amout,Integer type){
        BigDecimal couponAmout=new BigDecimal("0.00");
        if(couponAmout.compareTo(amout) >= 0) {
            return BigDecimal.ZERO;
        }
        if (userId==null||userId==0||StringUtils.isBlank(TickerNo)){
            log.error("----参数不能为空");
            return couponAmout;
        }
        Example example=new Example(UserCoupon.class);
        example.createCriteria().andEqualTo("tickerNo",TickerNo).andEqualTo("isDel",0);
        List<UserCoupon> list=selectByExample(example);
        if(list.size()==0){
            log.error(userId+"----没有可用优惠卷--tickerNo==="+TickerNo);
            return couponAmout;
        }

         UserCoupon userCoupon=list.get(0);
        if(userCoupon!=null&&userCoupon.getIsUse()==1){
            log.error(userId+"----该优惠卷已使用--tickerNo=="+TickerNo);
            return couponAmout;
        }
        if (type==1){
            userCoupon.setIsUse(1);
            userCoupon.setOrderNo(orderNo);
            userCoupon.setUseTime(System.currentTimeMillis());
            updateSelectiveById(userCoupon);
        }


        return   getCouponAmout(userCoupon.getCouponId(),channel,amout);
    }

    public  BigDecimal  getCouponAmout(Integer couponId,Integer channel,BigDecimal amout) {
        BigDecimal couponAmout = new BigDecimal("0.00");
        Coupon coupon = couponBiz.selectById(couponId);
        if (coupon != null && coupon.getChannel() == channel) {
            Integer type = coupon.getType();
            if (type != null) {
                BigDecimal useAmout = coupon.getUsedAmount();

                if (type == 3 || (type == 1 && (amout.compareTo(coupon.getWithAmount()) >= 0))) {
                    //couponAmout = amout.subtract(useAmout);
                    if (amout.compareTo(useAmout) > 0) {
                         couponAmout= useAmout;
                    }else {
                         couponAmout= amout;
                    }
                }
            }
        }
        return couponAmout;
    }

    //取消使用优惠卷
    public void cancelTickerNo(String TickerNo){
        if (StringUtils.isBlank(TickerNo)){
            log.error("----参数不能为空");
            return;
        }
        Example example=new Example(UserCoupon.class);
        example.createCriteria().andEqualTo("tickerNo",TickerNo).andEqualTo("isDel",0);
        List<UserCoupon> list=selectByExample(example);
        if(list.size()==0){
            log.error(TickerNo+"----优惠卷不存在");
            return;
        }
        UserCoupon userCoupon=list.get(0);
       if (userCoupon!=null&&userCoupon.getIsUse()!=1){
           log.error(TickerNo+"----没有领优惠卷");
           return;
       }
        userCoupon.setIsUse(0);
        userCoupon.setOrderNo("");
        userCoupon.setUseTime(0L);
        updateSelectiveById(userCoupon);
    }




}