package cn.newfeifan.mall.module.distri.service.dailyawardrecords;

import cn.newfeifan.mall.module.distri.controller.admin.integral.vo.IntegralSaveReqVO;
import cn.newfeifan.mall.module.distri.controller.admin.ptprofitlog.vo.PtProfitLogSaveReqVO;
import cn.newfeifan.mall.module.distri.dal.dataobject.integral.IntegralDO;
import cn.newfeifan.mall.module.distri.enums.CaclEnum;
import cn.newfeifan.mall.module.distri.service.integral.IntegralService;
import cn.newfeifan.mall.module.distri.service.ptprofitlog.PtProfitLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import cn.newfeifan.mall.module.distri.controller.admin.dailyawardrecords.vo.*;
import cn.newfeifan.mall.module.distri.dal.dataobject.dailyawardrecords.DailyAwardRecordsDO;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;

import cn.newfeifan.mall.module.distri.dal.mysql.dailyawardrecords.DailyAwardRecordsMapper;

import java.util.List;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.distri.enums.ErrorCodeConstants.*;

/**
 * 每日用户获得合赢奖记录 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class DailyAwardRecordsServiceImpl implements DailyAwardRecordsService {

    @Resource
    private DailyAwardRecordsMapper dailyAwardRecordsMapper;

    @Resource
    private IntegralService integralService;

    @Resource
    private PtProfitLogService ptProfitLogService;

    @Override
    public Long createDailyAwardRecords(DailyAwardRecordsSaveReqVO createReqVO) {
        // 插入
        DailyAwardRecordsDO dailyAwardRecords = BeanUtils.toBean(createReqVO, DailyAwardRecordsDO.class);
        dailyAwardRecordsMapper.insert(dailyAwardRecords);
        // 返回
        return dailyAwardRecords.getId();
    }

    @Override
    public void updateDailyAwardRecords(DailyAwardRecordsSaveReqVO updateReqVO) {
        // 校验存在
        validateDailyAwardRecordsExists(updateReqVO.getId());
        // 更新
        DailyAwardRecordsDO updateObj = BeanUtils.toBean(updateReqVO, DailyAwardRecordsDO.class);
        dailyAwardRecordsMapper.updateById(updateObj);
    }

    @Override
    public void deleteDailyAwardRecords(Long id) {
        // 校验存在
        validateDailyAwardRecordsExists(id);
        // 删除
        dailyAwardRecordsMapper.deleteById(id);
    }

    private void validateDailyAwardRecordsExists(Long id) {
        if (dailyAwardRecordsMapper.selectById(id) == null) {
            throw exception(DAILY_AWARD_RECORDS_NOT_EXISTS);
        }
    }

    @Override
    public DailyAwardRecordsDO getDailyAwardRecords(Long id) {
        return dailyAwardRecordsMapper.selectById(id);
    }

    @Override
    public PageResult<DailyAwardRecordsDO> getDailyAwardRecordsPage(DailyAwardRecordsPageReqVO pageReqVO) {
        return dailyAwardRecordsMapper.selectPage(pageReqVO);
    }

    @Override
    public void addDailyAwardRecords(Long userId, Long generateUserId, Long amount, Long logId, Long accumulatedQuotaAmount) {
        DailyAwardRecordsSaveReqVO createReqVO = DailyAwardRecordsSaveReqVO
                .builder()
                .userId(userId)
                .generateUserId(generateUserId)
                .amount(amount)
                .settled(false)
                .logId(logId)
                .accumulatedQuotaAmount(accumulatedQuotaAmount)
                .build();
        DailyAwardRecordsDO dailyAwardRecords = BeanUtils.toBean(createReqVO, DailyAwardRecordsDO.class);
        dailyAwardRecordsMapper.insert(dailyAwardRecords);
    }

    @Override
    public void transitionBonus() {
        //获取到当前7天前未结算的记录
        LambdaQueryWrapper<DailyAwardRecordsDO> wrapper = new LambdaQueryWrapper<DailyAwardRecordsDO>()
                .eq(DailyAwardRecordsDO::getSettled, false);
                //时间条件暂时关闭,因为现在的计算程序改为即算即用.后续如若改回,打开注释即可
//                .apply("date(create_time) <= DATE_SUB(now(), INTERVAL 7 DAY)");
//                .apply("date(create_time) <= DATE_SUB('2024-06-21', INTERVAL 7 DAY)");

        List<DailyAwardRecordsDO> dailyAwardRecordsSaveReqVOS = dailyAwardRecordsMapper.selectList(wrapper);

        dailyAwardRecordsSaveReqVOS.forEach(dailyAwardRecordsDO -> {
            //获取用户钱包
            IntegralDO integralDO = integralService.getIntegralByUserId(dailyAwardRecordsDO.getUserId());
            //减去待确权
            integralDO.setFreezeQuota(integralDO.getFreezeQuota() - dailyAwardRecordsDO.getAmount());
            //加入可用
            integralDO.setCurrentQuota(integralDO.getCurrentQuota() + dailyAwardRecordsDO.getAmount());
            integralService.updateIntegral(IntegralSaveReqVO.builder()
                    .id(integralDO.getId())
                    .freezeQuota(integralDO.getFreezeQuota())
                    .currentQuota(integralDO.getCurrentQuota())
                    .build());

            PtProfitLogSaveReqVO winWinLog = PtProfitLogSaveReqVO.builder()
                    .profitStatus(CaclEnum.SMALL_QUOTA_CRASH_SETTLE.getType())
                    .userId(dailyAwardRecordsDO.getUserId())
                    .amount(dailyAwardRecordsDO.getAmount())
                    .afterAmount(integralDO.getCurrentQuota())
                    .freezeAmount(-dailyAwardRecordsDO.getAmount())
                    .afterFreezeAmount(integralDO.getFreezeQuota())
                    .generateUserId(dailyAwardRecordsDO.getGenerateUserId())
                    .accumulatedQuotaAmount(dailyAwardRecordsDO.getAccumulatedQuotaAmount())
                    .build();
            ptProfitLogService.createPtProfitLog(winWinLog);

            dailyAwardRecordsDO.setSettled(true);
            dailyAwardRecordsMapper.updateById(dailyAwardRecordsDO);
        });
    }

}