package com.system.kingdee;

import com.system.api.KingDeeApi;
import com.system.utils.JsonUtil;
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.*;

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

    private final static String S_FORM_ID = "LQKJ_IMSSync";

    private Map<String, String> key = new LinkedHashMap<>();

    @Autowired
    private KingDeeApi kingDeeApi;


    public KingDeeSynchronizationApi() {
        /* 单据头实体主键 */
        this.key.put("FID", "FID");
        /* 同步记录数据内码 */
        this.key.put("F_LQKJ_SyncDataId", "F_LQKJ_SyncDataId");
        /* 同步记录数据分录内码 */
        this.key.put("F_LQKJ_SyncDataEntryId", "F_LQKJ_SyncDataEntryId");
        /* 同步记录表单 */
        this.key.put("F_LQKJ_Syncbill", "F_LQKJ_Syncbill");
        /* 同步 */
        this.key.put("F_LQKJ_SyncCheck", "F_LQKJ_SyncCheck");
    }

    /**
     * 查询同步为0的数据
     */
    public List<Map<String, Object>> synchronization() {
        //查询未同步数据
        List<List<Object>> list = kingDeeApi.getKingDeeData(S_FORM_ID, "", key, new HashMap<String, String>(1) {{
            put("F_LQKJ_SyncCheck", "0");
        }}, "");
        return purchaseTo(list);
    }

    /**
     * 将查询到的数据封装成本地字段
     */
    private List<Map<String, Object>> purchaseTo(List<List<Object>> tempList) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tempList)) {
            String errorName = "Errors";
            if (!tempList.get(0).get(0).toString().contains(errorName)) {
                for (List<Object> list : tempList) {
                    Map<String, Object> map = new HashMap<>(4);
                    map.put("fid", list.get(0));
                    map.put("dataId", list.get(1));
                    map.put("entryId", StringUtil.isNotBlank((String) list.get(2)) ? list.get(2) : null);
                    map.put("sFormId", list.get(3));
                    map.put("synchronization", list.get(4));
                    result.add(map);
                }
            }
        }
        return result;
    }

    public void batchAdd(List<Map<String, Object>> tempList) {
        kingDeeApi.batchAdd(S_FORM_ID, JsonUtil.toString(tempList));
    }


}
