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

import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
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.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.workflow.exception.WFErrorCode;

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

public class RefreshFanWeiMsgStatusTask extends AbstractTask {
    private static Log logger = LogFactory.getLog(RefreshFanWeiMsgStatusTask.class);
    private static String KEY_ENTITY_LOG = "nckd_ecology";

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        String selectField = "nckd_ecologyurl, nckd_ecologycode, nckd_ecologmsgcode, nckd_ecologappid, nckd_ecologsecret, nckd_ecologspk, nckd_ecologyurlmsg";
        DynamicObject[] commonParams = BusinessDataServiceHelper.load("nckd_commonparams", selectField, null);
        String FANWEI_URL = "";
        if(commonParams.length > 0){
            FANWEI_URL = commonParams[0].getString("nckd_ecologyurl");
        } else {
            return;
        }

        QFilter qFilter = new QFilter("nckd_logtype", QCP.in, new String[]{"1", "5"});
        qFilter.and(new QFilter("nckd_sendstatus", QCP.equals, "fail"));

        DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load(KEY_ENTITY_LOG, "id", new QFilter[]{qFilter});
        logger.info("RefreshFanWeiMsgStatusTask：同步待办状态start");
        if (dynamicObjects != null && dynamicObjects.length > 0) {
            logger.info("RefreshFanWeiMsgStatusTask：共【" + dynamicObjects.length + "】条记录！");

            List<DynamicObject> listObj = new ArrayList<>();
            for(int i = 0; i < dynamicObjects.length; i++) {
                String id = dynamicObjects[i].getPkValue().toString();
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(id, KEY_ENTITY_LOG);

                JSONObject fanweiBodyData = JSONObject.parseObject(dynamicObject.getString("nckd_senddata_tag"));
//                FANWEI_URL = dynamicObject.getString("nckd_sendurl");
                String url = FANWEI_URL + "/rest/ofs/ReceiveRequestInfoByJson";
                JSONObject result = doPostByHttpClient(url, fanweiBodyData);
                if (result == null) {
                    throw new KDException(WFErrorCode.httpRequestWrongResponse(), new Object[]{result != null ? result.toJSONString() : "result is null!"});
                }

                String sendStatus = "fail";
                //失败
                if ("1".equals(result.getString("operResult"))) {
                    sendStatus = "success";
                    logger.info("RefreshFanWeiMsgStatusTask：待办(" + dynamicObject.getString("number") + ")重发成功!");
                } else {
                    logger.info("RefreshFanWeiMsgStatusTask：待办(" + dynamicObject.getString("number") + ")重发失败" + result.getString("message"));
                }

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

                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[]{}));
            }
        }
        logger.info("RefreshFanWeiMsgStatusTask：同步待办状态end");
    }

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