/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * 
 * https://www.renren.io
 * 
 * 版权所有,侵权必究!
 */
package com.zt.generator.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zt.common.constant.Constant;
import com.zt.common.db.constant.OP;
import com.zt.common.exception.RenException;
import com.zt.common.servlet.Result;
import com.zt.generator.model.Config;
import com.zt.generator.data.DBUtil;
import com.zt.generator.data.DataTable;
import com.zt.generator.utils.GenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
 * 代码生成器
 *
 * @author xhb
 */
@RestController
@RequestMapping("/sys/generator")
@Api(tags = "代码生成")
public class SysGeneratorController {
    @GetMapping("properties")
    //@RequiresPermissions(Constant.Permissions.SUPER_ADMIN)
    public Result queryProperties() {
        JSONObject jsonObject = new JSONObject();
        try {
            File directory = new File("");// 参数为空
            String courseFile = directory.getCanonicalPath();
            File root = new File(courseFile);
            JSONArray array = new JSONArray();
            getSubFiles(root, array);
            jsonObject.put("modules", array);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray eqList = new JSONArray();
        for (OP.Type value : OP.Type.values()) {
            JSONObject json = new JSONObject();
            json.put("title", value.getTitle());
            json.put("op", value.getOp());
            eqList.add(json);
        }
        jsonObject.put("eqList", eqList);
        DbProperties jdbc = queryJdbcProperties();
        DataTable table = null;
        Connection conn = null;
        try {
            // 注册数据库驱动
            Class.forName(jdbc.getDriverClass());
            Properties props = new Properties();
            props.put("remarksReporting", "true");// 为了得到说明
            props.setProperty("user", jdbc.getUserName());
            props.setProperty("password", jdbc.getPassWord());
            // 获取连接
            conn = DriverManager.getConnection(jdbc.getUrl(), props);
            table = DBUtil.getTableList(conn, false);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        jsonObject.put("tableList", table.toJSONArray());
        return Result.ok(jsonObject);
    }
    private void getSubFiles(File file, JSONArray array) {
        if (file.isDirectory()) {
            // 获取当前目录下的所有子项
            File[] subs = file.listFiles();
            for (File sub : subs) {
                if (sub.isDirectory() && new File(sub.getPath() + "/pom.xml").exists()) {
                    if (new File(sub.getPath() + "/src").exists()) {
                        JSONObject object = new JSONObject();
                        object.put("filePath", sub.getPath());
                        object.put("fileName", sub.getName());
                        array.add(object);
                    } else {
                        getSubFiles(sub, array);
                    }
                }
                if (sub.isDirectory() && new File(sub.getPath() + "/package.json").exists()) {
                    JSONObject object = new JSONObject();
                    object.put("filePath", sub.getPath());
                    object.put("fileName", sub.getName());
                    array.add(object);
                }
            }
        }
    }
    @GetMapping("getTable")
    //@RequiresPermissions(Constant.Permissions.SUPER_ADMIN)
    public Result tableNameVerification(String tableName) {
        DbProperties jdbc = queryJdbcProperties();
        DataTable table = null;
        Connection conn = null;
        try {
            // 注册数据库驱动
            Class.forName(jdbc.getDriverClass());
            Properties props = new Properties();
            props.put("remarksReporting", "true");// 为了得到说明
            props.setProperty("user", jdbc.getUserName());
            props.setProperty("password", jdbc.getPassWord());
            // 获取连接
            conn = DriverManager.getConnection(jdbc.getUrl(), props);
            if (DBUtil.findTable(conn, tableName)) {
                table = DBUtil.getColumnInfo(conn, tableName, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        if (table != null) {
            JSONArray array = table.toJSONArray();
            for (int i = 0; i < array.size(); i++) {
                JSONObject json = array.getJSONObject(i);
                String columnName = json.getString("columnName");
                if ("is_delete,dept_id,company_id,tenant_id,creator,create_date,updater,update_date"
                        .indexOf(columnName.toLowerCase()) >= 0) {
                    json.put("isTableColumn", "false");
                }
            }
            return Result.ok(array);
        } else {
            throw new RenException("表不存在!");
        }
    }
    @Value("${spring.datasource.druid.driver-class-name}")
    private String dbDriverName;
    @Value("${spring.datasource.druid.url}")
    private String dbDriverUrl;
    @Value("${spring.datasource.druid.username}")
    private String dbDriverUserName;
    @Value("${spring.datasource.druid.password}")
    private String dbDriverPassword;
    private DbProperties queryJdbcProperties() {
        DbProperties jdbc = new DbProperties();
        String driver = dbDriverName;
        jdbc.setDbName(driver.equals("oracle.jdbc.driver.OracleDriver") ? "ORACLE" : "MYSQL");
        jdbc.setDriverClass(driver);
        jdbc.setUrl(dbDriverUrl);
        jdbc.setUserName(dbDriverUserName);
        jdbc.setPassWord(dbDriverPassword);
        return jdbc;
    }
    @Data
    class DbProperties implements Serializable {
        private String dbName;
        private String driverClass;
        private String url;
        private String userName;
        private String passWord;
    }
    /**
     * 生成代码
     */
    @PostMapping
    @ApiOperation("保存")
    //@RequiresPermissions(Constant.Permissions.SUPER_ADMIN)
    public Result code(@RequestBody Config dto) {
        String isGenService = dto.getChecked();
        GenUtils.generatorCode(dto.getTableName(), isGenService, dto.getClassName(), dto.getIsPageFlag(),
                dto.getIsExport(), JSONArray.parseArray(dto.getTableData()), dto.getPackName(), dto.getJavaFilePath(),
                dto.getVueFilePath());
        return Result.ok();
    }
}