package fi.cas.task;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.kingdee.util.StringUtils;
import fi.cas.opplugin.HttpUtils;
import fi.cas.opplugin.PayBillToolUtil;
import fi.cas.opplugin.TypeUtils;
import fi.cas.opplugin.Utils;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
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 org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

public class AgentpaybillQueryStatusTast extends AbstractTask {
    private static final Log log = LogFactory.getLog(AgentpaybillQueryStatusTast.class);
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //获取要查询的数据。状态为已审批，支付状态为支付中，或支付失败。理论上只需要查支付中
        //支付失败用的要查查询，因为支付失败的可能驳回重新支付。
        Set<String> paystatusSet = new HashSet<>();
        paystatusSet.add("2");
        paystatusSet.add("6");

        QFilter filter = new QFilter("billstatus", QCP.equals, "C");
        filter.and("nckd_paystatus", QCP.in, paystatusSet);
        filter.and("nckd_fkcs", QCP.large_than, 0);

        Map<Object, DynamicObject> payinfos  = BusinessDataServiceHelper.loadFromCache("cas_agentpaybill", new QFilter[] {filter});
        DynamicObject jkpzxx = BusinessDataServiceHelper.loadSingle("nckd_jkpzxx",new QFilter[]{new QFilter("number","=","paytoJHX")});
        String url =  jkpzxx.getString("nckd_servername");
        boolean isESBApi = jkpzxx.getBoolean("nckd_isesb");

        for (DynamicObject dataEntity : payinfos.values()) {
            //调用接口查询付款状态
            JSONObject param = new JSONObject();
            PayBillToolUtil.headJson(param);
            JSONObject data = new JSONObject();
            data.put("ERP_INS_ID",dataEntity.getPkValue()+"");

            param.put("data",data);
            param.put("txDateTime",Utils.getData(new Date(), "yyyyMMddHHmmss"));
            param.put("batchNo",TypeUtils.nullToString(dataEntity.get("billno"))+"-"+TypeUtils.nullToString(dataEntity.get("nckd_bbh"))+"-"+Utils.getData(new Date(), "yyyyMMddHHmmss"));
            param.put("code","JY-NSTC-Q001");

            String bodyjson=param.toString();
            String billNum = dataEntity.getString("billno");
            log.info("单据号："+billNum+"传入参数"+param.toString());


//            JSONObject cbsReturnJson =PayBillToolUtil.JHXServiceQuery(url,bodyjson);//待补充，超时返回参数待修改，整体待重构

            /***************************************add by wanghaiwu 20225/05/24*************************************************************/
            //改成调用restful ebs api的方式
//            Map<String, String> header = new HashMap<>();
//            header.put("Content-Type", "application/json; charset=UTF-8");

            Map<String, String> tokenMap = PayBillToolUtil.getNtscToken();

            if(tokenMap == null){
                log.info("单据号：" + billNum + "查询失败： 获取token失败");
                continue;
            }

            if(!"0".equals(tokenMap.get("code"))){
                log.info("单据号：" + billNum + "查询失败：获取token失败, " + tokenMap.get("msg"));

                continue;
            }

            String token = tokenMap.get("msg");

            //改成调用轻舟的方式
            Map<String, String> header = new HashMap<>();
            header.put("Content-Type", "application/json; charset=UTF-8");
            header.put("Authorization", "Bearer " + token);

            //如果是esb接口，需要包一层参数
            if(isESBApi) {
                bodyjson = PayBillToolUtil.buildEsbApiBodyJSON(new JSONObject(bodyjson));
            }

            String apiResult = "";
            try {
                log.info("代发查询接口调用参数：" + bodyjson);

                apiResult = HttpUtils.postjson(url, header, bodyjson);
            } catch (IOException e) {
                log.info("单据号：" + billNum + "查询失败：" + e.getMessage());
                continue;
            }

            if(StringUtils.isEmpty(apiResult)){
                log.info("单据号：" + billNum + "查询结果为空");
                continue;
            }

            log.info("单据号：" + billNum + "返回参数" + apiResult);

//            JSONObject cbsReturnJson = new JSONObject(apiResult);

            JSONObject esbReturnJson = new JSONObject(apiResult);
            if(esbReturnJson.get("responseData") == null){
                log.info("单据号：" + billNum + ", 未正常返回responseData参数");
                return;
            }

            JSONArray esbJSONArray = esbReturnJson.getJSONArray("responseData");
            if(esbJSONArray == null || esbJSONArray.length() == 0){
                log.info("单据号：" + billNum + ", 未正常返回responseData参数");
                return;
            }

            JSONObject cbsReturnJson = esbJSONArray.getJSONObject(0);
            /************************************************************/

            log.info("单据号："+billNum+"返回参数"+cbsReturnJson.toString());
            if(cbsReturnJson==null||cbsReturnJson.get("data")==null){
            }else{
                String errcode = cbsReturnJson.get("resultCode")+"";
                JSONObject bodyinfo = cbsReturnJson.getJSONObject("data");
                if(bodyinfo!=null){
                    boolean isupdate = false;
                    if ("000000".equals(errcode)) {//已查询到，不代表支付成功
                        String zfstatus = bodyinfo.getString("RET_CODE");//0：付款成功  -1：付款失败 -2：流程中 -3:驳回 -4：部分成功
                        String errormsg =bodyinfo.getString("ERROR_MSG");
                        if("-2".equals(zfstatus)){//流程中
                            //判断原因是否有变化
                           String sbyy =  dataEntity.getString("nckd_sbyy");
                           if(errormsg == null || "".equals(errormsg)){//空不更新

                           }else if(errormsg.equals(sbyy)){//相等不更新

                           }else{
                               dataEntity.set("nckd_sbyy",errormsg);//错误信息更新
                               isupdate = true;
                           }

                        }else if("0".equals(zfstatus)){//成功
                            dataEntity.set("nckd_paystatus",3);
                            dataEntity.set("nckd_sbyy","支付成功");//错误信息更新
                            //分录信息
                            DynamicObjectCollection coll = dataEntity.getDynamicObjectCollection("entry");
                            for (int i = 0; i <coll.size() ; i++) {
                                coll.get(i).set("e_issuccess",true);//分录是否成功
                                coll.get(i).set("bankreturnmsg","成功");//返回信息
                            }
                            isupdate = true;
                        }else if("-1".equals(zfstatus)){//失败
                            dataEntity.set("nckd_paystatus",6);//支付失败
                            dataEntity.set("nckd_sbyy",errormsg);//错误信息更新
                            updateEntrys(dataEntity,bodyinfo);
                            isupdate = true;
                        }else if("-3".equals(zfstatus)){//驳回
                            dataEntity.set("nckd_paystatus",5);//驳回
                            dataEntity.set("nckd_sbyy",errormsg);//错误信息更新
                            updateEntrys(dataEntity,bodyinfo);
                            isupdate = true;
                        }else if("-4".equals(zfstatus)){//部分成功
                            dataEntity.set("nckd_paystatus",7);//部分成功
                            dataEntity.set("nckd_sbyy",errormsg);//错误信息更新
                            updateEntrys(dataEntity,bodyinfo);
                            isupdate = true;
                        }
                        if(isupdate){
                            SaveServiceHelper.update(new DynamicObject[]{dataEntity});
                            //存入日志表
                            PayBillToolUtil.saveAgentlog(dataEntity, bodyjson, cbsReturnJson.toString(), "6");

                        }
                    }
                }
            }
        }
    }

    //更新分录
    public void updateEntrys(DynamicObject dataEntity,JSONObject bodyinfo){
        DynamicObjectCollection coll = dataEntity.getDynamicObjectCollection("entry");
        JSONArray ITEM_LIST =  bodyinfo.getJSONArray("ITEM_LIST");
        for (int i = 0; i < ITEM_LIST.length(); i++) {
            JSONObject iteminfo =(JSONObject)ITEM_LIST.get(i);
            String itempk = iteminfo.get("ERP_PVT_ID")+"";
            String error_msg = iteminfo.get("ERROR_MSG")+"";
            String result_code = iteminfo.get("RESULT_CODE")+"";
            for (int j = 0; j <coll.size() ; j++) {
                String itempkvalue =  coll.get(j).getPkValue()+"";
                if(itempk.equals(itempkvalue)){
                    if("0".equals(result_code)){
                        coll.get(j).set("e_issuccess",true);
                        coll.get(j).set("bankreturnmsg","成功");//返回信息
                    }else{
                        coll.get(j).set("e_issuccess",false);
                        coll.get(j).set("bankreturnmsg",error_msg);//返回信息
                    }
                }
            }
        }
    }
}
