package com.awspaas.user.apps.donenow_sys.controller;

import com.actionsoft.bpms.bo.design.cache.BOCache;
import com.actionsoft.bpms.bo.design.model.BOItemModel;
import com.actionsoft.bpms.bo.design.model.BOModel;
import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

@Controller
public class sysController {
    /**
     * 删除 通用方法
     * @param uc
     * @param ids
     * @return
     * @throws SQLException
     */
    @Mapping(value = "com.awspaas.user.apps.donenow_sys_Del")
    public ResponseObject del(UserContext uc, String tableName, String ids) throws SQLException {
        if (StringUtils.isBlank(ids))
            return ResponseObject.newErrResponse("请选择要删除的数据");

        BOModel boModel = BOCache.getInstance().getModelByEntityName(tableName);
        if (boModel == null || StringUtils.isBlank(tableName)) {
            return ResponseObject.newErrResponse("无权限删除");
        }

        tableName = boModel.getName();
        if (!tableName.startsWith("BO_EU_DN"))
            return ResponseObject.newErrResponse("无权限删除");

        BOItemModel closed_itemModel = boModel.getItem("CLOSED");
        boolean isClosed = false;
        if (closed_itemModel != null && closed_itemModel.getName().equals("CLOSED")) {
            isClosed = true;
            return ResponseObject.newErrResponse("无权限删除");
        }

        Connection conn = null;
        try {

            //引用校验
            conn = DBSql.open();
            conn.setAutoCommit(false);
            RowMap verify = DBSql.getMap(conn, "select * from BO_EU_DNSYS_DELETE_VERIFY where CODE=?", new Object[]{tableName});
            String sql = null;
            if (verify != null && StringUtils.isNotBlank(verify.getString("SEL_SQL"))) {
                sql = verify.getString("SEL_SQL");
                for (String id : ids.split(",")) {
                    String sqlById = sql.replace("**id**", "?");
                    List<RowMap> list = DBSql.getMaps(conn, sqlById, new Object[]{id});
                    if (!list.isEmpty()) {
                        String errMsg = null;
                        for (RowMap rowMap : list) {
                            errMsg += rowMap.getString("NAME") + rowMap.getString("NUM") + "\r\n";
                        }
                        throw new Exception("删除失败，被以下数据引用：\r\n" + errMsg);
                    }
                }
            }


            for (String id : ids.split(",")) {

                BO bo = SDK.getBOAPI().get(tableName, id);

                BOItemModel is_system_itemModel = boModel.getItem("IS_SYSTEM");
                if (is_system_itemModel != null && is_system_itemModel.getName().equals("IS_SYSTEM")) {
                    if (bo.getString("IS_SYSTEM").equals("1"))
                        throw new Exception("系统内置的分类不能删除");
                }

                if (isClosed) {
                    bo.set("CLOSED", "1");
                    SDK.getBOAPI().update(tableName, bo, conn);
                } else {
                    SDK.getBOAPI().remove(tableName, id, conn);
                }
            }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            conn.rollback();
            return ResponseObject.newErrResponse(e.getMessage());
        } catch (Exception e) {
            return ResponseObject.newErrResponse(e.getMessage());
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }
        return ResponseObject.newOkResponse();
    }


    /**
     * 发版提交，替换应用下jar包
     * @param ctx
     * @param boId
     * @return
     */
    @Mapping("com.awspaas.user.apps.donenow_sys_fbSubmit")
    public String fbSubmit(UserContext ctx, String boId) {
        if (ctx.getUID().equals("admin") == false)
            return "无权限";

        BO FBjar = SDK.getBOAPI().get("BO_EU_DNSYS_JAR", boId);
        if (FBjar == null)
            return "请保存刷新后重试";
        if (FBjar.getString("STATUS").equals("未发版") == false) {
            return "已发版";
        }

        String appId = FBjar.getString("APP_ID");
        if (StringUtils.isBlank(appId))
            return "请选择要发版的app";

        System.out.println("开始发版appId:" + appId + ";boId:" + boId);
        try {
            List<FormFile> jars = SDK.getBOAPI().getFiles(boId, "SCWJ");
            FormFile jar = jars.get(0);
            DCContext dcContext = SDK.getBOAPI().getFileDCContext(jar);

            System.out.println("jar--path:" + dcContext.getPath());
            System.out.println("jar--fileName:" + dcContext.getFileName());
            System.out.println("jar--filePath:" + dcContext.getFilePath());

            String currentDir = System.getProperty("user.dir");
            System.out.println("当前工作目录: " + currentDir);

            // 源文件
            Path source = Paths.get(dcContext.getFilePath());
            currentDir = currentDir.replace("bin", "apps");

            // 构建目标文件路径
            Path targetDirectory = Paths.get(currentDir, "install", appId, "lib");
            //如果路径不存在，则报错
            if (!Files.exists(targetDirectory)) {
                return "请选择要发版的app";
            }

            Path target = targetDirectory.resolve(source.getFileName());

            // 检查目标文件是否存在  以前文件不保存
            /*
            File targetFile = target.toFile();
            if (targetFile.exists()) {
                System.out.println("目标文件已存在，尝试重命名...");

                String fileName = targetFile.getName();
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
                String newFileName = fileName + "_" + timestamp;

                // 构建新文件路径
                Path newFilePath = targetDirectory.resolve(newFileName);

                // 重命名已存在的文件
                Files.move(target, newFilePath, StandardCopyOption.REPLACE_EXISTING);
                System.out.println("已重命名现有文件为: " + newFileName);
            }

             */
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件已移动到目标目录: " + target);
            FBjar.set("STATUS", "已发版--成功");
            SDK.getBOAPI().update("BO_EU_DNSYS_JAR", FBjar);

            return "成功";
        } catch (IOException e1) {
            return "失败";
        } catch (Exception e2) {
            return "失败";
        } finally {
            System.out.println("结束");
        }
    }
}
