package com.ssj.service.conch.conch.service.impl;

import com.ssj.bean.conch.conch.domain.HomeworkRanking;
import com.ssj.bean.conch.conch.domain.IntegralDetail;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.dao.conch.conch.dao.HomeworkRankingDao;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.conch.conch.dto.HomeworkRankingDto;
import com.ssj.service.conch.conch.dto.RankDTO;
import com.ssj.service.conch.conch.service.HomeworkRankingService;
import com.ssj.service.conch.conch.service.IntegralDetailService;
import com.ssj.service.kmt.service.KmtHomeworkWrongQuestionService;
import com.ssj.service.mapper.HomeworkMapper;
import com.ssj.service.weixin.library.service.ILibVipService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author yrf
 * @date 2019/4/26 10:59
 */
@Service
@Transactional
public class HomeworkRankingServiceImpl extends BaseServiceImpl<HomeworkRanking, String> implements HomeworkRankingService {

    @Autowired
    private HomeworkRankingDao homeworkRankingDao;
    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private KmtHomeworkWrongQuestionService kmtHomeworkWrongQuestionService;
    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private IntegralDetailService integralDetailService;
    @Autowired
    private ILibVipService vipService;

    @Override
    public PagingAndSortingRepository<HomeworkRanking, String> getDao() {
        return homeworkRankingDao;
    }

    @Override
    public int computeAndSaveIntegralByHomeworkUseTime(String vipId, String homeworkId, Long usedTime,String subject) {
        if (usedTime == null) {
            //未计时
            return 0;
        }
        //小于5分钟或大于等于50分钟记0分
        int integral = 0;
        if (5 < usedTime && usedTime <= 50) {
            if (usedTime <= 20) {
                integral = 3;
            } else if (usedTime <= 30) {
                integral = 2;
            } else {
                integral = 1;
            }
        }
        return this.saveRankIntegral(vipId, integral,1,subject);
    }

    @Override
    public void computeAndSaveIntegralByHomeworkCorrectRate(String vipId, double homeworkCorrectRate, String subject) {
        int integral = 0;
        if (homeworkCorrectRate >= 0.9) {
            integral = 5;
        } else if (homeworkCorrectRate >= 0.8) {
            integral = 3;
        } else if (homeworkCorrectRate >= 0.7) {
            integral = 2;
        } else if (homeworkCorrectRate >= 0.5) {
            integral = 1;
        }

        if (integral > 0) {
            this.saveRankIntegral(vipId, integral, 2, subject);
        }
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public RankDTO findByDerver(String derver) {
        if (StringUtils.isBlank(derver)) {
            return null;
        }

        List<Object []> tempResult = homeworkRankingDao.findByDerver(derver);
        if (tempResult.size() > 0) {
            RankDTO rankDTO = new RankDTO();
            rankDTO.setUserName(String.valueOf(tempResult.get(0)[0]));
            rankDTO.setImgUrl(String.valueOf(tempResult.get(0)[1]));
            rankDTO.setRankingNum((Integer) tempResult.get(0)[2]);
            rankDTO.setIndex(Double.valueOf(tempResult.get(0)[3].toString()).intValue());
            rankDTO.setDerver(String.valueOf(tempResult.get(0)[4]));
            rankDTO.setVipId(String.valueOf(tempResult.get(0)[5]));
            return rankDTO;
        }

        return null;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<RankDTO> findPrevious50() {
        List<Object[]> tempResult = homeworkRankingDao.findPrevious50();
        List<RankDTO> rankDTOList = new LinkedList<>();
        tempResult.forEach(it -> {
            RankDTO rankDTO = new RankDTO();
            rankDTO.setUserName(String.valueOf(it[0]));
            rankDTO.setImgUrl(String.valueOf(it[1]));
            rankDTO.setRankingNum((Integer) Optional.ofNullable(it[2]).orElse(0));
            rankDTO.setIndex(Double.valueOf(it[3].toString()).intValue());
            rankDTO.setDerver(String.valueOf(it[4]));
            rankDTO.setVipId(String.valueOf(it[5]));
            rankDTOList.add(rankDTO);
        });
        return rankDTOList;
    }

    @Override
    public int computeCorrectionIntegral() {
        return 0;
    }

    @Override
    public RankDTO findByVipId(String vipId) {
        return homeworkMapper.findByVipId(vipId);
    }

    @Override
    public ResponseEntity findHomeworkRankingByVipId(String vipId) {
        RankDTO ownRank = this.findByVipId(vipId);

        return this.getRankingList(ownRank);
    }

    @Override
    public ResponseEntity findHomeworkRankingByDerver(String derver) {
        RankDTO ownRank = this.findByDerver(derver);

        return this.getRankingList(ownRank);
    }

    private ResponseEntity getRankingList(RankDTO ownRank) {
        //如果自己在50名以内，则更新列表中自己的数据
        ResponseEntity responseEntity = new ResponseEntity();

        List<RankDTO> rankDTOList = tokenManager.getList(Constant.PREVIOUS50_HOMEWORK_RANK, RankDTO.class);
        if (CollectionUtils.isEmpty(rankDTOList)) {
            rankDTOList = this.findPrevious50();
            tokenManager.set(Constant.PREVIOUS50_HOMEWORK_RANK, rankDTOList);
        }
        boolean needSort = false;
        boolean inTheList = false;
        if (ownRank != null) {
            for (RankDTO rankDTO : rankDTOList) {
                if (Objects.equals(rankDTO.getVipId(), ownRank.getVipId())) {
                    inTheList = true;

                    if (!Objects.equals(ownRank.getRankingNum(), rankDTO.getRankingNum())) {
                        rankDTO.setRankingNum(ownRank.getRankingNum());
                        needSort = true;
                        break;
                    }
                }
            }
        }
        if (ownRank != null && !inTheList) {
            RankDTO lastOne = rankDTOList.get(rankDTOList.size() - 1);
            if (ownRank.getRankingNum() > lastOne.getRankingNum()) {
                rankDTOList.remove(lastOne);
                rankDTOList.add(ownRank);
                needSort = true;
            }
        }
        if (needSort) {
            rankDTOList.sort(Comparator.comparingInt(RankDTO::getRankingNum).reversed());
        }

        Map<String, Object> resultMap = new HashMap<>();

        HomeworkRankingDto dto = null;
        if (ownRank != null) {
            dto = new HomeworkRankingDto();
            dto.setUserName(ownRank.getUserName());
            dto.setImgUrl(ownRank.getImgUrl());
            dto.setRankingNum(ownRank.getRankingNum());
            dto.setIndex(ownRank.getIndex());
        }

        List<HomeworkRankingDto> dtoList = new ArrayList<>();
        for (RankDTO rankDTO : rankDTOList) {
            HomeworkRankingDto dto1 = new HomeworkRankingDto();
            dto1.setUserName(rankDTO.getUserName());
            dto1.setImgUrl(rankDTO.getImgUrl());
            dto1.setRankingNum(rankDTO.getRankingNum());
            dto1.setIndex(rankDTO.getIndex());
            dtoList.add(dto1);
        }
        resultMap.put("ownRank", dto);
        resultMap.put("rankList", dtoList);
        responseEntity.success(resultMap, "查询成功");
        return responseEntity;
    }

    @Override
    public int saveRankIntegral(String vipId, int integral,int operType,String details) {
        LibVip vip =vipService.getById(vipId);
        //没绑定校区的不加积分
        if(vip==null){
            return 0;
        }
        //积分夺宝跟兑换以及积分失效 不用限制是否绑定校区
        if(operType<9 || operType>11){
            if(StringUtils.isEmpty(vip.getLibId())){
                return 0;
            }
        }
        HomeworkRanking homeworkRanking = homeworkRankingDao.findByVipId(vipId);
        if (homeworkRanking == null) {
            homeworkRanking = new HomeworkRanking();
            homeworkRanking.setVipId(vipId);
            homeworkRanking.setRankingNum(integral);
            Date now = new Date();
            homeworkRanking.setUpdateTime(now);
            homeworkRanking.setCreateTime(now);
        } else {
            if (integral == 0) {
                return 0;
            }

            Integer currentRankingNum = homeworkRanking.getRankingNum();
            if (currentRankingNum == null) {
                currentRankingNum = 0;
            }
            homeworkRanking.setRankingNum(currentRankingNum + integral);
            homeworkRanking.setUpdateTime(new Date());
        }
        homeworkRankingDao.save(homeworkRanking);

        //记录明细
        if (integral == 0) {
            return 0;
        }
        IntegralDetail integralDetail = new IntegralDetail(operType,details);
        integralDetail.setVipId(vipId);
        integralDetail.setCreateTime(new Date());
        integralDetail.setIntegral(Math.abs(integral));
        integralDetailService.save(integralDetail);
        return integral;
    }

    @Override
    public int searchIntegralByVipId(String vipId) {
        HomeworkRanking ranking = homeworkRankingDao.findByVipId(vipId);
        if(ranking==null){
            return 0;
        }
       return  ranking.getRankingNum();
    }

}
