package com.liquidnet.service.platform.service.impl.candy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.common.exception.LiquidnetServiceException;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.entity.AdamUserMember;
import com.liquidnet.service.candy.constant.CandyRedisConst;
import com.liquidnet.service.candy.dto.*;
import com.liquidnet.service.candy.entity.*;
import com.liquidnet.service.candy.mapper.CandyCouponMapper;
import com.liquidnet.service.platform.service.impl.adam.PlatformAdamUserMemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class PlatformCandyCouponService extends ServiceImpl<CandyCouponMapper, CandyCoupon> {
    @Autowired
    private PlatformCandyCouponRuleService platformCandyCouponRuleService;
    @Autowired
    private PlatformCandyCouponCodeService platformCandyCouponCodeService;
    @Autowired
    private PlatformCandyUserCouponService platformCandyUserCouponService;
    @Autowired
    private PlatformCandyCommonCouponService platformCandyCommonCouponService;
    @Autowired
    private PlatformAdamUserMemberService platformAdamUserMemberService;
    @Autowired
    private RedisUtil redisUtil;

    private void issueCouponProcessing(final CandyMgtCoupon mgtCoupon, final CandyCoupon coupon) {
        List<CandyCouponRuleDto> couponRuleDtoList = platformCandyCouponRuleService.listForCouponRuleDto(coupon.getCouponId());

        CandyCouponInfoDto couponInfoDto = new CandyCouponInfoDto();
        BeanUtils.copyProperties(coupon, couponInfoDto);
        couponInfoDto.setUseRules(couponRuleDtoList);

        String couponInfoDtoKey = CandyRedisConst.BASIC_COUPON_INFO.concat(couponInfoDto.getCouponId());
        redisUtil.set(couponInfoDtoKey, couponInfoDto);

        switch (coupon.getBindType()) {// 领取方式[0-用户输入兑换｜1-发放至用户]
            case 0:
                this.processingCouponCode(mgtCoupon, coupon);
                break;
            case 1:
                switch (mgtCoupon.getEventType()) {// 发放类型[1-会员｜2-手机号|10-全体用户]
                    case 1:
                        this.processForAllMember(mgtCoupon, coupon, couponRuleDtoList);
                        break;
                    case 2:
                        this.processForUserCoupon(mgtCoupon, coupon, couponRuleDtoList);
                        break;
                    case 10:
                        this.processForCommonCoupon(mgtCoupon, coupon, couponRuleDtoList);
                        break;
                    default:
                        log.warn("发放券任务:无法处理，无效的发放类型[mcouponId:{},eventType:{}]", mgtCoupon.getMcouponId(), mgtCoupon.getEventType());
                        break;
                }
                break;
            default:
                log.warn("发放券任务:无法处理，无效的领取方式[mcouponId:{},bindType:{}]", mgtCoupon.getMcouponId(), coupon.getBindType());
                break;
        }
    }

    /**
     * <p>
     * 券码生成处理
     * </p>
     *
     * @param mgtCoupon CandyMgtCoupon
     * @param coupon    CandyCoupon
     */
    private void processingCouponCode(CandyMgtCoupon mgtCoupon, CandyCoupon coupon) {
        List<CandyCouponCode> initCouponCodeList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        Integer eventAmt = mgtCoupon.getEventAmt();
        for (int i = 0; i < eventAmt; i++) {
            CandyCouponCode couponCode = new CandyCouponCode();
            couponCode.setCcode(RandomStringUtils.randomAlphanumeric(16));
            couponCode.setCouponId(coupon.getCouponId());
            couponCode.setState(0);
            couponCode.setCreatedAt(now);
            couponCode.setRedeemStart(coupon.getRedeemStart());
            couponCode.setRedeemStop(coupon.getRedeemStop());

            initCouponCodeList.add(couponCode);
        }

        if (!initCouponCodeList.isEmpty()) {
            if (platformCandyCouponCodeService.saveBatch(initCouponCodeList)) {
                initCouponCodeList.forEach(r -> {
                    redisUtil.set(CandyRedisConst.BASIC_COUPON_CODE.concat(r.getCcode()), CandyCouponCodeDto.getNew().copy(r));
                });

                initCouponCodeList.clear();
            } else {
                throw new LiquidnetServiceException("-1", String.format("券发放失败[mcouponId=%s]", mgtCoupon.getMcouponId()));
            }
        }
    }

    /**
     * <p>
     * 发放处理-公有券
     * </p>
     *
     * @param mgtCoupon         CandyMgtCoupon
     * @param coupon            CandyCoupon
     * @param couponRuleDtoList List<CandyCouponRuleDto>
     */
    private void processForCommonCoupon(CandyMgtCoupon mgtCoupon, CandyCoupon coupon, List<CandyCouponRuleDto> couponRuleDtoList) {
        List<CandyCommonCoupon> initCommonCouponList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        Integer eventAmt = mgtCoupon.getEventAmt();
        log.info("发放券处理中:目标全体用户[发放量:{}]", eventAmt);

        for (int i = 0; i < eventAmt; i++) {
            CandyCommonCoupon commonCoupon = new CandyCommonCoupon();
            commonCoupon.setCcouponId(IDGenerator.nextMilliId());
            commonCoupon.setMcouponId(mgtCoupon.getMcouponId());
            commonCoupon.setCouponId(coupon.getCouponId());
            commonCoupon.setState(1);
            commonCoupon.setRanged(mgtCoupon.getEventType());
            commonCoupon.setOperator("system");
            commonCoupon.setCreatedAt(now);

            initCommonCouponList.add(commonCoupon);
        }

        if (!initCommonCouponList.isEmpty()) {
            if (platformCandyCommonCouponService.saveBatch(initCommonCouponList, initCommonCouponList.size())) {
                initCommonCouponList.forEach(r -> {
                    String ccKey = CandyRedisConst.BASIC_COMMON_COUPON;

                    List<CandyCommonCouponBasicDto> vos = (List<CandyCommonCouponBasicDto>) redisUtil.get(ccKey);
                    if (CollectionUtils.isEmpty(vos)) {
                        vos = new ArrayList<>();
                    }
                    vos.add(CandyCommonCouponBasicDto.getNew().copy(r, coupon, couponRuleDtoList));

                    redisUtil.set(ccKey, vos);
                });
            } else {
                throw new LiquidnetServiceException("-1", String.format("券发放失败[mcouponId=%s]", mgtCoupon.getMcouponId()));
            }
        }
        log.info("发放券处理中:目标全体用户[发放量:{},实际发放:{}]", eventAmt, initCommonCouponList.size());
    }

    /**
     * <p>
     * 发放处理-全体会员
     * </p>
     *
     * @param mgtCoupon         CandyMgtCoupon
     * @param coupon            CandyCoupon
     * @param couponRuleDtoList List<CandyCouponRuleDto>
     */
    private void processForAllMember(CandyMgtCoupon mgtCoupon, CandyCoupon coupon, List<CandyCouponRuleDto> couponRuleDtoList) {
        List<CandyUserCoupon> initUserCouponList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        LocalDateTime nowEndTime = now.withHour(23).withMinute(59).withSecond(59);
        LambdaQueryWrapper<AdamUserMember> queryWrapper = Wrappers.lambdaQuery(AdamUserMember.class).eq(AdamUserMember::getState, 1)
                .gt(AdamUserMember::getExpiryAt, nowEndTime);
        int userMemberCount = platformAdamUserMemberService.count(queryWrapper), num = 0, pSize = 1000;
        int totalCount = userMemberCount, eventAmt = mgtCoupon.getEventAmt();
        log.info("发放券处理中:目标全体会员[总数:{},发放量:{}]", userMemberCount, eventAmt);

        while (totalCount > 0) {
            initUserCouponList.clear();

            String lastLimitSql = "LIMIT " + (num * pSize) + "," + pSize;
            queryWrapper.orderByAsc(AdamUserMember::getMid).last(lastLimitSql);
            queryWrapper.select(AdamUserMember::getUid);
            List<AdamUserMember> userMemberList = platformAdamUserMemberService.list(queryWrapper);
            int userMemberListSize = CollectionUtils.isEmpty(userMemberList) ? -1 : userMemberList.size();

            for (int j = 0; j < eventAmt; j++) {
                for (int i = 0; i < userMemberListSize; i++) {
                    AdamUserMember userMember = userMemberList.get(i);

                    CandyUserCoupon userCoupon = new CandyUserCoupon();
                    userCoupon.setUcouponId(IDGenerator.get32UUID());
                    userCoupon.setMcouponId(mgtCoupon.getMcouponId());
                    userCoupon.setUid(userMember.getUid());
                    userCoupon.setCouponId(coupon.getCouponId());
                    userCoupon.setState(1);
                    userCoupon.setBindAt(now);
                    userCoupon.setDuedAt(coupon.getExpireAt());

                    initUserCouponList.add(userCoupon);
                }
            }

            if (!initUserCouponList.isEmpty()) {
                if (platformCandyUserCouponService.saveBatch(initUserCouponList)) {
                    initUserCouponList.forEach(r -> {
                        String uckey = CandyRedisConst.BASIC_USER_COUPON.concat(r.getUid());

                        List<CandyUserCouponBasicDto> vos = (List<CandyUserCouponBasicDto>) redisUtil.get(uckey);

                        if (CollectionUtils.isEmpty(vos)) {
                            vos = new ArrayList<>();
                        }
                        vos.add(CandyUserCouponBasicDto.getNew().copy(r, coupon, couponRuleDtoList));

                        redisUtil.set(uckey, vos);
                    });
                } else {
                    throw new LiquidnetServiceException("-1", "券发放失败");
                }
            }

            num++;
            totalCount -= pSize;
            log.info("发放券处理中:目标全体会员[总数:{},发放量:{},单次处理:{},剩余:{}]", userMemberCount, eventAmt, lastLimitSql, totalCount);
        }
    }

    /**
     * <p>
     * 发放处理-私有券（指定手机号）
     * </p>
     *
     * @param mgtCoupon         CandyMgtCoupon
     * @param coupon            CandyCoupon
     * @param couponRuleDtoList List<CandyCouponRuleDto>
     */
    private void processForUserCoupon(CandyMgtCoupon mgtCoupon, CandyCoupon coupon, List<CandyCouponRuleDto> couponRuleDtoList) {
        List<CandyUserCoupon> initUserCouponList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        String eventLimit = mgtCoupon.getEventLimit();
        String[] eventLimitArr = eventLimit.split(",");
        int eventAmt = mgtCoupon.getEventAmt(), pl = 0, limitSize = eventLimitArr.length;
        log.info("发放券处理中:目标指定手机号[总数:{},发放量:{}]", limitSize, eventAmt);

        for (int i = 0; i < eventAmt; i++) {
            for (String r : eventLimitArr) {
                String uid = (String) redisUtil.get(AdamRedisConst.IDENTITY_MOBILE.concat(r));

                if (StringUtils.isNotEmpty(uid)) {
                    CandyUserCoupon userCoupon = new CandyUserCoupon();
                    userCoupon.setUcouponId(IDGenerator.get32UUID());
                    userCoupon.setMcouponId(mgtCoupon.getMcouponId());
                    userCoupon.setUid(uid);
                    userCoupon.setCouponId(coupon.getCouponId());
                    userCoupon.setState(1);
                    userCoupon.setBindAt(now);
                    userCoupon.setDuedAt(coupon.getExpireAt());

                    initUserCouponList.add(userCoupon);

                    pl++;
                }
            }
        }

        if (!initUserCouponList.isEmpty()) {
            if (platformCandyUserCouponService.saveBatch(initUserCouponList)) {
                initUserCouponList.forEach(r -> {
                    String uckey = CandyRedisConst.BASIC_USER_COUPON.concat(r.getUid());

                    List<CandyUserCouponBasicDto> vos = (List<CandyUserCouponBasicDto>) redisUtil.get(uckey);

                    if (CollectionUtils.isEmpty(vos)) {
                        vos = new ArrayList<>();
                    }
                    vos.add(CandyUserCouponBasicDto.getNew().copy(r, coupon, couponRuleDtoList));

                    redisUtil.set(uckey, vos);
                });
            } else {
                throw new LiquidnetServiceException("-1", String.format("券发放失败[mcouponId=%s]", mgtCoupon.getMcouponId()));
            }
        }
        log.info("发放券处理中:目标指定手机号[总数:{},发放量:{},实际处理:{}]", limitSize, eventAmt, pl);
    }

    /**
     * <p>
     * 发放代金券
     * </p>
     *
     * @param mgtCoupon CandyMgtCoupon
     * @param coupon    CandyCoupon
     */
    public void issueCashCouponHandler(final CandyMgtCoupon mgtCoupon, final CandyCoupon coupon) {
        this.issueCouponProcessing(mgtCoupon, coupon);
    }

    /**
     * <p>
     * 发放满减券
     * </p>
     *
     * @param mgtCoupon CandyMgtCoupon
     * @param coupon    CandyCoupon
     */
    public void issueOverMinusCouponHandler(CandyMgtCoupon mgtCoupon, CandyCoupon coupon) {
        this.issueCouponProcessing(mgtCoupon, coupon);
    }

    /**
     * <p>
     * 发放兑换券
     * </p>
     *
     * @param mgtCoupon CandyMgtCoupon
     * @param coupon    CandyCoupon
     */
    public void issueExchangeCouponHandler(final CandyMgtCoupon mgtCoupon, final CandyCoupon coupon) {
        this.issueCouponProcessing(mgtCoupon, coupon);
    }

    /**
     * <p>
     * 发放折扣券
     * </p>
     *
     * @param mgtCoupon CandyMgtCoupon
     * @param coupon    CandyCoupon
     */
    public void issueDiscountCouponHandler(final CandyMgtCoupon mgtCoupon, final CandyCoupon coupon) {
        this.issueCouponProcessing(mgtCoupon, coupon);
    }
}
