package easydo.technology.system.rest;

import easydo.technology.components.JdbcClient;
import easydo.technology.exception.BizException;
import easydo.technology.system.model.SysDept;
import easydo.technology.system.model.SysRole;
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("/sysDept")
public class SysDeptController {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;

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


    @RequestMapping(value = "/save")
    public Object add(@RequestBody SysDept model) throws Exception {
        jdbcClient.jdbcInsert(model);
        return new ResponseEntity<>(model, HttpStatus.OK);
    }


    @RequestMapping(value = "/update")
    public Object update(@RequestBody SysDept model) throws Exception {
        jdbcClient.jdbcUpdateById(model);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(value = "/remove")
    public Object deleteProgram(@RequestBody SysDept model) throws Exception {
        Connection connection = dataSource.getConnection();
        try {
            SysDept childrenDept = new SysDept();
            childrenDept.setPid(model.getId());
            int count = jdbcClient.getJdbcCount(childrenDept, connection);
            if (count > 0) {
                throw new BizException("存在下级部门，无法删除");
            }

            jdbcClient.jdbcRemoveById(model, connection);
            return new ResponseEntity<>(HttpStatus.OK);
        } finally {
            connection.close();
        }
    }

}
