package com.hai.service.impl;

import com.alibaba.fastjson.JSON;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.dao.HighUserCouponMapper;
import com.hai.entity.*;
import com.hai.model.HighUserCouponModel;
import com.hai.service.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/27 16:10
 */
@Service("highUserCouponService")
public class HighUserCouponServiceImpl implements HighUserCouponService {

    @Resource
    private HighUserCouponMapper highUserCouponMapper;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighCouponRecycleService highCouponRecycleService;

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private HighUserService highUserService;

    @Override
    public void insertUserCoupon(HighUserCoupon highUserCoupon) {
        highUserCouponMapper.insert(highUserCoupon);
    }

    @Override
    public void updateUserCoupon(HighUserCoupon highUserCoupon) {
        highUserCouponMapper.updateByPrimaryKey(highUserCoupon);
    }

    @Override
    public List<HighUserCoupon> getOverdueCoupon() {
        HighUserCouponExample example = new HighUserCouponExample();
        example.createCriteria().andStatusEqualTo(1).andUseEndTimeLessThanOrEqualTo(new Date());
        return highUserCouponMapper.selectByExample(example);
    }

    @Override
    public HighUserCoupon getDetailByCodeId(Long couponCodeId) {

        HighUserCouponExample example = new HighUserCouponExample();
        example.createCriteria().andStatusEqualTo(1).andCouponCodeIdEqualTo(couponCodeId);
        List<HighUserCoupon> highUserCoupons = highUserCouponMapper.selectByExample(example);
        if (highUserCoupons.size() > 0) {
            return highUserCoupons.get(0);
        }
        return null;
    }

    @Override
    public HighUserCoupon getDetailById(Long userCouponId) {
        return highUserCouponMapper.selectByPrimaryKey(userCouponId);
    }

    @Override
    public HighUserCoupon getUserNewCoupon(Long userId, Long couponId) {
        HighUserCouponExample example = new HighUserCouponExample();
        example.createCriteria().andUserIdEqualTo(userId).andCouponIdEqualTo(couponId).andStatusEqualTo(1);
        example.setOrderByClause("create_time desc");
        List<HighUserCoupon> couponList = highUserCouponMapper.selectByExample(example);
        if (couponList != null && couponList.size() > 0) {
            return couponList.get(0);
        }
        return null;
    }

    @Override
    public List<HighUserCoupon> getUserCouponList(Map<String, Object> map) {
        HighUserCouponExample example = new HighUserCouponExample();
        HighUserCouponExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }

        if (MapUtils.getLong(map, "merchantId") != null) {
            criteria.andMerchantIdEqualTo(MapUtils.getLong(map, "merchantId"));
        }

        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        }

        if (MapUtils.getLong(map, "couponCodeId") != null) {
            criteria.andCouponCodeIdEqualTo(MapUtils.getLong(map, "couponCodeId"));
        }

        criteria.andStatusNotEqualTo(100);
        example.setOrderByClause("create_time desc");
        List<HighUserCoupon> highUserCoupons = highUserCouponMapper.selectByExample(example);
        if (highUserCoupons.size() > 0) {
            for (HighUserCoupon highUserCoupon : highUserCoupons) {
                highUserCoupon.setHighCouponModel(highCouponService.getCouponById(highUserCoupon.getCouponId()));
            }
        }
        return highUserCoupons;
    }

    @Override
    public HighUserCoupon getUserCoupon(Long userId, Long couponId) {
        HighUserCouponExample example = new HighUserCouponExample();
        example.createCriteria().andUserIdEqualTo(userId).andCouponIdEqualTo(couponId).andStatusNotEqualTo(100);
        List<HighUserCoupon> coupons = highUserCouponMapper.selectByExample(example);
        if (coupons != null && coupons.size() > 0) {
            return coupons.get(0);
        }
        return null;
    }

    @Override
    public List<HighUserCoupon> getCouponList(Long userId, Integer status) {
        HighUserCouponExample example = new HighUserCouponExample();
        HighUserCouponExample.Criteria criteria = example.createCriteria().andUserIdEqualTo(userId);
        if (status != null) {
            criteria.andStatusEqualTo(status);
        }
        example.setOrderByClause("create_time desc");
        return highUserCouponMapper.selectByExample(example);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRES_NEW)
    public HighUserCoupon againReceiveCoupon(Long userId, Long couponId) {
        // 用户的卡卷
        HighUserCoupon userCoupon = getUserCoupon(userId, couponId);
        if (userCoupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到卡卷");
        }
        if (userCoupon.getStatus() != 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法重新领取");
        }
        userCoupon.setStatus(100); // 删除
        highUserCouponMapper.updateByPrimaryKey(userCoupon);

        HighCoupon coupon = highCouponService.getCouponById(userCoupon.getCouponId());
        if (coupon == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到卡卷");
        }
        // 查询待销售
        List<HighCouponCode> list = highCouponCodeService.getNoSaleCode(coupon.getId());
        if (list == null || list.size() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, coupon.getCouponName() + "暂无库存,请联系客服");
        }

        HighCouponCode highCouponCode = list.get(0);
        //highCouponCode.setChildOrderId(userCoupon.getId());
        highCouponCode.setStatus(2);  // 状态：1.待销售 2.未使用 3.已使用  99.预支付
        highCouponCode.setReceiveTime(new Date());
        highCouponCodeService.updateCouponCode(highCouponCode);

        // 卡卷关联用户
        HighUserCoupon highUserCoupon = new HighUserCoupon();
        highUserCoupon.setMerchantId(coupon.getMerchantId());
        highUserCoupon.setCouponId(coupon.getId());
        highUserCoupon.setUserId(userId);
        highUserCoupon.setCouponCodeId(highCouponCode.getId());
        highUserCoupon.setCreateTime(new Date());

        // 计算使用有效期
        Calendar userEndTime = Calendar.getInstance();
        userEndTime.add(Calendar.DATE, coupon.getRecycleDay());
        if (userEndTime.getTime().compareTo(highCouponCode.getUseEndTime()) == 1) {
            highUserCoupon.setUseEndTime(highCouponCode.getUseEndTime());
        } else {
            highUserCoupon.setUseEndTime(userEndTime.getTime());
        }
        highUserCoupon.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
        highUserCoupon.setQrCodeImg(highCouponCode.getExt1());
        highUserCouponMapper.insert(highUserCoupon);

        return highUserCoupon;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void expiredCoupon(Long userCouponId) {
        HighUserCoupon highUserCoupon = highUserCouponMapper.selectByPrimaryKey(userCouponId);
        highUserCoupon.setStatus(0);   // 状态  0:已过期  1：未使用  2：已使用
        highUserCoupon.setQrCodeImg(null);
        updateUserCoupon(highUserCoupon);

        // 查询销售码
        HighCouponCode couponCode = highCouponCodeService.getCouponCodeById(highUserCoupon.getCouponCodeId());

        HighUser highUser = highUserService.findByUserId(highUserCoupon.getUserId());

        // 查询卡券信息
        HighCoupon coupon = highCouponService.getCouponById(highUserCoupon.getCouponId());

        HighChildOrder childOrder = highOrderService.getChildOrderByUserGoods(highUserCoupon.getUserId(),1, highUserCoupon.getCouponCodeId());
        HighOrder order = highOrderService.getOrderById(childOrder.getOrderId());

        // 归库记录
        HighCouponRecycle highCouponRecycle = new HighCouponRecycle();
        highCouponRecycle.setCouponId(coupon.getId());
        highCouponRecycle.setCouponName(coupon.getCouponName());
        highCouponRecycle.setMerchantId(coupon.getMerchantId());

        highCouponRecycle.setCouponSalesCode(couponCode.getSalesCode());
        highCouponRecycle.setCouponCodeId(couponCode.getId());

        highCouponRecycle.setOrderId(childOrder.getOrderId());
        highCouponRecycle.setOrderNo(order.getOrderNo());
        highCouponRecycle.setChildOrderId(childOrder.getId());

        highCouponRecycle.setUserId(highUser.getId());
        highCouponRecycle.setUserPhone(highUser.getPhone());

        highCouponRecycle.setType(1);   // 类型：1.过期    2.退款
        highCouponRecycle.setReceiveTime(highUserCoupon.getCreateTime());  // 领取时间
        highCouponRecycle.setCreateTime(new Date());
        highCouponRecycleService.insertCouponRecycle(highCouponRecycle);

        couponCode.setChildOrderId(null);
        couponCode.setReceiveTime(null);
        highCouponCodeService.updateCouponCode(couponCode);
    }
}
