package com.system.kingdee;

import com.system.api.KingDeeApi;
import com.system.constants.KingDeeCommonSynConstants;
import com.system.utils.KingDeeUtil;
import com.system.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

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

    @Autowired
    private KingDeeApi kingDeeApi;


    public List<Map<String, Object>> getKingDeeData(String sFormId, String queueId, String mesEntryName, List<Map<String, String>> fieldList, Map<String, String> where, String kingDeeLogName) {
        Map<String, String> key = KingDeeCommonSynConstants.purchaseKingDee(fieldList);
        List<List<Object>> result = kingDeeApi.getKingDeeData(sFormId, queueId, key, where, kingDeeLogName);
        return purchaseIms(result, fieldList, mesEntryName);
    }

    /**
     * 封装第三方字段
     */
    private List<Map<String, Object>> purchaseIms(List<List<Object>> list, List<Map<String, String>> fieldList, String mesEntryName) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            String errorName = "Errors";
            if (!list.get(0).get(0).toString().contains(errorName)) {
                Map<String, Object> map = new HashMap<>(fieldList.size());
                List<Map<String, Object>> imsList = new ArrayList<>();
                //判断是否查询的是多个数据
                if (list.size() == 1){
                    //只是单条数据
                    KingDeeCommonSynConstants.purchaseIms(list, fieldList, map, imsList);

                    if (!StringUtil.isEmpty(mesEntryName)) {
                        map.put(mesEntryName, imsList);
                    } else {
                        map.put("children", imsList);
                    }
                    result.add(map);
                }else {
                    //有多条数据
                    KingDeeCommonSynConstants.purchaseMultipleIms(list, fieldList, map, result, mesEntryName);
                }
            } else {
                //如果有错误信息则返回
                String message = KingDeeUtil.getMessage(list.get(0).get(0));

                Map<String, Object> resultMap = new HashMap<>(1);
                resultMap.put("false", message);
                result.add(resultMap);
            }
        }
        return result;
    }


}
