package com.pcloud.book.cultivate.biz.impl;

import com.google.common.collect.Lists;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.cultivate.biz.CultivateBiz;
import com.pcloud.book.cultivate.constant.CultivateConstant;
import com.pcloud.book.cultivate.dao.CultivateDao;
import com.pcloud.book.cultivate.dao.CultivateRecordDao;
import com.pcloud.book.cultivate.dao.CultivateRobotClassifyDao;
import com.pcloud.book.cultivate.dto.*;
import com.pcloud.book.cultivate.entity.Cultivate;
import com.pcloud.book.cultivate.entity.CultivateRecord;
import com.pcloud.book.cultivate.entity.CultivateRobotClassify;
import com.pcloud.book.cultivate.enums.CultivateChangeTypeEnum;
import com.pcloud.book.cultivate.enums.CultivateSkillTypeEnum;
import com.pcloud.book.cultivate.enums.FishBallChangeTypeEnum;
import com.pcloud.book.mq.delay.DelayMessageSender;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotClassifyBiz;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotClassify;
import com.pcloud.book.personal.biz.PersonalMedalBiz;
import com.pcloud.book.personal.dao.PersonalMedalDao;
import com.pcloud.book.personal.dao.PersonalMedalRecordDao;
import com.pcloud.book.personal.dto.PersonalMedalRecordDto;
import com.pcloud.book.personal.dto.PersonalStarReceiveDto;
import com.pcloud.book.personal.entity.PersonalMedal;
import com.pcloud.book.personal.entity.PersonalMedalRecord;
import com.pcloud.book.personal.entity.PersonalShareTemplate;
import com.pcloud.book.personal.mapper.PersonalShareTemplateMapper;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.mq.DelayQueueDTO;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.facade.shareimage.dto.HtmlDto;
import com.pcloud.facade.shareimage.facade.Htm2ImgService;
import com.pcloud.readercenter.wechat.entity.WechatUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component("cultivateBiz")
public class CultivateBizImpl implements CultivateBiz {

    @Autowired
    private CultivateDao cultivateDao;
    @Autowired
    private CultivateRobotClassifyDao cultivateRobotClassifyDao;
    @Autowired
    private DelayMessageSender delayMessageSender;
    @Autowired
    private CultivateRecordDao cultivateRecordDao;

    @Autowired
    private ReaderConsr readerConsr;

    @Autowired
    private PcloudRobotBiz pcloudRobotBiz;
    @Autowired
    private Htm2ImgService htm2ImgService;
    @Autowired
    private PcloudRobotClassifyBiz pcloudRobotClassifyBiz;
    @Autowired
    private PersonalShareTemplateMapper personalShareTemplateMapper;

    @Autowired
    private PersonalMedalDao personalMedalDao;

    @Autowired
    private PersonalMedalRecordDao personalMedalRecordDao;

    @Autowired
    private PersonalMedalBiz personalMedalBiz;






    @Transactional(rollbackFor = Exception.class)
    @ParamLog("新增养成")
    @Override
    public Long createCultivate(CreateCultivateDTO createCultivateDTO) {
        if (createCultivateDTO==null||createCultivateDTO.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"wechatUserId为空！");
        }
        Long wechatUserId=createCultivateDTO.getWechatUserId();
        Cultivate old = cultivateDao.getByWechatUserId(wechatUserId);
        if (old!=null){
            throw new BookBizException(BookBizException.ERROR,"已有养成！");
        }
        Cultivate cultivate=new Cultivate();
        cultivate.setEnergy(CultivateConstant.INITIAL_ENERGY);
        cultivate.setStar(CultivateConstant.INITIAL_STAR);
        cultivate.setWechatUserId(wechatUserId);
        cultivate.setLighten(false);
        cultivate.setFishBall(0);
        cultivateDao.insert(cultivate);
        return cultivate.getId();
    }

    @ParamLog("获取养成")
    @Override
    public Cultivate getCultivate(Long wechatUserId) {
        if (wechatUserId==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"wechatUserId为空！");
        }
        Cultivate cultivate = cultivateDao.getByWechatUserId(wechatUserId);
        //TODO 计算等级勋章等，获取用户基本信息等
        return cultivate;
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("新增养成分类关联")
    @Override
    public void createCultivateRobotClassify(CultivateRobotClassify cultivateRobotClassify) {
        if (cultivateRobotClassify==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"cultivateRobotClassify为空！");
        }
        if (cultivateRobotClassify.getCultivateId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"cultivateId为空！");
        }
        if (cultivateRobotClassify.getRobotClassifyId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"robotClassifyId为空！");
        }
        if (cultivateRobotClassify.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"用户id为空！");
        }
        //查询之前是否有
        CultivateRobotClassify byCondition = cultivateRobotClassifyDao.getByCondition(cultivateRobotClassify.getWechatUserId(), cultivateRobotClassify.getCultivateId(), cultivateRobotClassify.getRobotClassifyId());
        if (byCondition!=null){
            return;
        }
        cultivateRobotClassifyDao.insert(cultivateRobotClassify);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("能量消耗")
    @Override
    public void energyConsumption(EnergyConsumptionDTO energyConsumptionDTO) {
        if (energyConsumptionDTO==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"energyConsumptionDTO为空！");
        }
        if (energyConsumptionDTO.getCultivateId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成id为空！");
        }
        if (energyConsumptionDTO.getEnergy()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"能量为空！");
        }
        if (energyConsumptionDTO.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"用户id为空！");
        }
        Long wechatUserId=energyConsumptionDTO.getWechatUserId();
        Long cultivateId=energyConsumptionDTO.getCultivateId();
        Cultivate cultivate = cultivateDao.getById(cultivateId);
        if (cultivate==null){
            throw new BookBizException(BookBizException.ERROR,"没有养成！");
        }
        if (cultivate.getEnergy()<energyConsumptionDTO.getEnergy()){
            throw new BookBizException(BookBizException.ERROR,"能量不足，当前只有"+cultivate.getEnergy()+"能量");
        }
        cultivate.setEnergy(cultivate.getEnergy()-energyConsumptionDTO.getEnergy());
        //新增能量消耗记录
        CultivateRecord addEnergyRecord=new CultivateRecord();
        addEnergyRecord.setEnergyChange(-energyConsumptionDTO.getEnergy());
        addEnergyRecord.setCultivateId(cultivateId);
        addEnergyRecord.setChangeType(CultivateChangeTypeEnum.USE_ENERGY.code);
        addEnergyRecord.setWechatUserId(wechatUserId);
        Long recordId=createCultivateRecord(addEnergyRecord);
        if (!cultivate.getLighten()){
            //熄灭状态
            cultivate.setLighten(true);
            //加延时队列，到点熄灯，新增点亮记录
            addDelayEnergyConsumption(recordId,wechatUserId,energyConsumptionDTO.getEnergy());
            //新增点亮记录
            CultivateRecord liRecord=new CultivateRecord();
            liRecord.setWechatUserId(wechatUserId);
            liRecord.setCultivateId(cultivateId);
            liRecord.setChangeType(CultivateChangeTypeEnum.LIGHTEN.code);
            liRecord.setWechatUserId(wechatUserId);
            createCultivateRecord(liRecord);
        }
        cultivateDao.update(cultivate);
    }

    private void addDelayEnergyConsumption(Long cultivateRecordId,Long wechatUserId,Integer energy){
        EnergyConsumptionDelayDTO energyConsumptionDelayDTO=new EnergyConsumptionDelayDTO();
        energyConsumptionDelayDTO.setCultivateRecordId(cultivateRecordId);
        energyConsumptionDelayDTO.setEnergy(energy);
        DelayQueueDTO delayQueueDTONew = DelayQueueDTO.builder().key(wechatUserId.toString()).type(CultivateConstant.ENERGY_CONSUMPTION_DELAY).msg(energyConsumptionDelayDTO).timeout(energy*60*1000).build();
        delayMessageSender.send(delayQueueDTONew);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("能量消耗延时处理")
    @Override
    public void dealDelayEnergyConsumption(DelayQueueDTO delayQueueDTO) {
        Long wechatUserId=new Long(delayQueueDTO.getKey());
        EnergyConsumptionDelayDTO consumptionDelayDTO= (EnergyConsumptionDelayDTO) delayQueueDTO.getMsg();
        Long recordId=consumptionDelayDTO.getCultivateRecordId();
        CultivateRecord cultivateRecord = cultivateRecordDao.getById(recordId);
        //判断该记录之前还有没有能量消耗，如果有继续点亮，如果没有，熄灯
        Integer afterEnergy = cultivateRecordDao.getEnergyConsumptionAfter(cultivateRecord.getId(), wechatUserId);
        Long cultivateId=cultivateRecord.getCultivateId();
        if (afterEnergy>0){
            //继续点亮，重新加延时队列
            CultivateRecord last=cultivateRecordDao.getLastEnergyConsumptionRecord(wechatUserId,cultivateId);
            addDelayEnergyConsumption(last.getId(),wechatUserId,afterEnergy);
        } else {
            //熄灯，收取鱼丸
            Cultivate cultivate=cultivateDao.getById(cultivateId);
            cultivate.setLighten(false);
            //查询用户点灯之后收取过的鱼丸数量
            Integer userGatherFishBall=cultivateRecordDao.getUserGatherFishBallCount(wechatUserId,cultivateId);
            //系统收取鱼丸
            Integer allEnergy=0;
            CultivateRecord lastLighten = cultivateRecordDao.getLastLighten(wechatUserId, cultivateId);
            if (lastLighten!=null){
                //获取点灯之前的最后一次消耗能量记录
                CultivateRecord consumptionBefore =cultivateRecordDao.getLastEnergyConsumptionBefore(lastLighten.getId(),wechatUserId);
                if (consumptionBefore!=null){
                    Integer consumptionAfter = cultivateRecordDao.getEnergyConsumptionAfter(lastLighten.getId(), wechatUserId);
                    allEnergy=-consumptionBefore.getEnergyChange()+consumptionAfter;
                }
            }
            Integer currentAdd=allEnergy-userGatherFishBall;
            cultivate.setFishBall(cultivate.getFishBall()+currentAdd);
            //产生收鱼丸记录
            CultivateRecord hasFishBall=new CultivateRecord();
            hasFishBall.setCultivateId(cultivateId);
            hasFishBall.setWechatUserId(wechatUserId);
            hasFishBall.setChangeType(CultivateChangeTypeEnum.GET_FISH_BALL.code);
            hasFishBall.setFishBallChangeType(FishBallChangeTypeEnum.AUTO_CHANGE.value);
            hasFishBall.setFishBallChange(currentAdd);
            createCultivateRecord(hasFishBall);
            //熄灯,产生一条熄灯记录
            CultivateRecord quench=new CultivateRecord();
            quench.setWechatUserId(wechatUserId);
            quench.setCultivateId(cultivateId);
            quench.setChangeType(CultivateChangeTypeEnum.QUENCH.code);
            createCultivateRecord(quench);
            cultivateDao.update(cultivate);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("鱼丸兑换")
    @Override
    public void fishBallConversion(FishBallConversionDTO fishBallConversionDTO) {
        if (fishBallConversionDTO==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"fishBallConversionDTO为空！");
        }
        if (fishBallConversionDTO.getCultivateId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成id为空！");
        }
        if (fishBallConversionDTO.getFishBall()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"鱼丸为空！");
        }
        if (fishBallConversionDTO.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"用户id为空！");
        }
        Long wechatUserId=fishBallConversionDTO.getWechatUserId();
        Cultivate cultivate = cultivateDao.getById(fishBallConversionDTO.getCultivateId());
        if (cultivate==null){
            throw new BookBizException(BookBizException.ERROR,"没有养成！");
        }
        if (cultivate.getFishBall()<fishBallConversionDTO.getFishBall()){
            throw new BookBizException(BookBizException.ERROR,"鱼丸不足，当前只有"+cultivate.getFishBall()+"鱼丸");
        }
        if (fishBallConversionDTO.getFishBall()%100!=0){
            throw new BookBizException(BookBizException.ERROR,"请使用100的倍数");
        }

        //插入鱼丸兑换记录
        CultivateRecord convertFishBall=new CultivateRecord();
        convertFishBall.setWechatUserId(wechatUserId);
        convertFishBall.setChangeType(CultivateChangeTypeEnum.FISH_BALL_CONVERT_STAR.code);
        convertFishBall.setCultivateId(fishBallConversionDTO.getCultivateId());
        convertFishBall.setFishBallChange(-fishBallConversionDTO.getFishBall());
        convertFishBall.setStarChange(fishBallConversionDTO.getFishBall()/100);
        createCultivateRecord(convertFishBall);
        //先插入记录在更新养成表星星数
        cultivate.setFishBall(cultivate.getFishBall()-fishBallConversionDTO.getFishBall());
        cultivate.setStar(cultivate.getStar()+fishBallConversionDTO.getFishBall()/100);
        cultivateDao.update(cultivate);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("插入成长动态记录")
    @Override
    public Long createCultivateRecord(CultivateRecord cultivateRecord) {
        if (cultivateRecord==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"cultivateRecord为空！");
        }
        if (cultivateRecord.getCultivateId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成id为空！");
        }
        if (cultivateRecord.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"用户id为空！");
        }
        if (cultivateRecord.getChangeType()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"动态类型为空！");

        }
        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.GET_FISH_BALL.code)){
            if (cultivateRecord.getFishBallChange()==null){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"鱼丸数为空！");

            }
            if (cultivateRecord.getFishBallChangeType()==null){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"鱼丸变化类型为空！");

            }
            cultivateRecord.setRemark("获得了"+cultivateRecord.getFishBallChange()+"个鱼丸");
        }
        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.LIGHTEN.code)){

            cultivateRecord.setRemark("灯已点亮，我有吃的了！");
        }
        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.QUENCH.code)){

            cultivateRecord.setRemark("灯已熄灭,我看不见了小主，点亮我吧！");
        }

        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.USE_ENERGY.code)){
            if(cultivateRecord.getEnergyChange()==null){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"能量值为空！");
            }
            Integer hour=(-cultivateRecord.getEnergyChange())/60;
            Integer min=(-cultivateRecord.getEnergyChange())%60;
            if(hour>0) {
                cultivateRecord.setRemark("你已使用" + (-cultivateRecord.getEnergyChange()) + "能量值点亮" + hour + "小时" + min + "分钟");
            }else{
                cultivateRecord.setRemark("你已使用" + (-cultivateRecord.getEnergyChange()) + "能量值点亮" + min + "分钟");
            }
        }

        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.USE_SKILL.code)){
            if(cultivateRecord.getSkillType()==null){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"技能类型为空！");
            }
            String skill=CultivateSkillTypeEnum.getNameByCode(cultivateRecord.getSkillType());

            cultivateRecord.setRemark("你使用了"+skill+"技能,请添加小睿为好友后，回复您想");
        }

        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.FISH_BALL_CONVERT_STAR.code)){
            if(cultivateRecord.getStarChange()==null){
                throw new BookBizException(BookBizException.PARAM_IS_NULL,"星星数量为空！");
            }
            cultivateRecord.setRemark("你已将"+cultivateRecord.getStarChange()*100+"个鱼丸兑换了"+cultivateRecord.getStarChange()+"颗星");
        }
        cultivateRecordDao.insert(cultivateRecord);
        if(cultivateRecord.getChangeType().equals(CultivateChangeTypeEnum.FISH_BALL_CONVERT_STAR.code)){
            Cultivate cultivate = cultivateDao.getByWechatUserId(cultivateRecord.getWechatUserId());
            Boolean isUp= isUpGrade(cultivate.getStar(),cultivate.getStar()+cultivateRecord.getStarChange());
            Integer  newStarCount=cultivate.getStar()+cultivateRecord.getStarChange();
            if(isUp){
                //插入升级记录
                CultivateRecord upGradeRecord=new CultivateRecord();
                upGradeRecord.setWechatUserId(cultivateRecord.getWechatUserId());
                upGradeRecord.setChangeType(CultivateChangeTypeEnum.UPGRADE.code);
                upGradeRecord.setCultivateId(cultivate.getId());
                //插入领取的勋章
                // 获取用户的星星数
                Integer starCount =cultivate.getStar()+cultivateRecord.getStarChange();
                // 查询当前数量的星星可以领取的勋章(过滤掉已领取的)
                List<Long> medalIds = personalMedalDao.getReceivingMedal(cultivateRecord.getWechatUserId(), starCount);
                if(!ListUtils.isEmpty(medalIds)){
                    // 插入可以领取的记录
                    PersonalMedalRecord medalRecord;
                    for (Long medalId : medalIds){
                        medalRecord = new PersonalMedalRecord();
                        medalRecord.setMedalId(medalId);
                        medalRecord.setWechatUserId(cultivateRecord.getWechatUserId());
                        medalRecord.setHasShow(YesOrNoEnums.YES.getValue());
                        // 插入领取记录
                        personalMedalRecordDao.insert(medalRecord);
                    }
                }
                if(CultivateConstant.second_MEDAL_STAR<=newStarCount&&newStarCount<CultivateConstant.third_MEDAL_STAR) {
                    upGradeRecord.setRemark("已成功升级LV2学有小成");
                }
                if(CultivateConstant.third_MEDAL_STAR<=newStarCount&&newStarCount<CultivateConstant.fourth_MEDAL_STAR) {
                    upGradeRecord.setRemark("已成功升级LV3渐入佳境");
                }
                if(CultivateConstant.fourth_MEDAL_STAR<=newStarCount&&newStarCount<CultivateConstant.fifth_MEDAL_STAR) {
                    upGradeRecord.setRemark("已成功升级LV4炉火纯青");
                }
                if(CultivateConstant.fifth_MEDAL_STAR<=newStarCount&&newStarCount<CultivateConstant.sixth_MEDAL_STAR) {
                    upGradeRecord.setRemark("已成功升级LV5学识渊博");
                }
                if(CultivateConstant.sixth_MEDAL_STAR<=newStarCount) {
                    upGradeRecord.setRemark("已成功升级LV6学亘古今");
                }
                cultivateRecordDao.insert(upGradeRecord);

            }


        }
        return cultivateRecord.getId();
    }



    @Override
    public void addUseSkillRecord(Long wechatUserId, SkillUseDTO skillUseDTO) {
        CultivateRecord cultivateRecord=new CultivateRecord();
        cultivateRecord.setChangeType(CultivateChangeTypeEnum.USE_SKILL.code);
        cultivateRecord.setCultivateId(skillUseDTO.getCultivateId());
        cultivateRecord.setSkillType(skillUseDTO.getSkillType());
        cultivateRecord.setWechatUserId(wechatUserId);
        createCultivateRecord(cultivateRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("鱼丸摘取")
    @Override
    public void fishBallPick(FishBallPickDTO fishBallPickDTO) {
        if (fishBallPickDTO==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"鱼丸摘取参数为空！");
        }
        if (fishBallPickDTO.getCultivateId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成Id为空！");
        }
        if (fishBallPickDTO.getFishBall()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"鱼丸数量为空！");
        }
        if (fishBallPickDTO.getWechatUserId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"用户id为空！");
        }
        Long wechatUserId=fishBallPickDTO.getWechatUserId();
        Long cultivateId=fishBallPickDTO.getCultivateId();
        Cultivate cultivate = cultivateDao.getById(cultivateId);
        if (cultivate==null){
            throw new BookBizException(BookBizException.ERROR,"没有该养成！");
        }
        Integer notPick = getFishBallNotPick(cultivateId);
        if (notPick<=0){
            throw new BookBizException(BookBizException.ERROR,"没有可摘取的鱼丸！");
        }
        cultivate.setFishBall(cultivate.getFishBall()+fishBallPickDTO.getFishBall());
        cultivateDao.update(cultivate);
        CultivateRecord cultivateRecord=new CultivateRecord();
        cultivateRecord.setWechatUserId(wechatUserId);
        cultivateRecord.setCultivateId(cultivateId);
        cultivateRecord.setChangeType(CultivateChangeTypeEnum.GET_FISH_BALL.code);
        cultivateRecord.setFishBallChangeType(FishBallChangeTypeEnum.USER_CHANGE.value);
        cultivateRecord.setFishBallChange(fishBallPickDTO.getFishBall());
        createCultivateRecord(cultivateRecord);
    }

    @ParamLog("获取现有未摘取鱼丸")
    @Override
    public Integer getFishBallNotPick(Long cultivateId) {
        if (cultivateId==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成id为空！");
        }
        Cultivate cultivate = cultivateDao.getById(cultivateId);
        Long wechatUserId=cultivate.getWechatUserId();
        if (cultivate==null){
            throw new BookBizException(BookBizException.ERROR,"没有该养成！");
        }
        //熄灭状态
        if (!cultivate.getLighten()){
            return 0;
        }
        //查询上次点亮之后到现在的时间
        CultivateRecord lastLighten=cultivateRecordDao.getLastLighten(wechatUserId,cultivateId);
        if (lastLighten==null){
            return 0;
        }
        //一共产生的鱼丸
        Integer proFishBall=(int)(new Date().getTime()-lastLighten.getCreateTime().getTime())/1000/60;
        //点亮期间已经摘取过的语言
        Integer gatherFishBallCount = cultivateRecordDao.getUserGatherFishBallCount(wechatUserId, cultivateId);
        return proFishBall-gatherFishBallCount;
    }

    @Override
    public PageBeanNew<CultivateRecord> getCultivateRecordList(Long cultivateId, Long wechatUserId, Integer currentPage, Integer numPerPage) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("cultivateId", cultivateId);
        paramMap.put("wechatUserId", wechatUserId);
        PageBeanNew<CultivateRecord> pageBeanNew=cultivateRecordDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "getCultivateRecordList");
        if (pageBeanNew == null || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, new ArrayList<>());
        }
        return pageBeanNew;
    }

    @Override
    public Long getLoginDays(Long wechatUserId) {
        WechatUser wechatUser = readerConsr.getWechatUser(wechatUserId);
        Long dateDiff = DateUtils.getDateDiff(wechatUser.getCreatedDate(), new Date());
        if(dateDiff==0){
            return 1L;
        }
        return dateDiff;
    }

    @Override
    public Integer getRanking(Long wechatUserId) {


        Integer ranking=0;
        List<Cultivate> list= cultivateDao.getAllOrderByStar();
        if(list==null||list.size()==0){
            return ranking;
        }

        for (int i=0;i<=list.size()-1;i++){
            Cultivate cultivate = list.get(i);
            if(cultivate.getWechatUserId().equals(wechatUserId)){
                ranking=i+1;
                return ranking;
            }
        }

        return ranking;
    }

    @Override
    @ParamLog("获取用户已获得勋章数据")
    public List<PersonalMedalRecordDto> getUserMedalList(Long wechatUserId) {
        List<PersonalMedalRecordDto> userMedalList = personalMedalRecordDao.getUserMedalList(wechatUserId);
        if(ListUtils.isEmpty(userMedalList)){
            return Lists.newArrayList();
        }
        return userMedalList;
    }

    @ParamLog("获取剩余亮灯时间")
    @Override
    public Integer getResidueLightTime(Long cultivateId) {
        if (cultivateId==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"养成id不能为空！");
        }
        //查询上次亮灯时间和亮灯之后的兑换的能量
        Cultivate cultivate = cultivateDao.getById(cultivateId);
        if (cultivate==null||!cultivate.getLighten()){
            return 0;
        }
        Long wechatUserId=cultivate.getWechatUserId();
        CultivateRecord lastLighten = cultivateRecordDao.getLastLighten(wechatUserId, cultivateId);
        if (lastLighten==null){
            return 0;
        }
        //获取点灯之前的最后一次消耗能量记录
        CultivateRecord consumptionBefore =cultivateRecordDao.getLastEnergyConsumptionBefore(lastLighten.getId(),wechatUserId);
        if (consumptionBefore==null){
            return 0;
        }
        Integer consumptionAfter = cultivateRecordDao.getEnergyConsumptionAfter(lastLighten.getId(), wechatUserId);
        Integer allEnergy=-consumptionBefore.getEnergyChange()+consumptionAfter;
        Integer time=allEnergy*60-(int)(new Date().getTime()-lastLighten.getCreateTime().getTime())/1000;
        if (time<=0){
            return 0;
        }
        return time;
    }

    @Override
    @ParamLog("分享")
    public String shareMedal(Long wechatUserId) {
        // 获取用户基本信息
        WechatUser wechatUser = readerConsr.getWechatUser(wechatUserId);
        Long loginDays =  getLoginDays(wechatUserId);
        List<PersonalMedal> baseMedalList = personalMedalBiz.getBaseMedalList();
        List<PersonalMedalRecordDto> personalMedalRecordDtos = new ArrayList<>();
        // TODO 换小程序二维码图片地址
        String projectQrcodeUrl="https://file.5rs.me/oss/uploadfe/jpg/5e586c6176e13b8806736581b9f641a0.jpg";
        //根据星星数获取勋章图片信息
        Cultivate cultivate = cultivateDao.getByWechatUserId(wechatUserId);
        if(CultivateConstant.FIRST_MEDAL_STAR<=cultivate.getStar()&&cultivate.getStar()<CultivateConstant.second_MEDAL_STAR) {
            PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
            personalMedalRecordDto.setBigImgUrl(baseMedalList.get(0).getBigImgUrl());
            personalMedalRecordDtos.add(personalMedalRecordDto);
        }
        if(CultivateConstant.second_MEDAL_STAR<=cultivate.getStar()&&cultivate.getStar()<CultivateConstant.third_MEDAL_STAR) {
            for (int i=0;i<2 ;i++) {
                PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
                personalMedalRecordDto.setLightImgUrl(baseMedalList.get(i).getLightImgUrl());
                personalMedalRecordDtos.add(personalMedalRecordDto);
            }
        }
        if(CultivateConstant.third_MEDAL_STAR<=cultivate.getStar()&&cultivate.getStar()<CultivateConstant.fourth_MEDAL_STAR) {
            for (int i=0;i<3 ;i++) {
                PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
                personalMedalRecordDto.setLightImgUrl(baseMedalList.get(i).getLightImgUrl());
                personalMedalRecordDtos.add(personalMedalRecordDto);
            }
        }
        if(CultivateConstant.fourth_MEDAL_STAR<=cultivate.getStar()&&cultivate.getStar()<CultivateConstant.fifth_MEDAL_STAR) {
            for (int i=0;i<4 ;i++) {
                PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
                personalMedalRecordDto.setLightImgUrl(baseMedalList.get(i).getLightImgUrl());
                personalMedalRecordDtos.add(personalMedalRecordDto);
            }
        }
        if(CultivateConstant.fifth_MEDAL_STAR<=cultivate.getStar()&&cultivate.getStar()<CultivateConstant.sixth_MEDAL_STAR) {
            for (int i=0;i<5 ;i++) {
                PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
                personalMedalRecordDto.setLightImgUrl(baseMedalList.get(i).getLightImgUrl());
                personalMedalRecordDtos.add(personalMedalRecordDto);
            }
        }
        if(CultivateConstant.fifth_MEDAL_STAR<=cultivate.getStar()) {
            for (int i=0;i<6 ;i++) {
                PersonalMedalRecordDto personalMedalRecordDto=new PersonalMedalRecordDto();
                personalMedalRecordDto.setLightImgUrl(baseMedalList.get(i).getLightImgUrl());
                personalMedalRecordDtos.add(personalMedalRecordDto);
            }
        }
        if(wechatUser == null){
            throw new BizException(BizException.DB_DML_FAIL.getCode(), "未找到用户信息");
        }


        String html = null;
        if (personalMedalRecordDtos.size() == 1){
            //只生成大图
            html = buildMedalHtml4Big(personalMedalRecordDtos.get(0), wechatUser, projectQrcodeUrl,loginDays);
        }else {
            //多个小图
            html = buildMedalHtml4Little(personalMedalRecordDtos, wechatUser, projectQrcodeUrl,loginDays);
        }
        HtmlDto htmlDto=new HtmlDto();
        htmlDto.setHeight(1206);
        htmlDto.setWidth(750);
        htmlDto.setHtmlCode(html);
        htmlDto.setSnapshot(new Long(System.currentTimeMillis()).toString());
        return ResponseHandleUtil.parseResponse(htm2ImgService.toJPGByChrome(htmlDto),String.class);
    }

    private String buildMedalHtml4Little(List<PersonalMedalRecordDto> personalMedalRecordDtos, WechatUser wechatUser, String projectQrcodeUrl, Long loginDays) {
        PersonalShareTemplate personalShareTemplate = personalShareTemplateMapper.selectByPrimaryKey(2);
        String html = personalShareTemplate.getContent();
        html = html.replace("${headUrl}",wechatUser.getWechatUserHeadurl());
        html = html.replace("${nickName}",wechatUser.getWechatUserNickname());
        html = html.replace("${loginDays}",loginDays.toString());
        html = html.replace("${classifyQrcode}",projectQrcodeUrl);
        html = html.replace("${medalCount}",personalMedalRecordDtos.size()+"");
        String medalImg = "";
        for(PersonalMedalRecordDto personalMedalRecordDto : personalMedalRecordDtos){
            medalImg +=  "<img src='"+personalMedalRecordDto.getLightImgUrl()+"'class=\"medal\" />";
        }
        html = html.replace("${medalImgs}",medalImg);
        return  html;
    }

    private String buildMedalHtml4Big(PersonalMedalRecordDto personalMedalRecordDto, WechatUser wechatUser,String projectQrcodeUrl, Long loginDays) {
        PersonalShareTemplate personalShareTemplate = personalShareTemplateMapper.selectByPrimaryKey(1);
        String html = personalShareTemplate.getContent();
        html = html.replace("${headUrl}",wechatUser.getWechatUserHeadurl());
        html = html.replace("${nickName}",wechatUser.getWechatUserNickname());
        html = html.replace("${loginDays}",loginDays.toString());
        html = html.replace("${classifyQrcode}",projectQrcodeUrl);
        return  html;
    }

    @ParamLog("鱼丸兑换后是否升级")
    private Boolean isUpGrade(Integer oldStarCounts,Integer newStarCounts){
        if(CultivateConstant.FIRST_MEDAL_STAR<=oldStarCounts&&oldStarCounts<CultivateConstant.second_MEDAL_STAR&&newStarCounts>=CultivateConstant.second_MEDAL_STAR) {
           return true;

        }
        if(CultivateConstant.second_MEDAL_STAR<=oldStarCounts&&oldStarCounts<CultivateConstant.third_MEDAL_STAR&&newStarCounts>=CultivateConstant.third_MEDAL_STAR) {
            return true;
        }
        if(CultivateConstant.third_MEDAL_STAR<=oldStarCounts&&oldStarCounts<CultivateConstant.fourth_MEDAL_STAR&&newStarCounts>=CultivateConstant.fourth_MEDAL_STAR) {
            return true;
        }
        if(CultivateConstant.fourth_MEDAL_STAR<=oldStarCounts&&oldStarCounts<CultivateConstant.fifth_MEDAL_STAR&&newStarCounts>=CultivateConstant.fifth_MEDAL_STAR) {
            return true;
        }
        if(CultivateConstant.fifth_MEDAL_STAR<=oldStarCounts&&oldStarCounts<CultivateConstant.sixth_MEDAL_STAR&&newStarCounts>=CultivateConstant.sixth_MEDAL_STAR) {
            return true;
        }
        return false;
    }


}
