package com.hdkj.lt.si.controller.sql;

import com.hdkj.hussar.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;

@RestController
@RequestMapping("/fhzgSqlExecute")
@RequiredArgsConstructor
public class FhzgSqlExecuteController {

    private final SqlSessionFactory sqlSessionFactory;

    @PostMapping("/importData")
    public ApiResponse<String> importData(@RequestParam("file") MultipartFile file) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Connection connection = sqlSession.getConnection();
        ScriptRunner scriptRunner = new ScriptRunner(connection);
        InputStream sqlFileIn = file.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(sqlFileIn, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        scriptRunner.runScript(bufferedReader);
        return ApiResponse.success("导入完成");
    }
}
