package easydo.technology.controller;

import easydo.technology.annotation.WebLog;
import easydo.technology.components.JdbcClient;
import easydo.technology.model.UserProjectRef;
import lombok.extern.java.Log;
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("/api")
public class UserProjectRefController {
    @Resource
    JdbcClient jdbcClient;
    @Resource
    DataSource dataSource;

    @WebLog
    @RequestMapping(value = "/getList")
    public Object getList(@RequestBody Map<String, Object> map) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();

            List<UserProjectRef> list = jdbcClient.getJdbcList(map, UserProjectRef.class, connection);
            return new ResponseEntity<>(list, HttpStatus.OK);
        } catch (Exception e) {
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }

    @WebLog
    @RequestMapping(value = "/saveBatch")
    public Object save(@RequestBody UserProjectRef model) throws Exception {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);

            jdbcClient.jdbcRemove(model, connection);

            String[] projectIdArr = model.getProjectIds().split(",");
            for (String projectId : projectIdArr) {
                UserProjectRef ref = new UserProjectRef();
                ref.setProjectId(Long.valueOf(projectId));
                jdbcClient.jdbcInsert(ref, connection);
            }
            connection.commit();
            return new ResponseEntity<>(model, HttpStatus.OK);
        } catch (Exception e) {
            connection.rollback();
            throw e;
        } finally {
            jdbcClient.finallyExecute(connection);
        }
    }
}
