package nckd.jimin.jyyy.bd.plugin.msg.ecology;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.workflow.exception.WFErrorCode;
import kd.bos.workflow.exception.WFMessageServiceException;
import kd.sdk.plugin.Plugin;
import org.apache.commons.lang3.ObjectUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EcologyOpPlugin extends AbstractOperationServicePlugIn implements Plugin {
    private static Log logger = LogFactory.getLog(EcologyOpPlugin.class);
    private static final String KEY_ENTITY_LOG = "nckd_ecology";
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);

        StringBuffer errMsg = new StringBuffer();

        //获取选中行
        DynamicObject[] dynamicObjects = e.getDataEntities();

        //获取操作按钮操作编码
        String operationKey = e.getOperationKey();
        if (StringUtils.equals( "sendmsg",operationKey)){
            List<DynamicObject> listObj = new ArrayList<>();

            String selectField = "nckd_entryentity.nckd_key, nckd_entryentity.nckd_value";

            QFilter qFilter = new QFilter("number", QCP.equals, "fanwei");
            DynamicObject commonParam = BusinessDataServiceHelper.loadSingle("nckd_commonparams", selectField, qFilter.toArray());
            if (ObjectUtils.isEmpty(commonParam)) {
                errMsg.append("未配置泛微相关参数nckd_commonparams");
                return;
            }

            DynamicObjectCollection entryentity = commonParam.getDynamicObjectCollection("nckd_entryentity");
            Map<String, String> mapentity = entryentity.stream().collect(Collectors.toMap(k -> k.getString("nckd_key"), v -> v.getString("nckd_value")));

            if(mapentity == null ){
                errMsg.append("未配置泛微相关参数nckd_entryentity");
                return;
            }

            String sendFlowUrl = mapentity.get("sendflow");
            String secretkey = mapentity.get("secret_key");

            if(StringUtils.isEmpty(sendFlowUrl) || StringUtils.isEmpty(secretkey)){
                return;
            }

            String token = FanweiCommonUtil.getFanWeiToken(true);

            for(int i = 0; i < dynamicObjects.length; i++) {
                String id = dynamicObjects[i].getPkValue().toString();
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(id, KEY_ENTITY_LOG);
                Boolean needSend = false;
                if(dynamicObject.getString("nckd_logtype").matches("1|5")
                    && "fail".equals(dynamicObject.getString("nckd_sendstatus"))){
                    needSend = true;
                }

                if(!needSend){
                    continue;
                }

                JSONObject fanweiBodyData = JSONObject.parseObject(dynamicObject.getString("nckd_senddata_tag"));

                String url = sendFlowUrl + "?access_token=" + token + "&secret_key=" + secretkey;

                JSONObject returnObj = doPostByHttpClient(url, fanweiBodyData);
                if (returnObj == null) {
                    throw new KDException(WFErrorCode.httpRequestWrongResponse(), new Object[]{returnObj != null ? returnObj.toJSONString() : "return value is null!"});
                }

                String result = returnObj.toJSONString();

                if(kd.bos.util.StringUtils.isEmpty(result)){
                    logger.info("重发待办异常: 接口返回为空");
                    throw new WFMessageServiceException("创建泛微待办异常: 接口返回为空");
                }

                JSONObject msgObj = JSONObject.parseObject(result);
                if(msgObj.get("message") == null){
                    logger.info("重发待办异常: 接口返回message为空");
                    throw new WFMessageServiceException("创建泛微待办异常: 接口返回为空");
                }

                JSONObject message = msgObj.getJSONObject("message");

                if(message.get("errcode") == null){
                    logger.info("重发待办异常: 接口返回errorcode为空");
                    throw new WFMessageServiceException("创建泛微待办异常: 接口返回为空");
                }

                String sendStatus = "fail";
                String code = message.getString("errcode");
                if(!"200".equals(code)) {
                    String errCode = message.getString("errcode") == null ? "" : message.getString("errcode");
                    String msg = message.getString("errmsg") == null ? "" : message.getString("errmsg");

                    logger.info("EcologyOpPlugin：待办(" + dynamicObject.getString("number") + ")重发失败" + msg);
                    errMsg.append(dynamicObject.getString("number")).append(":").append("重发失败!").append(msg).append("\r\n");
                } else {
                    sendStatus = "success";
                    logger.info("EcologyOpPlugin：待办(" + dynamicObject.getString("number") + ")重发成功!");
                    errMsg.append(dynamicObject.getString("number")).append(":").append("重发成功!").append("\r\n");
                }

                if (result.length() < 200) {
                    dynamicObject.set("nckd_resultdata", result);
                } else {
                    dynamicObject.set("nckd_resultdata", result.substring(0, 200) + "...");
                }
                dynamicObject.set("nckd_resultdata_tag", result);
                dynamicObject.set("nckd_sendstatus", sendStatus);
                dynamicObject.set("nckd_sendurl", sendFlowUrl);

                listObj.add(dynamicObject);

                if(listObj.size() == 500) {
                    SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
                    listObj.clear();
                }
            }
            if(listObj.size() > 0) {
                SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
            }
        }

        if(errMsg != null && errMsg.length() > 0) {
            ////将错误信息返回到前端
            e.setCancelMessage(errMsg.toString());
            e.setCancel(true);
            System.out.println("EcologyOpPlugin 错误信息：" + errMsg.toString());
        }
    }

    public static JSONObject doPostByHttpClient(String url, JSONObject bodyData) {
        try {
            Map<String, String> headers = new HashMap();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("Accept", "application/json");
            logger.info(String.format("url[%s],data[%s]", url, bodyData.toJSONString()));
            System.out.println(String.format("url[%s],data[%s]", url, bodyData.toJSONString()));

            String responseEntify = HttpUtils.postjson(url, headers, bodyData.toJSONString());
            JSONObject result = (JSONObject)JSONObject.parse(responseEntify);
            return result;
        } catch (IOException var5) {
            throw new KDException(var5, WFErrorCode.httpRequestException(), new Object[]{var5.getMessage()});
        }
    }
}
