package com.zanxiang.game.module.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.erp.base.ErpServer;
import com.zanxiang.erp.base.rpc.ISysUserRpc;
import com.zanxiang.erp.security.util.SecurityUtil;
import com.zanxiang.game.module.base.pojo.enums.DeleteEnum;
import com.zanxiang.game.module.base.pojo.enums.ShellControlEnum;
import com.zanxiang.game.module.base.pojo.enums.StatusEnum;
import com.zanxiang.game.module.manage.pojo.dto.GameDTO;
import com.zanxiang.game.module.manage.pojo.params.GameAppletShellAddUpdateParam;
import com.zanxiang.game.module.manage.pojo.params.GameAppletShellListParam;
import com.zanxiang.game.module.manage.pojo.vo.GameAppletShellListVO;
import com.zanxiang.game.module.manage.service.IGameAppletShellService;
import com.zanxiang.game.module.manage.service.IGameService;
import com.zanxiang.game.module.mybatis.entity.GameAppletShell;
import com.zanxiang.game.module.mybatis.mapper.GameAppletShellMapper;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : lingfeng
 * @time : 2023-07-06
 * @description : 壳包控制
 */
@Slf4j
@Service
public class GameAppletShellServiceImpl extends ServiceImpl<GameAppletShellMapper, GameAppletShell> implements IGameAppletShellService {

    @Autowired
    private IGameService gameService;

    @Lazy
    @DubboReference(providedBy = ErpServer.SERVER_DUBBO_NAME)
    private ISysUserRpc sysUserRpc;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addOrUpdate(GameAppletShellAddUpdateParam param) {
        //参数判断
        if (Objects.equals(ShellControlEnum.SHELL_CONTROL_LOW_LEVEL_OPEN.getShellControl(), param.getProControlType())
                && param.getProControlLevel() == null) {
            throw new BaseException("参数错误, 控制低等级开启壳, 等级限制不可为空");
        }
        //非申诉中, 类型限制
        if (!param.getIsAppeal() && !ShellControlEnum.SHELL_CONTROL_CLOSE.getShellControl().equals(param.getProControlType())
                && !ShellControlEnum.SHELL_CONTROL_OPEN.getShellControl().equals(param.getProControlType())) {
            throw new BaseException("参数错误, 非申诉中状态, 控制类型只能选开启/关闭");
        }
        Long id = param.getId();
        //创建
        if (id == null) {
            GameAppletShell gameAppletShell = super.getOne(new LambdaQueryWrapper<GameAppletShell>()
                    .eq(GameAppletShell::getGameId, param.getGameId()));
            if (gameAppletShell != null) {
                throw new BaseException("该游戏已经存在壳包配置, 禁止重复添加");
            }
            return super.save(this.transform(param));
        }
        //更新
        GameAppletShell gameAppletShell = super.getById(id);
        if (gameAppletShell == null) {
            throw new BaseException("参数错误, 游戏壳包配置信息不存在");
        }
        gameAppletShell.setIsAppeal(param.getIsAppeal());
        gameAppletShell.setProVersion(param.getProVersion());
        gameAppletShell.setArraignVersion(param.getArraignVersion());
        gameAppletShell.setProControlType(param.getProControlType());
        gameAppletShell.setProControlLevel(param.getProControlLevel());
        gameAppletShell.setIsSkipSwitch(param.getIsSkipSwitch());
        gameAppletShell.setUpdateBy(SecurityUtil.getUserId());
        gameAppletShell.setUpdateTime(LocalDateTime.now());
        return super.updateById(gameAppletShell);
    }

    private GameAppletShell transform(GameAppletShellAddUpdateParam param) {
        return GameAppletShell.builder()
                .gameId(param.getGameId())
                .isAppeal(param.getIsAppeal())
                .proVersion(param.getProVersion())
                .arraignVersion(param.getArraignVersion())
                .proControlType(param.getProControlType())
                .proControlLevel(param.getProControlLevel())
                .isSkipSwitch(param.getIsSkipSwitch())
                .status(StatusEnum.YES.getCode())
                .isDelete(DeleteEnum.NO.getCode())
                .createBy(SecurityUtil.getUserId())
                .createTime(LocalDateTime.now())
                .createBy(SecurityUtil.getUserId())
                .updateTime(LocalDateTime.now())
                .build();
    }

    @Override
    public IPage<GameAppletShellListVO> listOfPage(GameAppletShellListParam param) {
        return super.page(param.toPage(), new QueryWrapper<GameAppletShell>().lambda()
                .eq(param.getGameId() != null, GameAppletShell::getGameId, param.getGameId())
                .orderByDesc(GameAppletShell::getCreateTime)
        ).convert(this::toVO);
    }

    private GameAppletShellListVO toVO(GameAppletShell gameAppletShell) {
        if (gameAppletShell == null) {
            return null;
        }
        GameAppletShellListVO gameAppletShellListVO = BeanUtil.copy(gameAppletShell, GameAppletShellListVO.class);
        GameDTO gameDTO = gameService.getById(gameAppletShellListVO.getGameId());
        if (gameDTO != null) {
            gameAppletShellListVO.setGameName(gameDTO.getName());
        }
        Map<Long, String> userNameMap = null;
        List<Long> userIds = Arrays.asList(gameAppletShellListVO.getCreateBy(), gameAppletShellListVO.getUpdateBy());
        try {
            userNameMap = sysUserRpc.getUserNameByIds(userIds).getData();
        } catch (Exception e) {
            log.error("获取投手名字信息异常, userIds : {}, e : {}", userIds, e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(userNameMap)) {
            gameAppletShellListVO.setCreateByName(userNameMap.get(gameAppletShellListVO.getCreateBy()));
            gameAppletShellListVO.setUpdateByName(userNameMap.get(gameAppletShellListVO.getUpdateBy()));
        }
        return gameAppletShellListVO;
    }

}
