package net.northking.cctp.platform.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class InterfaceSqlUtils {

    private final static Logger logger = LoggerFactory.getLogger(InterfaceSqlUtils.class);

    public static void interfaceSql(String sql) throws IOException {
        //文件地址
        String path = Class.class.getClass().getResource("/").getPath();
        String[] split = path.split("/target");
        String filePath =  split[0] + "/src/main/resources/db/mysql/data/interface.sql";

        File file = new File(filePath);
        FileInputStream fis = null;
        InputStreamReader isr = null;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            if (file.exists()) {
                boolean delete = file.delete();
                if (!delete) {
                    logger.error("删除文件失败");
                }
            }
            boolean newFile = file.createNewFile();
            if (!newFile){
                logger.error("创建文件失败");
            }
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(sql.toCharArray());
            pw.flush();

        } catch (IOException e) {
            logger.error("IO异常",e);
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
}
