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.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.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import org.apache.commons.lang3.StringUtils;

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();
    }
}
