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

import com.infoepoch.pms.dispatchassistant.domain.basic.menu.IMenuRepository;
import com.infoepoch.pms.dispatchassistant.domain.basic.menu.Menu;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class MenuRepository implements IMenuRepository {

    @Autowired
    JdbcTemplate jdbcTemplate;


    @Override
    public void insert(Menu menu) {
        String sql = "INSERT INTO BAS_MENUS(ME_ID,ME_NAME,ME_URL,ME_ICON,ME_COLLAPSE,ME_DISABLED,ME_DESCRIPTION,ME_PARENT_ID," +
                "ME_ELEMENT,ME_SORTING,ME_CREATE_TIME,ME_TYPE,ME_CONTROLDATA) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql, menu.getId(),
                menu.getName(), menu.getUrl(), menu.getIcons(), menu.isCollapse(), menu.isDisabled(),
                menu.getDescription(), menu.getParentId(), menu.getElement(), menu.getSorting(), menu.getCreateTime(),
                menu.getType(), menu.isControlData());
    }

    @Override
    public void deleteMenuById(String id) {
        String sql = "DELETE FROM BAS_MENUS WHERE ME_ID=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public void updateMenuById(Menu menu) {
        String sql = "UPDATE BAS_MENUS SET ME_NAME=?,ME_URL=?,ME_ICON=?,ME_COLLAPSE=?,ME_DISABLED=?,ME_DESCRIPTION=?," +
                "ME_PARENT_ID=?,ME_ELEMENT=?,ME_SORTING=?,ME_MODIFY_TIME=?,ME_CONTROLDATA=? WHERE ME_ID=?";
        jdbcTemplate.update(sql, menu.getName(), menu.getUrl(), menu.getIcons(), menu.isCollapse(), menu.isDisabled(),
                menu.getDescription(), menu.getParentId(), menu.getElement(), menu.getSorting(), menu.getModifyTime(), menu.isControlData(),
                menu.getId());
    }

    @Override
    public List<Menu> selectMainMenuByUserId(String userId) {
        String sql = "SELECT m.* FROM BAS_MENUS m WHERE m.ME_ELEMENT<>1 AND m.ME_TYPE=? AND m.ME_ID IN (" +
                "SELECT DISTINCT rm.RM_MENU_ID FROM BAS_ROLE_MENU rm LEFT JOIN BAS_ROLE r ON (rm.RM_ROLE_ID=r.RL_ID) " +
                "LEFT JOIN BAS_USER_ROLE ur ON (ur.UR_ROLE_ID=r.RL_ID) LEFT JOIN BAS_USER u ON (u.U_ID=ur.UR_USER_ID) " +
                "WHERE u.U_ID=?) ORDER BY m.ME_SORTING";
        return jdbcTemplate.query(sql, new MenuRowMapper(), Menu.TYPE_MENU_MAIN, userId);
    }

    @Override
    public List<Menu> selectMainMenuBySaId(String saId) {
        String sql = "SELECT m.* FROM BAS_MENUS m WHERE m.ME_ELEMENT<>1 AND m.ME_TYPE=? AND m.ME_ID IN (" +
                "SELECT DISTINCT rm.SRM_MENU_ID FROM BAS_SUPPLIER_ROLE_MENU rm LEFT JOIN BAS_SUPPLIER_ROLE r ON (rm.SRM_ROLE_ID=r.SR_ID) " +
                "LEFT JOIN BAS_SUPPLIER_ACCOUNT_ROLE ur ON (ur.SAR_ROLE_ID=r.SR_ID) LEFT JOIN BAS_SUPPLIER_ACCOUNT u ON (u.SA_ID=ur.SAR_ACCOUNT_ID) " +
                "WHERE u.SA_ID=?) ORDER BY m.ME_SORTING";
        return jdbcTemplate.query(sql, new MenuRowMapper(), Menu.TYPE_MENU_COOP, saId);
    }

    @Override
    public List<Menu> selectMainMenuByRoleName(String roleName) {
        String sql = "SELECT m.* FROM BAS_MENUS m WHERE m.ME_ELEMENT<>1 AND m.ME_TYPE=? AND m.ME_ID IN (" +
                "SELECT rm.RM_MENU_ID FROM BAS_ROLE_MENU rm LEFT JOIN BAS_ROLE r ON (rm.RM_ROLE_ID=r.RL_ID) WHERE r.RL_NAME=?) order by ME_SORTING";
        return jdbcTemplate.query(sql, new MenuRowMapper(), Menu.TYPE_MENU_MAIN, roleName);
    }

    @Override
    public List<Menu> selectMainMenuBySaRoleName(String roleName) {
        String sql = "SELECT m.* FROM BAS_MENUS m WHERE m.ME_ELEMENT<>1 AND m.ME_TYPE=? AND m.ME_ID IN (" +
                "SELECT rm.SRM_MENU_ID FROM BAS_SUPPLIER_ROLE_MENU rm LEFT JOIN BAS_SUPPLIER_ROLE r ON (rm.SRM_ROLE_ID=r.SR_ID) WHERE r.SR_NAME=?)";
        return jdbcTemplate.query(sql, new MenuRowMapper(), Menu.TYPE_MENU_COOP, roleName);
    }

    @Override
    public Menu selectById(String id) {
        String sql = "SELECT * FROM BAS_MENUS WHERE ME_ID = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new MenuRowMapper(), id);
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 根据名称查询菜单
     */
    @Override
    public List<Menu> selectByName(String name) {
        List<Menu> list = new ArrayList<>();
        String sql = "SELECT * FROM BAS_MENUS where ME_PARENT_ID=(SELECT ME_ID FROM BAS_MENUS where ME_NAME=?)";
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql, name);
        while (sqlRowSet.next()) {
            Menu menu = convert(sqlRowSet);
            list.add(menu);
        }
        return list;
    }

    /**
     * 根据菜单名称集合查询菜单
     */
    @Override
    public List<Menu> selectByNameList(List<String> nameList) {
        if (CollectionUtils.isEmpty(nameList)) {
            return new ArrayList<>();
        }
        StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM BAS_MENUS where ME_PARENT_ID in (SELECT ME_ID FROM BAS_MENUS where ME_NAME IN (");
        for (int i = 0; i < nameList.size(); i++) {
            sqlBuilder.append("?");
            if (i < nameList.size() - 1) {
                sqlBuilder.append(",");
            }
        }
        sqlBuilder.append("))");
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sqlBuilder.toString(), nameList.toArray());
        List<Menu> list = new ArrayList<>();
        while (sqlRowSet.next()) {
            Menu menu = convert(sqlRowSet);
            list.add(menu);
        }
        return list;
    }

    @Override
    public void deleteByRoleId(String roleId) {
        String sql = "DELETE FROM BAS_MENUS WHERE ME_ID IN (SELECT RM_MENU_ID FROM BAS_ROLE_MENU WHERE RM_ROLE_ID=?)";
        jdbcTemplate.update(sql, roleId);
    }

    @Override
    public List<Menu> selectAll(int type) {
//        String sql = "SELECT * FROM BAS_MENUS WHERE ME_TYPE=? ORDER BY ME_SORTING";
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM BAS_MENUS WHERE ME_TYPE=?");
        sql.append(" AND ME_DISABLED = 0");
        sql.append(" ORDER BY ME_SORTING");
        return jdbcTemplate.query(sql.toString(), new MenuRowMapper(), type);
    }

    @Override
    public Menu selectByUrl(String url) {
        String sql = "SELECT * FROM BAS_MENUS WHERE ME_URL=? AND ME_TYPE='1'";
        try {
            return jdbcTemplate.queryForObject(sql, new MenuRowMapper(), url);
        } catch (Exception ex) {
            return null;
        }
    }

    private Menu convert(SqlRowSet sqlRowSet) {
        Menu menu = new Menu(
                sqlRowSet.getString("ME_ID"),
                sqlRowSet.getString("ME_NAME"),
                sqlRowSet.getString("ME_URL"),
                sqlRowSet.getString("ME_ICON"),
                sqlRowSet.getBoolean("ME_COLLAPSE"),
                sqlRowSet.getBoolean("ME_DISABLED"),
                sqlRowSet.getString("ME_DESCRIPTION"),
                sqlRowSet.getString("ME_PARENT_ID"),
                sqlRowSet.getInt("ME_ELEMENT"),
                sqlRowSet.getInt("ME_SORTING"),
                sqlRowSet.getDate("ME_CREATE_TIME"),
                sqlRowSet.getDate("ME_MODIFY_TIME"),
                sqlRowSet.getInt("ME_TYPE"),
                sqlRowSet.getBoolean("ME_CONTROLDATA")
        );
        return menu;
    }
}
