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

import com.infoepoch.pms.dispatchassistant.common.component.SnowFlake;
import com.infoepoch.pms.dispatchassistant.domain.basic.menu.Menu;
import com.infoepoch.pms.dispatchassistant.domain.basic.role.IRoleMenuRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuyj
 * @description 用户菜单关联
 * @date 2019-11-14 11:10
 */
@Repository
public class RoleMenuRepository implements IRoleMenuRepository {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public void batchInsert(List<String> ids,String roleId, List<String> menuIds, List<String> invoiceList) {
        String sql = "INSERT INTO BAS_ROLE_MENU(RM_ID,RM_MENU_ID,RM_ROLE_ID,RM_INVOICE) VALUES(?,?,?,?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                String menuId = menuIds.get(i);
                String invoice = invoiceList.get(i);
                ps.setString(1, ids.get(i));
                ps.setString(2, menuId);
                ps.setString(3, roleId);
                ps.setString(4, invoice);
            }

            @Override
            public int getBatchSize() {
                return menuIds.size();
            }
        });
    }

    @Override
    public void deleteAll(String roleId) {
        String sql = "DELETE FROM BAS_ROLE_MENU WHERE RM_ROLE_ID=?";
        jdbcTemplate.update(sql, roleId);
    }

    @Override
    public List<Menu> select(String roleId) {
        String sql = "SELECT * FROM BAS_MENUS m LEFT JOIN BAS_ROLE_MENU rm ON rm.RM_MENU_ID=m.ME_ID WHERE rm.RM_ROLE_ID=?";
        return jdbcTemplate.query(sql, new RoleAndMenuMapper(), roleId);
    }

    @Override
    public List<String> selectInvoice(String menuId, List<String> roleId) {
        String sql = "SELECT RM_INVOICE FROM BAS_ROLE_MENU WHERE RM_MENU_ID=? AND FIND_IN_SET(RM_ROLE_ID,?)";
        List<Object> objList = new ArrayList<>();
        objList.add(menuId);
        objList.add(StringUtils.join(roleId, ","));
        return jdbcTemplate.queryForList(sql, objList.toArray(), String.class);
    }
}
