package com.infoepoch.pms.dispatchassistant.infractructure.basic.permission;

import com.infoepoch.pms.dispatchassistant.common.utils.OracleUtils;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.IRoleRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.Role;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.RoleCriteria;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuyj
 * @description 角色仓储
 * @date 2019-11-12 11:36
 */
@Repository
public class RoleRepository implements IRoleRepository {

    private static final Logger logger = LoggerFactory.getLogger(RoleRepository.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public List<Role> selectByUserId(String userId) {
        String sql = "SELECT RL.* FROM BAS_ROLE RL,BAS_USER_ROLE UR WHERE RL.RL_ID=UR.UR_ROLE_ID AND UR.UR_USER_ID=?";
        return jdbcTemplate.query(sql, new RoleMapper(), userId);
    }

    @Override
    public void insert(Role role) {
        String sql = "INSERT INTO BAS_ROLE(RL_ID,RL_NAME,RL_DESCRIPTION,RL_DISABLED,RL_CREATE_TIME,RL_EDITOR) VALUES(?,?,?,?,?,?)";
        jdbcTemplate.update(sql, role.getId(), role.getName(), role.getDescription(), role.isDisabled(), role.getCreateTime(), role.isEditor());
    }

    @Override
    public void update(Role role) {
        String sql = "UPDATE BAS_ROLE SET RL_NAME=?,RL_DESCRIPTION=?,RL_DISABLED=?,RL_MODIFY_TIME=? WHERE RL_ID=?";
        jdbcTemplate.update(sql, role.getName(), role.getDescription(), role.isDisabled(), role.getModifyTime(), role.getId());
    }

    @Override
    public void delete(String id) {
        String sql = "DELETE FROM BAS_ROLE WHERE RL_ID=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Role> queryByPage(RoleCriteria criteria, int pageIndex, int pageSize) {
        StringBuffer sql = new StringBuffer("SELECT * FROM BAS_ROLE");
        List<Object> paramList = OracleUtils.combinationSql(sql, transferCriteria(criteria), pageIndex, pageSize);
        return jdbcTemplate.query(sql.toString(), new RoleMapper(), paramList.toArray());
    }

    @Override
    public int queryByPageCount(RoleCriteria criteria) {
        StringBuffer sql = new StringBuffer("SELECT COUNT(1) FROM BAS_ROLE");
        List<Object> paramList = OracleUtils.combinationSql(sql, transferCriteria(criteria));
        try {
            return jdbcTemplate.queryForObject(sql.toString(), paramList.toArray(), Integer.class);
        } catch (DataAccessException e) {
            logger.info("queryByPageCount:", e);
        }
        return 0;
    }

    @Override
    public Role selectByRoleName(String roleName) {
        String sql = "SELECT * FROM BAS_ROLE WHERE RL_NAME=?";
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql, roleName);
        if (sqlRowSet.next()) {
            return new Role(
                    sqlRowSet.getString("RL_ID"),
                    sqlRowSet.getString("RL_NAME"),
                    sqlRowSet.getString("RL_DESCRIPTION"),
                    sqlRowSet.getBoolean("RL_DISABLED")
            );
        }
        return null;
    }

    @Override
    public Role selectById(String roleId) {
        String sql = "SELECT * FROM BAS_ROLE WHERE RL_ID=?";
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql, roleId);
        if (sqlRowSet.next()) {
            return new Role(
                    sqlRowSet.getString("RL_ID"),
                    sqlRowSet.getString("RL_NAME"),
                    sqlRowSet.getString("RL_DESCRIPTION"),
                    sqlRowSet.getBoolean("RL_DISABLED")
            );
        }
        return null;
    }

    private Map<String, Object> transferCriteria(RoleCriteria criteria) {
        Map<String, Object> andMap = new HashMap<>();
        if (StringUtils.isNotBlank(criteria.getName())) {
            andMap.put(" RL_NAME LIKE ?", "%" + criteria.getName() + "%");
        }
        if (criteria.isBranchFlag()) {
            Role role = selectByRoleName("培训管理员（全省）");
            if(role == null) {
                andMap.put(" RL_ID NOT IN ('1') ", null);
            } else {
                andMap.put(" RL_ID NOT IN ('1','" + role.getId() + "') ", null);
            }
        }
        return andMap;
    }

    static class RoleMapper implements RowMapper<Role> {
        @Override
        public Role mapRow(ResultSet resultSet, int i) throws SQLException {
            return new Role(resultSet.getString("RL_ID"),
                    resultSet.getString("RL_NAME"),
                    resultSet.getString("RL_DESCRIPTION"),
                    resultSet.getBoolean("RL_DISABLED"),
                    resultSet.getBoolean("RL_EDITOR"),
                    resultSet.getDate("RL_CREATE_TIME"),
                    resultSet.getDate("RL_MODIFY_TIME"));
        }
    }
}
