package com.jeequan.jeepay.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.db.entity.MchVideoCacheEntity;
import com.jeequan.jeepay.service.mapper.MchVideoCacheMapper;
import org.springframework.stereotype.Service;

@Service
public class MchVideoCacheService extends ServiceImpl<MchVideoCacheMapper, MchVideoCacheEntity> {

    public MchVideoCacheEntity getRandomOne(String mchNo) {
        long count = lambdaQuery()
                .eq(MchVideoCacheEntity::getMchNo, mchNo)
                .eq(MchVideoCacheEntity::getChoiceFlag, "1")
                .count();
        if (count == 0) {
            return null;
        }
        long randomIndex = RandomUtil.randomNumber() % count;
        MchVideoCacheEntity result = lambdaQuery().eq(MchVideoCacheEntity::getMchNo, mchNo)
                .eq(MchVideoCacheEntity::getChoiceFlag, "1")
                .last("order by id desc limit 1 offset "+ randomIndex)
                .one();
        return result;
    }

    public JSONObject getRandomOneVo(String mchNo) {
        MchVideoCacheEntity randomOne = getRandomOne(mchNo);
        if(randomOne != null){
            JSONObject result = new JSONObject();
            result.put("exportId",randomOne.getExportId());
            result.put("uniqueId",randomOne.getUniqueId());
            return result;
        }
        return null;
    }
}
