package easydo.technology.system.rest;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.system.model.SysRolesMenus;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sysRolesMenus")
public class SysRolesMenusController {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;

    @RequestMapping(value = "/getList")
    public Object getList(@RequestBody Map<String, Object> map) throws Exception {
        List<SysRolesMenus> list = jdbcClient.getJdbcList(map, SysRolesMenus.class);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @RequestMapping(value = "/batchSave")
    public Object batchSave(@RequestBody SysRolesMenus rolesMenus) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            connection.setAutoCommit(false);
            List<Long> menuIdList = rolesMenus.getMenuIdList();
            jdbcClient.jdbcRemove(rolesMenus, connection);
            for (Long menuId : menuIdList) {
                SysRolesMenus model = new SysRolesMenus();
                model.setMenuId(menuId);
                model.setRoleId(rolesMenus.getRoleId());
                jdbcClient.jdbcInsert(model, connection);
            }
            connection.commit();
            return new ResponseEntity<>(rolesMenus, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw new BizException(e.getMessage());
        } finally {
            connection.close();
        }

    }
}
