package com.fs.qw;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.qw.service.IQwWorkTaskService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.util.Asserts;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 后台统计相关 定时任务
 */
@Slf4j
@Service("qwFsCourseTask")
public class FsCourseTask {
    @Autowired
    private IFsCourseWatchLogService fsCourseWatchLogService;
    @Autowired
    private IQwWorkTaskService qwWorkTaskService;
    @Autowired
    private RedisCache redisCache;
    private static final String REDPACKET_COMPANY_MONEY_CHANGE = "redpacket_money_CHANGE";
    @Autowired
    private SysConfigMapper sysConfigMapper;
    private static final String REDPACKET_POOL_LOCK = "redpacket_pool_lock";
    private static final String REDPACKET_COMPANY_MONEY = "redpacket_money";

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 润天公司账户充值
     * @param chargeMoney 充值金额
     */
    public void rechargeRedpacketMoney(String chargeMoney){
        Assert.notNull(chargeMoney,"充值金额不能为空!");

        log.info("润天公司账户充值 充值金额: {}",chargeMoney);

        RLock lock = redissonClient.getLock(REDPACKET_POOL_LOCK);
        try{
            boolean locked = lock.tryLock(3, 10, TimeUnit.SECONDS);

            if (!locked) {
                log.error("获取锁失败...");
                return;
            }

            BigDecimal redPacketCompanyMoney = redisCache.getCacheObject(REDPACKET_COMPANY_MONEY);
            if(ObjectUtils.isNull(redPacketCompanyMoney)){
                redPacketCompanyMoney = BigDecimal.ZERO;
            }
            BigDecimal value = redPacketCompanyMoney.add(new BigDecimal(chargeMoney));

            log.info("润天公司账户充值成功 目前余额: {}",value);

            redisCache.setCacheObject(REDPACKET_COMPANY_MONEY,value);


            // 保存到数据库
            SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("company.money");

            sysConfig.setConfigValue(value.setScale(4, RoundingMode.HALF_UP).toPlainString());
            sysConfig.setConfigKey("company.money");
            sysConfigMapper.updateConfig(sysConfig);

        }catch (Exception e){
            log.error("充值失败 原因：{}", ExceptionUtils.getMessage(e),e);
            throw new RuntimeException(e);
        }finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
    /**
     * 公司红包金额变更
     */
    public void redpacketCompanyMoneyChange(){
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("company.money");
        Asserts.notNull(sysConfig,"公司账户配置不能为空!");

        String configValue = sysConfig.getConfigValue();
        Asserts.notNull(configValue,"公司账户余额不能为空");

        BigDecimal oldBigDecimal = new BigDecimal(configValue);

        BigDecimal redPacketCompanyMoney = redisCache.getCacheObject(REDPACKET_COMPANY_MONEY);

        log.info("公司账户红包余额变更 {} -> {}",oldBigDecimal,redPacketCompanyMoney);

        // 如果两者不一致才同步到数据库
        if(oldBigDecimal.compareTo(redPacketCompanyMoney) != 0){
            sysConfig.setConfigValue(redPacketCompanyMoney.setScale(4, RoundingMode.HALF_UP).toPlainString());
            sysConfig.setConfigKey("company.money");
            sysConfigMapper.updateConfig(sysConfig);
        }
    }
    /**
     * 添加企微观看日志
     * @throws Exception
     */
    public void addQwWatchLog() throws Exception
    {
        fsCourseWatchLogService.addCourseWatchLogDay();
    }

    /**
     * 企微任务定时更新
     * @throws Exception
     */
    public void qwWorkTask1() throws Exception
    {
        qwWorkTaskService.addQwWorkByCourse4();
        qwWorkTaskService.addQwWorkByCourseLastTime();
    }
    /**
     * 企微待看课和先导课
     * @throws Exception
     */
    public void qwWorkTask2() throws Exception
    {
        qwWorkTaskService.addQwWorkByCourse();
        qwWorkTaskService.addQwWorkByFirstCourse();
    }
    /**
     * 用户大小转
     * @throws Exception
     */
    public void qwWorkTask3() throws Exception
    {
        qwWorkTaskService.addQwWorkByConversionDay();
    }
    /**
     * 删除过期数据
     * @throws Exception
     */
    public void qwWorkTask4() throws Exception
    {
        qwWorkTaskService.delQwWorkTaskByOver();
    }

}
