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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssj.bean.sys.game.domain.GameAnswerRecord;
import com.ssj.bean.sys.game.domain.GameRecord;
import com.ssj.bean.sys.game.domain.GameRespondent;
import com.ssj.bean.sys.game.domain.Ranklist;
import com.ssj.bean.weixin.user.domain.User;
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.framework.weixin.util.DateUtil;
import com.ssj.service.conch.game.dto.HistoryDto;
import com.ssj.service.conch.game.dto.RanklistDto;
import com.ssj.service.conch.game.request.*;
import com.ssj.service.conch.game.service.*;
import com.ssj.service.mapper.GameMapper;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 GameV2ServiceImpl implements GameV2Service {

    @Autowired
    private RanklistDao ranklistDao;
    @Autowired
    private RanklistService ranklistService;
    @Autowired
    private UserService userService;
    @Autowired
    private GameRecordDao gameRecordDao;
    @Autowired
    private GameRecordService gameRecordService;
    @Autowired
    private GameMapper gameMapper;
    @Autowired
    private GameAnswerRecordService gameAnswerRecordService;
    @Autowired
    private GameRespondentService gameRespondentService;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ResponseEntity rankingList(RanklistReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        Map<String, Object> data = new HashMap<>();
        Page<RanklistDto> page = new Page<>(req.getPageNo(), req.getPageSize());
        page = gameMapper.findPage(page, req.getMaxCreateTime());
        data.put("pages", page.getPages());
        data.put("pageSize", req.getPageSize());
        data.put("pageNo", req.getPageNo());
        data.put("list", page.getRecords());
        return responseEntity.success(data, "查询成功");
    }

    @Override
    public ResponseEntity saveResult(String userId, SaveV2Req req) {
        ResponseEntity responseEntity = new ResponseEntity();

        GameRecord record = gameRecordService.findByUserIdAndLevel(userId, req.getLevel());
        if (record == null) {
            record = new GameRecord();
            record.setCreateTime(new Date());
        }

        record.setUserId(userId);
        record.setScore(req.getScore());
        record.setSpaceImagination(req.getSpaceImagination());
        record.setExecutionFunctionality(req.getExecutionFunctionality());
        record.setVisualSearch(req.getVisualSearch());
        record.setWorkingMemory(req.getWorkingMemory());
        record.setAttention(req.getAttention());
        record.setRelevantMemory(req.getRelevantMemory());
        record.setMentalRotation(req.getMentalRotation());
        record.setGraphicReasoning(req.getGraphicReasoning());
        record.setAppraisal(req.getAppraisal());
        record.setLevel(req.getLevel());
        record.setIsDelete(0);
        gameRecordService.save(record);

        //更新总分
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        ranklist.setScore(req.getScore());
        ranklist.setLevel(req.getLevel());
        ranklistService.save(ranklist);

        return responseEntity.success("保存成功");
    }

    @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());
            map.put("level", ranklist.getLevel());
            map.put("ageGroup", ranklist.getAgeGroup());
        } else {
            //第一次授权后新增数据
            User user = userService.getById(userId);
            if (user == null) {
                return responseEntity.failure("用户不存在");
            }
            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("level", -1);
            map.put("ageGroup", -1);
        }
        return responseEntity.success(map, "成功");
    }

    @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);
            return responseEntity.success("成功");
        } else {
            return responseEntity.failure("用户数据不存在，请联系管理员！");
        }
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public ResponseEntity findResult(String userId, TestResultReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        GameRecord gameRecord;
        if (StringUtils.isBlank(req.getGameRecordId())) {
            gameRecord = gameRecordDao.findNewest(userId);
        } else {
            gameRecord = gameRecordService.getById(req.getGameRecordId());
        }

        if (gameRecord == null) {
            return responseEntity.failure("您还未开始测试");
        }

        Map<String, Object> resultMap = new HashMap<>();
        Ranklist ranklist = ranklistService.findByUserId(userId);
        resultMap.put("appraisal", gameRecord.getAppraisal());
        resultMap.put("score", gameRecord.getScore());
        resultMap.put("level", gameRecord.getLevel());
        resultMap.put("totalScore", ranklist.getScore());
        resultMap.put("spaceImagination", gameRecord.getSpaceImagination());
        resultMap.put("executionFunctionality", gameRecord.getExecutionFunctionality());
        resultMap.put("visualSearch", gameRecord.getVisualSearch());
        resultMap.put("workingMemory", gameRecord.getWorkingMemory());
        resultMap.put("attention", gameRecord.getAttention());
        resultMap.put("relevantMemory", gameRecord.getRelevantMemory());
        resultMap.put("mentalRotation", gameRecord.getMentalRotation());
        resultMap.put("graphicReasoning", gameRecord.getGraphicReasoning());

        return responseEntity.success(resultMap, "成功");
    }

    @Override
    public ResponseEntity reset(String userId) {
        ResponseEntity responseEntity = new ResponseEntity();

        Ranklist ranklist = ranklistService.findByUserId(userId);

        if (ranklist == null) {
            return responseEntity.failure("您还未开始测试");
        }

        //清除测试总分和当前关卡
        ranklist.setScore(0.0);
        ranklist.setLevel(0);
        ranklistService.save(ranklist);

        //清除所有关卡的测试记录
        gameRecordService.deleteByUserId(userId);

        return responseEntity.success("重置成功");
    }

    @Override
    public ResponseEntity saveResultV2(String userId, SaveV2Req req) {
        ResponseEntity responseEntity = new ResponseEntity();

        //更新测试结果
        Ranklist ranklist = ranklistDao.findByUserId(userId);
        if (ranklist == null) {
            return responseEntity.failure("失败");
        }
        if (Objects.equals(0, req.getLevel()) && ranklist.getLevel() > -1) {
            // 已完成练习关卡
            return responseEntity.success("成功");
        }

        if (0 == req.getLevel()) {
            // 练习关卡结果保存
            ranklist.setLevel(0);
        } else {
            // 正常测试结果保存
//            GameRecord record = gameRecordService.findByUserIdAndLevel(userId, req.getLevel());
            GameRecord record = gameRecordService.findByUserIdAndGameRespondentIdAndLevel(userId,
                    req.getGameRespondentId(), req.getLevel());
            if (record == null) {
                record = new GameRecord();
                record.setCreateTime(new Date());
            }

            // 测试记录
            record.setUserId(userId);
            record.setGameRespondentId(req.getGameRespondentId());
            record.setScore(req.getScore());
            record.setSpaceImagination(req.getSpaceImagination());
            record.setExecutionFunctionality(req.getExecutionFunctionality());
            record.setVisualSearch(req.getVisualSearch());
            record.setWorkingMemory(req.getWorkingMemory());
            record.setAttention(req.getAttention());
            record.setRelevantMemory(req.getRelevantMemory());
            record.setMentalRotation(req.getMentalRotation());
            record.setGraphicReasoning(req.getGraphicReasoning());
            record.setAppraisal(req.getAppraisal());
            record.setLevel(req.getLevel());
            record.setIsDelete(0);
            gameRecordService.save(record);

            // 排行榜记录
            ranklist.setScore(req.getScore());
            ranklist.setLevel(req.getLevel());
        }
        ranklistService.save(ranklist);

        return responseEntity.success("保存成功");
    }

    @Override
    public ResponseEntity answerInfoSave(String userId, AnswerInfoSaveReq req) {
        GameAnswerRecord gameAnswerRecord = new GameAnswerRecord();
        BeanUtils.copyProperties(req, gameAnswerRecord);
        gameAnswerRecord.setUserId(userId);
        gameAnswerRecord.setCreateTime(new Date());
        gameAnswerRecordService.save(gameAnswerRecord);
        return new ResponseEntity().success("保存成功");
    }

    @Override
    public ResponseEntity saveRespondentInfo(String userId, SaveRespondentInfoReq req) {
        GameRespondent gameRespondent = new GameRespondent();
        BeanUtils.copyProperties(req, gameRespondent);
        gameRespondent.setUserId(userId);
        gameRespondent.setCreateTime(new Date());
        gameRespondent = gameRespondentService.save(gameRespondent);
        return new ResponseEntity().success(Collections.singletonMap("gameRespondentId", gameRespondent.getId()), "成功");
    }

    @Override
    public ResponseEntity findHistory(String userId, RanklistReq req) {
        ResponseEntity responseEntity = new ResponseEntity();

        try {
            DateUtil.parse_yyyyMMddHHmmss(req.getMaxCreateTime());
        } catch (Exception e) {
            return responseEntity.failure("时间格式不正确");
        }

        IPage<HistoryDto> page = new Page<>(req.getPageNo(), req.getPageSize());
        gameMapper.findHistory(page, userId, req);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("pageNo", page.getCurrent());
        resultMap.put("pageSize", page.getSize());
        resultMap.put("pages", page.getPages());
        resultMap.put("list", page.getRecords());

        return responseEntity.success(resultMap, "成功");
    }

}
