package nckd.jimin.jyyy.fi.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
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.fi.er.business.trip.model.TripSyncDataMappingModel;
import kd.fi.er.business.trip.service.function.AbstractOrgInvoke;
import kd.fi.er.business.trip.supplier.Supplier;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiOrgAndUserInvokeUtil;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiServiceUtil;
import kd.fi.er.business.trip.util.TripCommonUtil;
import kd.fi.er.business.trip.util.TripSyncConfigUtil;
import kd.fi.er.business.trip.util.TripSyncDataMappingUtil;
import kd.fi.er.common.ExternalConstants;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 滴滴-同步组织，全复制的7.0.8的标准源码后改造
 * @author wanghaiwu_kd
 * @date 2025/06/16
 */
public class DiDiTripOrgCusInvoke extends AbstractOrgInvoke<Set<JSONObject>> {
    private static Log logger = LogFactory.getLog(DiDiTripOrgCusInvoke.class);

    public DiDiTripOrgCusInvoke() {
    }

    protected String supplier() {
        return Supplier.DIDI.name();
    }

    protected Object getInnerData() {
        this.bizInfoObject = BusinessDataServiceHelper.loadSingle("er_biz_info", "lastsyncorgtamp", new QFilter[]{new QFilter("number", "=", this.supplier())});
        this.lastSyncOrgTamp = this.bizInfoObject.getString("lastsyncorgtamp");
        return this.queryChangeInfo();
    }

    private Map<String, JSONArray> queryChangeInfo() {
        Date changetime = TripCommonUtil.convertToDate(this.lastSyncOrgTamp);
        int paramValue = TripSyncConfigUtil.getIntValue("budget_center_id", 1);
        QFilter qFilter;
        if (3 == paramValue) {
            qFilter = new QFilter("view", "=", 10L);
        } else {
            qFilter = new QFilter("view", "=", 1L);
        }

        if (this.params != null && null != this.params.get("orgList")) {
            qFilter.and(new QFilter("org", "in", this.params.get("orgList")));
        } else {
            QFilter createtimeFilter = new QFilter("createtime", ">=", changetime);
            QFilter modifytimeFilter = new QFilter("modifytime", ">=", changetime);
            QFilter timeFilter = createtimeFilter.or(modifytimeFilter);
            qFilter.and(timeFilter);
        }

        DynamicObject[] orgDOs = BusinessDataServiceHelper.load("bos_org_structure", "fullname ,number, org, org.id，org.name, parent,parent.id, createtime, modifytime, isfreeze", new QFilter[]{qFilter}, "level");
        if (orgDOs != null && orgDOs.length >= 1) {
            Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
            String client_id = (String)supplierMap.get("appkey");
            String access_token = DiDiServiceUtil.getCacheToken(new Date());
            logger.info("Line 76 access_token{}", access_token);
            if (access_token == null) {
                this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，获取滴滴Token为空，请检查配置。", "DiDiTripOrgInvoke_1", "fi-er-business", new Object[0]));
                this.tripSyncLogParam.setStatus("B");
                return null;
            } else {
                String company_id = (String)supplierMap.get("orationid");
                int type = 1;
                int budget_cycle = 0;
                int total_quota = 0;
                QFilter uFilter = new QFilter("server", "=", this.supplier());
                uFilter.and(new QFilter("datatype", "=", "bos_org"));
                Map<Object, Object> dataMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(uFilter, "innerdataid", "outdataid");
                Map<String, JSONArray> postOrgMap = new HashMap();
                JSONArray addOrgList = new JSONArray();
                JSONArray updateOrgList = new JSONArray();
                logger.info("orgDOS size{}", orgDOs.length);
                Arrays.stream(orgDOs).forEach((orgDO) -> {
                    String name = orgDO.getString("fullname");
                    String out_budget_id = String.valueOf(orgDO.getLong("org.id"));

                    HashMap<String, Object> signMap = new HashMap();
                    signMap.put("client_id", client_id);
                    signMap.put("access_token", access_token);
                    signMap.put("company_id", company_id);
                    signMap.put("budget_cycle", budget_cycle);
                    signMap.put("total_quota", total_quota);
                    signMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
                    signMap.put("type", type);
                    signMap.put("name", name);
                    signMap.put("out_budget_id", String.valueOf(out_budget_id));

                    //二开，增加上级同步，获取上级组织ID映射的DiDi组织ID
                    String parentId_DiDi = getDiDiOrgId(orgDO.getLong("parent.id"));
                    if(StringUtils.isNotEmpty(parentId_DiDi)) {
                        signMap.put("parent_id", String.valueOf(parentId_DiDi));
                    }

                    String signKey = (String)supplierMap.get("reservedfield1");
                    String addDeptSign = DiDiServiceUtil.genSign(signMap, signKey);
                    JSONObject addOrgObj = new JSONObject(signMap);
                    addOrgObj.put("sign", addDeptSign);
                    addOrgList.add(addOrgObj);
                    logger.info("Line 118 addOrgList size{}", addOrgList.size());
                    Object externalOrgId = dataMappingMap.get(Long.valueOf(out_budget_id));
                    if (dataMappingMap != null && dataMappingMap.size() > 0 && externalOrgId != null) {
                        signMap.put("id", externalOrgId);
                        signKey = (String)supplierMap.get("reservedfield1");
                        String editDeptSign = DiDiServiceUtil.genSign(signMap, signKey);
                        JSONObject editOrgObj = new JSONObject(signMap);
                        editOrgObj.put("sign", editDeptSign);
                        editOrgObj.remove("sign_key");
                        updateOrgList.add(editOrgObj);
                    }

                });
                logger.info(String.format("addOrgList size %1$s updateOrgList size %2$s", addOrgList.size(), updateOrgList.size()));
                postOrgMap.put("add", addOrgList);
                postOrgMap.put("edit", updateOrgList);
                return postOrgMap;
            }
        } else {
            logger.info("Line 68 orgDOs in");
            this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，组织更新，组织为空。", "DiDiTripOrgInvoke_0", "fi-er-business", new Object[0]));
            return null;
        }
    }

    protected Object convert(Object info) {
        return info;
    }

    protected String batPushProcess(Object data) {
        Map<String, JSONArray> postOrgJSONArrayMap = (Map)data;
        if (postOrgJSONArrayMap != null && postOrgJSONArrayMap.size() > 0) {
            AtomicReference<Boolean> successflag = new AtomicReference(true);
            postOrgJSONArrayMap.forEach((syncKey, postOrgJSONArray) -> {
                String url = "";
                switch (syncKey) {
                    case "add":
                        url = (String)ExternalConstants.DIDIURLMAP.get("BudgetCenterAddKey");
                        break;
                    case "edit":
                        url = (String)ExternalConstants.DIDIURLMAP.get("BudgetCenterEditKey");
                }

                if (StringUtils.isNotBlank(url)) {
                    Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
                    String signKey = (String)supplierMap.get("reservedfield1");
                    List<TripSyncDataMappingModel> dataMappingList = DiDiOrgAndUserInvokeUtil.postChangeData(successflag, syncKey, "bos_org", postOrgJSONArray, url, this.supplier(), this.tripSyncLogParam, this.tripSyncLogParamList, signKey);
                    TripSyncDataMappingUtil.saveTripSyncDataMapping(dataMappingList);
                }

            });
            String code = "300";
            if ((Boolean)successflag.get()) {
                code = "200";
            }

            return code;
        } else {
            String code = "200";
            if (this.tripSyncLogParam.getStatus().equals("B")) {
                code = "300";
            }

            if (StringUtils.isEmpty(this.tripSyncLogParam.getMessage())) {
                this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，组织更新，组织为空。", "DiDiTripOrgInvoke_0", "fi-er-business", new Object[0]));
            }

            return code;
        }
    }

    /**
     * 根据星瀚组织ID查询映射的DiDi组织ID
     * @param orgId
     * @return
     */
    private String getDiDiOrgId(Long orgId){
        String didiOrgId = "";

        if(orgId > 0L){
            QFilter qFilter = new QFilter("server", QCP.equals, "DIDI");
            qFilter.and(new QFilter("datatype", QCP.equals, "bos_org"));
            qFilter.and(new QFilter("innerdataid", QCP.equals, orgId));

            DynamicObject mappingInfo = BusinessDataServiceHelper.loadSingle("er_tripsync_datamapping", qFilter.toArray());
            if(mappingInfo != null){
                didiOrgId = mappingInfo.getString("outdataid");
            }
        }

        return didiOrgId;
    }
}
