/**
 * 游戏勘探controller，管理前端游戏相关的勘探操作
 */


package com.td.Dawa.game.comcharactersdiscovery.controller;

import com.td.Dawa.annotation.Decrypt;
import com.td.Dawa.annotation.Encrypt;
import com.td.Dawa.common.controller.*;
import com.td.Dawa.common.pojo.PageInfo;
import com.td.Dawa.common.pojo.Result;
import com.td.Dawa.config.enums.GameEnum;
import com.td.Dawa.config.enums.ResultEnum;
import com.td.Dawa.config.exception.AuthorizeException;
import com.td.Dawa.game.comcharacters.service.ComCharactersService;
import com.td.Dawa.game.comcharacters.vo.ComCharactersVo;
import com.td.Dawa.game.comcharactersdiscovery.pojo.ComCharactersDiscovery;
import com.td.Dawa.game.comcharactersdiscovery.vo.ComCharactersDiscoveryClientVo;
import com.td.Dawa.game.comcharactersdiscovery.vo.ComCharactersDiscoveryVo;
import com.td.Dawa.game.comcharactersdiscovery.service.ComCharactersDiscoveryService;
import com.td.Dawa.util.RedisData;
import com.td.Dawa.util.RedisLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/game/comCharactersDiscovery/")
public class ComCharactersDiscoveryController extends CommonController<ComCharactersDiscoveryVo, ComCharactersDiscovery, Integer> {
    @Autowired
    private ComCharactersDiscoveryService comCharactersDiscoveryService;
    @Autowired
    private ComCharactersService comCharactersService;

    @Autowired
    private RedisLock redisLock;

    /**
     * 开始工作
     *
     * @param userId
     * @param sceneId
     * @return
     */
    @PostMapping("startExploration")
    @Decrypt
    @Encrypt
    public Result<?> startExploration(@RequestParam(value = "userId") String userId,
                                      @RequestParam(value = "sceneId") Integer sceneId) {
        try {
            ComCharactersDiscoveryClientVo characterDiscoveryClientVo = comCharactersDiscoveryService.startDiscover(userId, sceneId);
            return Result.of(characterDiscoveryClientVo);
        } catch (AuthorizeException e) {
            return Result.of(null, false, e.getMessage(), e.getCode());
        } catch (Exception e) {
            return Result.of(e.getMessage(), false, ResultEnum.EXPLORATION_INFO_ERROR);
        }

    }

    /**
     * 玩家选择一个添加角色,添加工作
     * @param userId
     * @param roleId
     * @param workPos
     * @param sceneId
     * @param isAdd 默认true是添加角色，false则移除工作角色
     * @return
     */
    @PostMapping("addExplorationRole")
    @Decrypt
    @Encrypt
    public Result<?> addExplorationRole(@RequestParam(value = "userId") String userId,
                                        @RequestParam(value = "roleId") Integer roleId,
                                        @RequestParam(value = "workPos") Integer workPos,
                                        @RequestParam(value = "sceneId") Integer sceneId,
                                        @RequestParam(value = "isAdd",defaultValue = "true") Boolean isAdd) {

        long time = System.currentTimeMillis() + RedisData.getCharactersTimeout();
        String _redisKey = RedisData.getCharactersKey(userId,roleId);

        try {
            // 防止重复操作
            if (!redisLock.lock(_redisKey, String.valueOf(time))) {
                return Result.of(null, false, ResultEnum.REDIS_IS_LOCK);
            }
            //拿出一个角色对应的配置数据来生成角色
            ComCharactersVo comCharactersVo = comCharactersService.getVo(roleId);
            if (comCharactersVo == null || !comCharactersVo.getUserId().equals(userId)) {
                return Result.of(null, false, ResultEnum.ROLE_DOES_NOT_EXIST);
            }
            //如果是添加的状态
            if(isAdd){
                if(!comCharactersVo.getProfessional().equals(GameEnum.PRO_WORK_NORMAL.getValue())){
                    //带工作信息的不给添加
                    return Result.of(null, false, ResultEnum.ROLE_WORK_NOT_NORMAL);
                }
                if (workPos.equals(GameEnum.PRO_POWER.getValue() + 1)) {
                    //按场景区分，是挖矿还是伐木
                    if (sceneId.equals(GameEnum.MINE_00.getValue())) {
                        comCharactersVo.setProfessional(GameEnum.PRO_WORK_MINING.getValue());
                    } else if (sceneId.equals(GameEnum.LUMBERING_00.getValue())) {
                        comCharactersVo.setProfessional(GameEnum.PRO_WORK_LUMBERING.getValue());
                    } else {
                        //不存在场景时候，抛出异常
                        return Result.of(null, false, ResultEnum.SCENE_ID_NOT);
                    }
                } else if (workPos.equals(GameEnum.PRO_INTELLIGENCE.getValue() + 1)) {
                    comCharactersVo.setProfessional(GameEnum.PRO_WORK_PROSPECT.getValue());
                } else if (workPos.equals(GameEnum.PRO_SKIlLS.getValue() + 1)) {
                    comCharactersVo.setProfessional(GameEnum.PRO_WORK_TRANSPORT.getValue());
                } else {
                    return Result.of(null, false, ResultEnum.ROLE_PRO_DOES_NOT_EXIST);
                }
                //设置一个位置
                comCharactersVo.setWorkPos(workPos);
                //根据roleId 对应的数据，加入队伍
                ComCharactersDiscoveryClientVo clientVo = comCharactersDiscoveryService.addDiscoverRole(comCharactersVo, sceneId);
                return Result.of(clientVo);
            }else{
                if(comCharactersVo.getProfessional().equals(GameEnum.PRO_WORK_NORMAL.getValue())){
                    //不带工作信息的不给移除
                    return Result.of(null, false, ResultEnum.ROLE_NOT_WORK);
                }
                //根据roleId 对应的数据，移出队伍
                ComCharactersDiscoveryClientVo clientVo = comCharactersDiscoveryService.removeDiscoverRole(comCharactersVo, sceneId);
                return Result.of(clientVo);
            }

        } catch (AuthorizeException e) {
            return Result.of(null, false, e.getMessage(), e.getCode());
        } catch (Exception e) {
            return Result.of(e.getMessage(), false, ResultEnum.ROLE_ADD_ERROR);
        } finally {
            redisLock.unlock(_redisKey, String.valueOf(time));
        }

    }


    /**
     * 返回一个挖矿队伍列表
     *
     * @param userId
     * @return
     */
    @PostMapping("getExplorationList")
    @Encrypt
    public Result<PageInfo<ComCharactersDiscoveryClientVo>> getExplorationList(@RequestParam(value = "userId") String userId,
                                                                               @RequestParam(value = "page", defaultValue = "0") Integer page,
                                                                               @RequestParam(value = "limit", defaultValue = "3") Integer limit) {
        ComCharactersDiscoveryVo characterDiscoveryVo = new ComCharactersDiscoveryVo();
        characterDiscoveryVo.setUserId(userId);
        characterDiscoveryVo.setPage(page + 1);
        characterDiscoveryVo.setRows(limit);
        characterDiscoveryVo.setSidx("desc");
        characterDiscoveryVo.setSord("createTime");
        PageInfo<ComCharactersDiscoveryClientVo> clientVoList = comCharactersDiscoveryService.findDiscoverClientVo(characterDiscoveryVo);
        return Result.of(clientVoList);
    }

    /**
     * 根据探索队伍的id，更新当前探索的状态
     * 用于处理中途显示奖励之类的操作
     *
     * @param userId
     * @param explorationId
     * @return ComCharactersDiscoveryClientVo And string
     */
    @PostMapping("updateState")
    @Decrypt
    @Encrypt
    public Result<?> updateState(@RequestParam(value = "userId") String userId,
                                 @RequestParam(value = "explorationId") Integer explorationId,
                                 @RequestParam(value = "isStop", defaultValue = "false") Boolean isStop) {
        try {
            //查看是否存在勘探数据
            ComCharactersDiscoveryVo discoveryVo = comCharactersDiscoveryService.getVo(explorationId);
            if (discoveryVo == null || !discoveryVo.getUserId().equals(userId)) {
                throw new RuntimeException("勘探队伍不存在！");
            }
            //计算收益updateState
            return Result.of(comCharactersDiscoveryService.explorationState(discoveryVo, isStop));
        } catch (AuthorizeException e) {
            return Result.of(null, false, e.getMessage(), e.getCode());
        } catch (Exception e) {
            return Result.of(e.getMessage(), false, ResultEnum.EXPLORATION_ERROR);
        }

    }
}
