package com.sonic.lion.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sonic.common.utils.DateConvertUtils;
import com.sonic.lion.dao.AccountBuffBillDao;
import com.sonic.lion.dao.BuffRewardRecordDao;
import com.sonic.lion.dao.PayTradeDao;
import com.sonic.lion.domain.entity.BuffRewardRecord;
import com.sonic.lion.domain.entity.PayCharge;
import com.sonic.lion.domain.enums.ProductRewardType;
import com.sonic.lion.service.ActivityService;
import com.sonic.lion.service.PayChargeService;
import com.sonic.lion.service.PayConfigService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private BuffRewardRecordDao buffRewardRecordDao;

    @Autowired
    private AccountBuffBillDao accountBuffBillDao;

    @Autowired
    private PayConfigService payConfigService;

    @Autowired
    private PayTradeDao payTradeDao;
    @Autowired
    private PayChargeService payChargeService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveRecord(BuffRewardRecord buffRewardRecord) {
        buffRewardRecordDao.insert(buffRewardRecord);
    }


    /**
     * 判断某个 session 的版本号是否  大于等于 某个版本
     *
     * @param specifyVersion 某个版本号
     * @param sessionVerison 当前session版本号
     * @return
     */
    public static boolean checkVersion(String sessionVerison, String specifyVersion) {
        if (StringUtils.isBlank(sessionVerison)) {
            return true;
        }
        String[] specifyVersionList = specifyVersion.split("\\.");
        String[] sessionVersionList = sessionVerison.split("\\.");
        if (specifyVersionList.length == 3 && sessionVersionList.length == 3) {
            String s1 = String.format("%02d", Integer.valueOf(specifyVersionList[0])) + String.format("%02d", Integer.valueOf(specifyVersionList[1])) + String.format("%02d", Integer.valueOf(specifyVersionList[2]));
            String s2 = String.format("%02d", Integer.valueOf(sessionVersionList[0])) + String.format("%02d", Integer.valueOf(sessionVersionList[1])) + String.format("%02d", Integer.valueOf(sessionVersionList[2]));
            Integer specifyVersionValue = Integer.valueOf(s1);
            Integer sessionVersionValue = Integer.valueOf(s2);
            return sessionVersionValue >= specifyVersionValue;
        } else {
            return false;
        }
    }

    /**
     * 获取 奖励类型 并领取
     *
     * @param userId
     * @param createTime
     * @param productId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ProductRewardType getRewardTypeByUserId(Long userId, LocalDateTime createTime, String productId, String version) {
        log.info("getRewardTypeByUserId当前版本号{}", version);
        if(!checkVersion(version,"4.18.0")){
            return null;
        }

        if (productId == null) {
            return null;
        }

        //6.23.0 版本新增，老的充值版本没有首冲送buff的逻辑了
        if(LocalDateTime.now().isAfter(LocalDateTime.of(2024, 06, 01, 00, 00, 00))) {
            return null;
        }

        int firstChargeRows = buffRewardRecordDao.selectCount(Wrappers.<BuffRewardRecord>lambdaQuery()
                .eq(BuffRewardRecord::getRewardType, ProductRewardType.FIRST_CHARGE).eq(BuffRewardRecord::getUid, userId)
        );


        /**
         * gg.epal.web_buff_1
         * gg.epal.buff_0002
         * gg.epal.buff_009
         */
        List<String> productList = Lists.newArrayList("gg.epal.web_buff_1", "gg.epal.buff_0002", "gg.epal.buff_009");


        //查询是否有充值过（充值并支付不算）
        int chargeRows = payTradeDao.countAnyChargeOrders(userId);

        //没有领取过 首单奖励 。 而且 当前也没下过单 才可以
        if (chargeRows == 0 && firstChargeRows == 0 && productList.contains(productId) && payConfigService.enableFirstOrderReward()) {
            return ProductRewardType.FIRST_CHARGE;
        }

        //查询当前时间是否有领取过  这个档位的 周五福利。
        int everyFridayRows = buffRewardRecordDao.selectCount(Wrappers.<BuffRewardRecord>lambdaQuery().eq(BuffRewardRecord::getRewardDate, DateConvertUtils.toZone(createTime,"Asia/Shanghai","America/Los_Angeles").toLocalDate())
                .eq(BuffRewardRecord::getRewardType, ProductRewardType.EVERY_FRIDAY).eq(BuffRewardRecord::getUid, userId)
                .eq(BuffRewardRecord::getProductId, productId)
        );


        //没有领取过 可以领取
        if (DayOfWeek.FRIDAY.equals(DateConvertUtils.toZone(createTime,"Asia/Shanghai","America/Los_Angeles").getDayOfWeek()) && everyFridayRows == 0 && payConfigService.enableEveryFridayReward()) {
            return ProductRewardType.EVERY_FRIDAY;
        }
        return null;
    }


    @Override
    public List<String> getRewardTypeByUserIdV2(Long userId, LocalDateTime createTime, List<String> productIdList, String version) {
        if (CollectionUtils.isEmpty(productIdList)) {
            return null;
        }
        //查询出PST本月已使用的商品列表
        Integer yearMonthInt = com.sonic.lion.utils.DateConvertUtils.formatYearMonthToInt(DateConvertUtils.toZone(createTime,"Asia/Shanghai","America/Los_Angeles"));
        //获取本月已使用的大额充值数量
        List<String> usedProductIdList = buffRewardRecordDao.selectList(Wrappers.<BuffRewardRecord>lambdaQuery()
                .select(BuffRewardRecord::getProductId)
                .eq(BuffRewardRecord::getYearMonthInt, yearMonthInt)
                .in(BuffRewardRecord::getProductId, productIdList)
                .eq(BuffRewardRecord::getRewardType, ProductRewardType.LARGE_PRODUCT)
                .eq(BuffRewardRecord::getUid, userId))
                .stream().map(e -> e.getProductId()).collect(Collectors.toList());
        return usedProductIdList;
    }

    @Override
    public PayCharge getRewardTypeByUserIdV2(Long userId, LocalDateTime createTime, String productId, String version) {
        //没有充值档位ID，不能进行赠送，直接快速返回
        if (StringUtils.isEmpty(productId)) {
            return null;
        }
        //查询档位数据是否存在
        PayCharge payCharge = payChargeService.getByProductId(productId);
        if(payCharge == null) {
            return null;
        }
        //没有大额充送类型，不能进行赠送，直接快速返回
        if(!ProductRewardType.LARGE_PRODUCT.name().equals(payCharge.getBizType())) {
            return null;
        }
        //判断PST本月大额充送是否已经使用过，已使用则不能进行赠送，直接快速返回
        Integer yearMonthInt = com.sonic.lion.utils.DateConvertUtils.formatYearMonthToInt(DateConvertUtils.toZone(createTime,"Asia/Shanghai","America/Los_Angeles"));
        //获取本月已使用的大额充值数量
        int useCount = buffRewardRecordDao.selectCount(Wrappers.<BuffRewardRecord>lambdaQuery()
                .select(BuffRewardRecord::getProductId)
                .eq(BuffRewardRecord::getYearMonthInt, yearMonthInt)
                .in(BuffRewardRecord::getProductId, productId)
                .eq(BuffRewardRecord::getRewardType, ProductRewardType.LARGE_PRODUCT)
                .eq(BuffRewardRecord::getUid, userId));
        if(useCount > 0) {
            return null;
        }
        //没有被限制，则返回需要进行赠送的充值档位基础数据
        return payCharge;
    }

}
