package com.system.serivce.impl;

import com.system.constants.KingDeeCommonSynConstants;
import com.system.kingdee.KingDeeCommonGetKingDeeApi;
import com.system.scheduler.LicScheduler;
import com.system.serivce.IKingDeeCommonGetService;
import com.system.transfer.kingdee.KingDeeDataListInVo;
import com.system.transfer.response.RestResponse;
import com.system.utils.JsonUtil;
import com.system.utils.ThirdPartyLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Inori
 */
@Service
public class KingDeeCommonGetServiceImpl implements IKingDeeCommonGetService {

    @Autowired
    private KingDeeCommonSynConstants kingDeeCommonSynConstants;

    @Autowired
    private KingDeeCommonGetKingDeeApi kingDeeCommonGetKingDeeApi;

    @Autowired
    private ThirdPartyLogUtil thirdPartyLogUtil;

    @Autowired
    private LicScheduler licScheduler;


    @Override
    public RestResponse kingDeeDataList(KingDeeDataListInVo inVo) {
        if (!licScheduler.isFlag()) {
            return RestResponse.fail("操作失败！权限限制");
        }

        String queueId = inVo.getQueueId();

        Map<String, String> map = kingDeeCommonSynConstants.getKingDee(inVo.getDocType());
        if (org.springframework.util.CollectionUtils.isEmpty(map)) {
            return RestResponse.fail("自定义查询失败! docType为: " + inVo.getDocType() + " 的表单ERP-MES标识不存在");
        }

        Integer id = thirdPartyLogUtil.thirdPartyLogCreate(map.get("name"), inVo.getDocType(), queueId, JsonUtil.toString(inVo.getData()), null, 0);

        List<Object> tempList = JsonUtil.toList(map.get("kingdeeFiledDetail"), Object.class);
        List<Map<String, String>> fieldList = tempList.stream().map(m -> JsonUtil.toMap(JsonUtil.toString(m), String.class, String.class)).collect(Collectors.toList());

        Map<String, String> where = new HashMap<>(5);
        if (!CollectionUtils.isEmpty(inVo.getData())) {
            for (Map.Entry<String, Object> entry : inVo.getData().entrySet()) {
                where.put(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }

        List<Map<String, Object>> result = kingDeeCommonGetKingDeeApi.getKingDeeData(map.get("sFormId"), queueId, map.get("mesEntryName"), fieldList, where, map.get("name"));
        if (!CollectionUtils.isEmpty(result)) {
            String temp = "false";
            if (result.get(0).containsKey(temp)) {
                thirdPartyLogUtil.toThirdPartyLogUpdate(id, JsonUtil.toString(result), String.valueOf(result.get(0).get(temp)));
                return RestResponse.fail(String.valueOf(result.get(0).get(temp)));
            }
        }
        thirdPartyLogUtil.toThirdPartyLogUpdate(id, JsonUtil.toString(result), "");
        return RestResponse.success(result);
    }


}
