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

import com.actionsoft.bpms.bo.design.cache.BOCache;
import com.actionsoft.bpms.bo.design.model.BOModel;
import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ListenerConst;
import com.actionsoft.bpms.bpmn.engine.listener.ValueListener;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeneralDeactivate extends ValueListener {

    /**
     * 通用注销
     * @param ctx
     * @return
     * @throws Exception
     */
    @Override
    public String execute(ProcessExecutionContext ctx) {
        //参数获取
        //记录ID
        String boId = ctx.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BOID);
        //表单ID
        String formId = ctx.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_FORMID);
        //BO表名
        String boName = ctx.getParameterOfString(ListenerConst.FORM_EVENT_PARAM_BONAME);
        //视图场景获取选中行数据
        String rowData = ctx.getParameterOfString("$SOURCEDATA");
        // Ajax方式
        ResponseObject ro = ResponseObject.newOkResponse();
        boolean r = true;// 针对业务进行处理

        /*
        System.out.println("注销");
        System.out.println("boId:" + boId);
        System.out.println("formId:" + formId);
        System.out.println("boName:" + boName);
        System.out.println("rowData:" + rowData);
         */

        List<String> Ids = new ArrayList<>();

        if (StringUtils.isNotBlank(boId))
            Ids.add(boId);

        if (StringUtils.isNotBlank(rowData)) {
            JSONObject rowDataJson = JSONObject.parseObject(rowData);
            JSONArray data = rowDataJson.getJSONArray("data");
            if ((data.size() > 0)) for (int i = 0; i < data.size(); i++) {
                JSONObject jsonObject = data.getJSONObject(i);
                String id = jsonObject.getString("_ID");
                //如果最后两个字符是 _0/_1... 则去掉
                if (id.substring(id.length() - 2, id.length() - 1).equals("_")) {
                    id = id.substring(0, id.length() - 2);
                }
                Ids.add(id);
            }

            if (StringUtils.isBlank(boName)) {
                BOModel model = BOCache.getInstance().getModel(rowDataJson.getString("boDefId"));
                //System.out.println("BOModel:" + model.toJson());
                boName = model.getName();
            }

        }

        if (Ids.size() == 0) {
            ro.msg("请选择注销记录");
            return ro.toString();
        }
        Connection conn = null;
        int updateCount = 0;
        try {
            conn = DBSql.open();
            conn.setAutoCommit(false);
            for (String id : Ids) {
                BO bo = SDK.getBOAPI().get(boName, id);
                if (bo == null) {
                    throw new Exception("数据不存在");
                }
                bo.set("CLOSED", 1);
                Map<String, Object> params = new HashMap<>();
                params.put("ID", id);
                params.put("CLOSED", 1);
                dn.recordFormChanges.record(ctx.getUserContext(), boName, params, "注销", conn);//记录操作日志
                if (SDK.getBOAPI().update(boName, bo, conn) > 0) {
                    updateCount++;
                }
            }
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                r = false;
            }
        } catch (Exception e) {
            ro = ResponseObject.newErrResponse();
            ro.msg("错误" + e.getMessage());
            return ro.toString();
        } finally {
            if (conn != null)
                DBSql.close(conn);
        }

        if (updateCount != Ids.size())
            r = false;

        // 处理业务逻辑成功时
        if (r) {
            ro.msg("成功");// 返回给服务器的消息
            // ro.put("key1", "value1").put("key2", "value2");// 放入前端需要的参数
            return ro.toString();
        } else {
            // 错误时
            ro = ResponseObject.newErrResponse();
            ro.msg("错误");
            return ro.toString();
        }
    }
}
