package com.system.kingdee;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.system.api.KingDeeApi;
import com.system.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Inori
 */
@Component
public class KingDeeCommonPushKingDeeApi {

    @Autowired
    private KingDeeApi kingDeeApi;

    public String kingDeeUpdateThirdData(List<Map<String, Object>> tempList, List<Map<String, String>> fieldList, Map<String, Object> data, String entryName, String kingDeeLogName, String queueId) {
        data.put("Model", thirdPartyFieldToKingDee(tempList, fieldList, entryName));
        return kingDeeApi.kingDeeDataPush(data, kingDeeLogName, queueId);
    }

    /**
     * thirdPartyField字段转换成金蝶云待添加(其实都是下推后修改)字段
     */
    public Map<String, Object> thirdPartyFieldToKingDee(List<Map<String, Object>> dataList, List<Map<String, String>> fieldList, String entryName) {
        Map<String, Object> modelMap = new LinkedHashMap<>(2);
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> map : dataList) {
            Map<String, Object> entityMap = new LinkedHashMap<>(10);

            for (Map<String, String> field : fieldList) {
                if ("true".equals(field.get("isDetailField"))) {
                    this.populateThirdPartyData(entityMap, map, field);
                    if (map.containsKey("ERP_SIC")) {
                        entityMap.put("ERP_SIC", map.get("ERP_SIC"));
                    }
                    if (map.containsKey("MES_CODE")) {
                        entityMap.put("MES_CODE", map.get("MES_CODE"));
                    }
                } else {
                    this.populateThirdPartyData(modelMap, map, field);
                }
            }

            list.add(entityMap);
        }
        modelMap.put(entryName, list);

        return modelMap;
    }

    private void populateThirdPartyData(Map<String, Object> temp, Map<String, Object> map, Map<String, String> field) {
        String kingDeeField = field.get("kingdeeField");
        String thirdPartyField = field.get("thirdPartyField");
        String indexField = field.get("indexField");

        if (!Constants.NULL.equals(String.valueOf(map.get(thirdPartyField)))) {
            if (StringUtil.isNotBlank(indexField)) {
                temp.put(kingDeeField, new HashMap<String, Object>(1) {{
                    put(indexField, map.get(thirdPartyField));
                }});
            } else {
                temp.put(kingDeeField, map.get(thirdPartyField));
            }
        }
    }

    public String kingDeeUpdateBySql(String sql, String kingDeeLogName, String queueId) {
        return kingDeeApi.kingDeeUpdateBySql(sql, kingDeeLogName, queueId);
    }

    public String sendPlugInUnit(String plugInUrl, String json) {
        return kingDeeApi.sendPlugInUnit(plugInUrl, json, 1);
    }


}
