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

import com.ssj.bean.sys.game.domain.GameQuestion;
import com.ssj.bean.sys.game.domain.GameQuestionOption;
import com.ssj.bean.sys.game.domain.GameRecord;
import com.ssj.bean.sys.game.domain.Ranklist;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.sys.game.dao.GameQuestionDao;
import com.ssj.dao.sys.game.dao.GameQuestionOptionDao;
import com.ssj.dao.sys.game.dao.GameRecordDao;
import com.ssj.dao.sys.game.dao.RanklistDao;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.conch.game.dto.QuestionDto;
import com.ssj.service.conch.game.dto.RanklistDto;
import com.ssj.service.conch.game.request.RanklistReq;
import com.ssj.service.conch.game.request.SavePersonInfoReq;
import com.ssj.service.conch.game.request.SaveV1Req;
import com.ssj.service.conch.game.service.GameRecordService;
import com.ssj.service.conch.game.service.GameService;
import com.ssj.service.conch.game.service.RanklistService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Mount Liu
 * @date 2018/2/20
 */
@Service
@Transactional
public class GameServiceImpl implements GameService {

    @Autowired
    private RanklistDao ranklistDao;

    @Autowired
    private RanklistService ranklistService;

    @Autowired
    private UserService userService;

    @Autowired
    private GameRecordDao gameRecordDao;

    @Autowired
    private GameRecordService gameRecordService;

    @Autowired
    private GameQuestionDao gameQuestionDao;

    @Autowired
    private GameQuestionOptionDao gameQuestionOptionDao;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ResponseEntity rankingList(RanklistReq req, Pageable pageable) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> params = new HashMap<>(16);
        List<RanklistDto> list = new ArrayList<>();
        if (StringUtils.isNotBlank(req.getMaxCreateTime())) {
            params.put("LTE_createTime", req.getMaxCreateTime());
        }
        Page<Ranklist> page = ranklistService.findByPage(params, pageable);
        for (Ranklist ranklist : page.getContent()) {
            RanklistDto dto = new RanklistDto();
            dto.setName(ranklist.getName());
            dto.setPhoto(ranklist.getPhoto());
            dto.setScore(ranklist.getScore());
            dto.setSex(ranklist.getSex());
            list.add(dto);
        }
        data.put("pages", page.getTotalElements());
        data.put("pageSize", req.getPageSize());
        data.put("pageNo", req.getPageNo());
        data.put("list", list);
        responseEntity.success(data, "成功");
        return responseEntity;
    }

    @Override
    public ResponseEntity saveResult(String userId, SaveV1Req req) {
        ResponseEntity responseEntity = new ResponseEntity();
        //插入新记录
        GameRecord record = new GameRecord();
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        record.setScore(req.getScore());
        record.setSpaceImagination(req.getSpaceImagination());
//        record.setSpatialAbility(req.getSpatialAbility());
//        record.setTextSearch(req.getTextSearch());
//        record.setMemory(req.getMemory());
//        record.setObservationAbility(req.getObservationAbility());
        record.setGraphicReasoning(req.getGraphicReasoning());
        record.setAttention(req.getAttention());
        record.setAppraisal(req.getAppraisal());
        record.setLevel(req.getLevel());
        //更新总分
        double totalScore = req.getScore() + ranklist.getScore();
        ranklist.setScore(totalScore);
        ranklist.setLevel(req.getLevel());
        ranklistService.save(ranklist);
        gameRecordService.save(record);
        responseEntity.success("成功");
        return responseEntity;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ResponseEntity homepageInfo(String userId) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> map = new HashMap<>(16);
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        if (ranklist != null) {
            map.put("name", ranklist.getName());
            map.put("photo", ranklist.getPhoto());
            List<GameRecord> records = gameRecordDao.findByUserId(userId);
            //1:第一次测试，2：已经测过，没有结束，3已经测过，已经结束
            switch (records.size()) {
                case 0:
                    map.put("type", 1);
                    break;
                case 5:
                    map.put("type", 3);
                    break;
                default:
                    map.put("type", 2);
                    break;
            }
        } else {
            //第一次授权后新增数据
            User user = userService.getById(userId);
            Ranklist newRanklist = new Ranklist();
            newRanklist.setUserId(userId);
            newRanklist.setName(user.getName());
            newRanklist.setPhoto(user.getPhoto());
            newRanklist.setCreateTime(new Date());
            ranklistService.save(newRanklist);
            map.put("name", user.getName());
            map.put("photo", user.getPhoto());
            map.put("type", 1);
        }
        responseEntity.success(map,"成功");
        return responseEntity;
    }

    @Override
    public ResponseEntity savePersonInfo(String userId, SavePersonInfoReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        if (ranklist != null) {
            ranklist.setSex(req.getSex());
            ranklist.setAgeGroup(req.getAgeGroup());
            ranklistService.save(ranklist);
            responseEntity.success("成功");
        } else {
            responseEntity.failure("用户数据不存在，请联系管理员！");
        }
        return responseEntity;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ResponseEntity findResult(String userId) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> map = new HashMap<>(16);
        List<GameRecord> ranklist = gameRecordDao.findByUserId(userId);
        if (ranklist != null && ranklist.size() > 0) {
            double totalScore = 0.0;
            for (GameRecord record : ranklist) {
                totalScore += record.getScore();
            }
            map.put("score", ranklist.get(0).getScore());
            map.put("totalScore", totalScore);
            map.put("spaceImagination", ranklist.get(0).getSpaceImagination());
//            map.put("spatialAbility", ranklist.get(0).getSpatialAbility());
//            map.put("textSearch", ranklist.get(0).getTextSearch());
//            map.put("memory", ranklist.get(0).getMemory());
//            map.put("observationAbility", ranklist.get(0).getObservationAbility());
            map.put("graphicReasoning", ranklist.get(0).getGraphicReasoning());
            map.put("attention", ranklist.get(0).getAttention());
            map.put("appraisal", ranklist.get(0).getAppraisal());
            if (ranklist.size() == 5) {
                map.put("isEnd", 1);
            } else {
                map.put("isEnd", 0);
            }
        }
        responseEntity.success(map,"成功");
        return responseEntity;
    }

    @Override
    public ResponseEntity findQuestion(String userId, int selection) {
        ResponseEntity responseEntity = new ResponseEntity();
        //题目列表
        List<QuestionDto.Question> questionList = new ArrayList();
        //选项列表
        List<QuestionDto.Question.Option> optionList = new ArrayList();
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        QuestionDto dto = new QuestionDto();
        dto.setAgeGroup(ranklist.getAgeGroup());
        dto.setSex(ranklist.getSex());
        //1：重新开始；2：接着测试（或挑战下一关）
        if (selection == 1) {
            //软删除用户游戏记录
            gameRecordDao.deleteRecordsByUserId(userId);
            //清空分数
            ranklistDao.updateScore(0.0, userId);
            dto.setLevel(1);
        } else {
            dto.setLevel(ranklist.getLevel() + 1);
        }
        //查询当前关卡所有题目，按照升序排列
        List<GameQuestion> questions = gameQuestionDao.findByLevelOrderByNumberAsc(dto.getLevel());
        for (GameQuestion question : questions) {
            QuestionDto.Question qusDto = dto.new Question();
            qusDto.setTitle(question.getTitle());
            if (StringUtils.isNotBlank(question.getPicture())) {
                qusDto.setPicture(Arrays.asList(question.getPicture().split(",")));
            }
            qusDto.setContent(question.getContent());
            qusDto.setAnswerId(question.getAnswerId());
            qusDto.setAnswer(question.getAnswer());
            qusDto.setType(question.getType());
            List<GameQuestionOption> options = gameQuestionOptionDao.findByQuestionId(question.getId());
            if (options != null && options.size() > 0) {
                for (GameQuestionOption option : options) {
                    QuestionDto.Question.Option optDto = qusDto.new Option();
                    optDto.setId(optDto.getId());
                    optDto.setContent(option.getContent());
                    optionList.add(optDto);
                }
            }
            qusDto.setOptions(optionList);
            questionList.add(qusDto);
        }
        dto.setList(questionList);
        responseEntity.success(dto,"成功");
        return responseEntity;
    }

}
