package com.system.kingdee;

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

import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private KingDeeApi kingDeeApi;

    @Autowired
    private DatabaseTableMapper databaseTableMapper;

    @Autowired
    private FormTableStructureConstants formTableStructureConstants;


    /**
     * 获取金蝶云数据
     */
    public List<Map<String, Object>> synchronization(String sFormId, String mesEntryName, List<Map<String, String>> fieldList, Map<String, String> where, String kingDeeLogName, String queueId) {
        Map<String, String> key = KingDeeCommonSynConstants.purchaseKingDee(fieldList);
        List<List<Object>> result = kingDeeApi.synchronization(sFormId, key, where, kingDeeLogName, queueId);

        this.databaseTableDataCreate(sFormId, result, fieldList, queueId);
        return purchaseIms(mesEntryName, result, fieldList, queueId);
    }

    /**
     * 封装第三方字段
     */
    private List<Map<String, Object>> purchaseIms(String mesEntryName, List<List<Object>> list, List<Map<String, String>> fieldList, String queueId) {
        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>> mesList = new ArrayList<>();
                map.put("QUEUE_ID", queueId);

                KingDeeCommonSynConstants.purchaseIms(list, fieldList, map, mesList);

                if (!CollectionUtils.isEmpty(mesList)) {
                    map.put(mesEntryName, mesList);
                }
                result.add(map);
            } 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;
    }

    /**
     * 数据库表数据创建
     */
    private void databaseTableDataCreate(String sFormId, List<List<Object>> result, List<Map<String, String>> fieldList, String queueId) {
        Map<String, String> temp = formTableStructureConstants.get(sFormId);
        if (!CollectionUtils.isEmpty(temp)) {
            List<String> dbFieldList = fieldList.stream().map(m -> String.valueOf(m.get("thirdPartyField"))).collect(Collectors.toList());
            dbFieldList.add("queue_id");

            List<Map<String, Object>> dataList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(result)) {
                String errorName = "Errors";
                if (!result.get(0).get(0).toString().contains(errorName)) {
                    for (List<Object> objectList : result) {
                        Map<String, Object> map = new LinkedHashMap<>();
                        for (int i = 0; i < fieldList.size(); i++) {
                            map.put(fieldList.get(i).get("thirdPartyField"), objectList.get(i));
                        }
                        map.put("queue_id", queueId);

                        dataList.add(map);
                    }

                    try {
                        databaseTableMapper.databaseTableDataCreate(sFormId.toLowerCase(), dbFieldList, dataList);
                    } catch (Exception e) {
                        System.out.println("数据库表: " + sFormId.toLowerCase() + " 唯一标识: " + queueId + " 的数据创建失败");
                    }
                }
            }
        }
    }

    /**
     * SQL查询结果: 数据库表数据创建
     */
    public void databaseTableDataCreateBySql(String sFormId, List<Object> result, List<Map<String, String>> fieldList, String queueId) {
        Map<String, String> map = formTableStructureConstants.get(sFormId);
        if (!CollectionUtils.isEmpty(map)) {
            List<String> dbFieldList = fieldList.stream().map(m -> String.valueOf(m.get("thirdPartyField"))).collect(Collectors.toList());
            dbFieldList.add("queue_id");

            List<Map<String, Object>> dataList = new ArrayList<>();

            for (Object object : result) {
                Map<String, Object> temp = JsonUtil.toMap(JsonUtil.toString(object), String.class, Object.class);

                Map<String, Object> request = new LinkedHashMap<>();
                for (Map<String, String> temp02Map : fieldList) {
                    request.put(temp02Map.get("thirdPartyField"), temp.get(temp02Map.get("kingdeeField")));
                }
                dataList.add(request);
            }
            try {
                databaseTableMapper.databaseTableDataCreate(sFormId.toLowerCase(), dbFieldList, dataList);
            } catch (Exception e) {
                System.out.println("数据库表: " + sFormId.toLowerCase() + " 唯一标识: " + queueId + " 的数据创建失败");
            }
        }
    }

    /**
     * 数据库表数据删除
     */
    public void databaseTableDataDelete(String sFormId, String queueId) {
        databaseTableMapper.databaseTableDataDelete(sFormId.toLowerCase(), queueId);
    }

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

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

    public String kingDeeSelectBySql(String sql, String kingDeeName, String queueId) {
        return kingDeeApi.kingDeeSelectBySql(sql, kingDeeName, queueId);
    }


}
