package com.zanxiang.game.data.serve.service.impl;

import com.zanxiang.game.data.serve.pojo.dto.GameDTO;
import com.zanxiang.game.data.serve.pojo.dto.GameUserConfigCreateOrUpdateDTO;
import com.zanxiang.game.data.serve.pojo.dto.GameUserConfigListDTO;
import com.zanxiang.game.data.serve.pojo.entity.GameUserConfig;
import com.zanxiang.game.data.serve.pojo.vo.GameUserConfigListVO;
import com.zanxiang.game.data.serve.service.IGameUserConfigService;
import com.zanxiang.game.data.serve.utils.Page;
import com.zanxiang.module.util.exception.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * packageName com.zanxiang.game.data.serve.service.impl
 *
 * @author ZhangXianyu
 * @date 2024/4/18
 * @description 创角配置
 */
@Service
public class GameUserConfigServiceImpl implements IGameUserConfigService {

    @Autowired
    private Dao dao;

    @Override
    public Page<GameUserConfigListVO> validRoleConfigList(GameUserConfigListDTO dto) {
        Criteria criA = Cnd.cri();
        if (dto.getGameId() != null) {
            criA.where().andEquals("game_id", dto.getGameId());
        }
        if (StringUtils.isNotEmpty(dto.getSourceSystem())) {
            criA.where().andEquals("source_system", dto.getSourceSystem());
        }
        //分页对象
        Pager pager = dao.createPager(dto.getPageNum(), dto.getPageSize());
        //查询总记录数
        Sql countSql = Sqls.create(getGameUserConfigTotalSql() + criA);
        countSql.setCallback(Sqls.callback.integer());
        dao.execute(countSql);
        pager.setRecordCount(countSql.getInt());

        //创建sql
        Sql sql = Sqls.create(getGameUserConfigSql(criA));
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(GameUserConfigListVO.class));
        sql.setPager(pager);
        dao.execute(sql);
        //查询结果
        List<GameUserConfigListVO> list = sql.getList(GameUserConfigListVO.class);
        Map<Long, GameDTO> parentGameMap = getGameMap();
        list.forEach(item -> {
            GameDTO gameDTO = parentGameMap.get(item.getGameId());
            if (gameDTO != null) {
                item.setGameName(gameDTO.getGameName());
            }
        });
        return new Page<>(list, pager);
    }

    @Override
    public Boolean create(GameUserConfigCreateOrUpdateDTO dto) {
        int gameId = dao.count(GameUserConfig.class, Cnd.where("game_id", "=", dto.getGameId()));
        if (gameId > 0) {
           throw new BaseException("该游戏已存在创角配置");
        }
        GameUserConfig gameUserConfig = new GameUserConfig();
        gameUserConfig.setSourceSystem("ZX_ONE");
        gameUserConfig.setGameId(dto.getGameId());
        gameUserConfig.setRoleLevel(dto.getRoleLevel());
        gameUserConfig.setCreateTime(LocalDateTime.now());
        gameUserConfig.setUpdateTime(LocalDateTime.now());
        dao.insert(gameUserConfig);
        return true;
    }

    @Override
    public Boolean delete(Long id) {
        dao.delete(GameUserConfig.class, id);
        return true;
    }

    @Override
    public Boolean update(GameUserConfigCreateOrUpdateDTO dto) {
        if(dto.getId()==null){
            throw new BaseException("id不能为空");
        }
        int count = dao.count(GameUserConfig.class, Cnd.where("game_id", "=", dto.getGameId()).and("id", "!=", dto.getId()));
        if (count > 0) {
            throw new BaseException("该游戏已存在创角配置");
        }
        GameUserConfig old = dao.fetch(GameUserConfig.class, Cnd.where("id", "=", dto.getId()));
        if (old == null) {
            throw new BaseException("创角配置不存在");
        }
        old.setUpdateTime(LocalDateTime.now());
        old.setGameId(dto.getGameId());
        old.setRoleLevel(dto.getRoleLevel());
        dao.update(old, FieldFilter.create(GameUserConfig.class, "gameId|roleLevel|updateTime"));
        return true;
    }

    public String getGameUserConfigSql(Criteria criA) {
        String sql = """
                select 
                 source_system,
                 id,
                 game_id,
                 role_level,
                 create_time,
                 update_time
                 from 
                 dm_game_order.t_game_user_config   
                 """ + criA + """
                    order by create_time desc
                """;
        return sql;
    }


    public String getGameUserConfigTotalSql() {
        String sql = """
                select count(*) from dm_game_order.t_game_user_config
                """;
        return sql;
    }


    /**
     * 获取游戏列表
     */
    private Map<Long, GameDTO> getGameMap() {
        Sql sql = Sqls.create(getGameSql());
        sql.setCallback(Sqls.callback.entities());
        sql.setEntity(dao.getEntity(GameDTO.class));
        dao.execute(sql);
        List<GameDTO> gameDtoList = sql.getList(GameDTO.class);
        //将游戏拼成map key为游戏id，value为游戏名称
        return gameDtoList.stream().collect(Collectors.toMap(GameDTO::getId, Function.identity()));
    }

    /**
     * 查询游戏sql
     *
     * @return String
     */
    private String getGameSql() {
        return """
                 SELECT
                            -- 游戏名称、游戏类型、父游戏id、超父游戏id
                            source_system,
                            id,
                            game_name,
                            classify,
                            parent_id,
                            super_game_id
                        FROM dm_game_order.t_game
                        where source_system = 'ZX_ONE'
                """;
    }
}