package com.system.serivce.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.system.constants.FormTableStructureConstants;
import com.system.constants.KingDeeCommonSynConstants;
import com.system.constants.KingDeeConstants;
import com.system.dao.SynchronizationRecordsMapper;
import com.system.kingdee.KingDeeCommonSynKingDeeApi;
import com.system.serivce.IKingDeeCommonSynService;
import com.system.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Inori
 */
@Service
public class KingDeeCommonSynServiceImpl implements IKingDeeCommonSynService {

    @Autowired
    private KingDeeCommonSynConstants kingDeeCommonSynConstants;

    @Autowired
    private KingDeeCommonSynKingDeeApi kingDeeCommonSynKingDeeApi;

    @Autowired
    private FormTableStructureConstants formTableStructureConstants;

    @Autowired
    private SynchronizationRecordsMapper synchronizationRecordsMapper;

    @Autowired
    private KingDeeLogUtil kingDeeLogUtil;

    @Autowired
    private ThirdPartyLogUtil thirdPartyLogUtil;


    @Override
    public void synchronization(Integer id, String sFormId, Integer dataId, Integer entryId) {
        String queueId = SnowFlakeIdUtil.generateId().toString();
        //查询表单
        Map<String, String> map = kingDeeCommonSynConstants.get(sFormId);
        if (CollectionUtils.isEmpty(map)) {
            kingDeeLogUtil.kingDeePushLogCreate("自定义同步失败", queueId, "sFormId为: " + sFormId + " 的表单不存在", null);
            synchronizationRecordsMapper.synchronizationRecordsUpdate(id, queueId, "sFormId为: " + sFormId + " 的表单不存在", 2);
            return;
        }

        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());

        List<Map<String, Object>> list = new ArrayList<>();
        String customSql = map.get("customSql");
        List<Object> objectList = new ArrayList<>();
        if (StringUtil.isNotBlank(customSql)) {
            customSql = customSql.replaceAll("@" + map.get("primaryKeyField"), String.valueOf(dataId));
            customSql = customSql.replaceAll("@" + map.get("entryPrimaryKeyField"), String.valueOf(entryId));
            //DES加密
            customSql = DesHelperUtil.encrypt(customSql, StandardCharsets.UTF_8, "MES&&DES");
            String customSqlResult = kingDeeCommonSynKingDeeApi.kingDeeSelectBySql(customSql, map.get("name") + "执行SQL", queueId);

            Map<String, Object> temp = JsonUtil.toMap(customSqlResult, String.class, Object.class);
            if (!CollectionUtils.isEmpty(temp)) {
                if (temp.containsKey(KingDeeConstants.CODE_NAME) && KingDeeConstants.SUCCESS_CODE.equals(temp.get(KingDeeConstants.CODE_NAME))) {
                    objectList = JsonUtil.toList(JsonUtil.toString(temp.get("data")), Object.class);
                    if (!CollectionUtils.isEmpty(objectList)) {
                        Map<String, Object> request = new LinkedHashMap<>();
                        KingDeeCommonSynConstants.purchaseSqlIms(objectList, fieldList, request);
                        list.add(request);
                        kingDeeCommonSynKingDeeApi.databaseTableDataCreateBySql(sFormId, objectList, fieldList, queueId);
                    }
                } else {
                    synchronizationRecordsMapper.synchronizationRecordsUpdate(id, queueId, customSqlResult, 2);
                    return;
                }
            } else {
                synchronizationRecordsMapper.synchronizationRecordsUpdate(id, queueId, customSqlResult, 2);
                return;
            }
        } else {
            //设置需要同步的主键和分录主键
            Map<String, String> where = new HashMap<>(1);
            where.put(map.get("primaryKeyField"), dataId.toString());
            String entryPrimaryKeyField = map.get("entryPrimaryKeyField");
            if (StringUtil.isNotBlank(entryPrimaryKeyField)) {
                if (StringUtil.isNotNull(entryId)) {
                    where.put(entryPrimaryKeyField, entryId.toString());
                }
            }

            list = kingDeeCommonSynKingDeeApi.synchronization(map.get("sFormId"), map.get("mesEntryName"), fieldList, where, map.get("name"), queueId);
            if (list.get(0).containsKey(Constants.FALSE)) {
                synchronizationRecordsMapper.synchronizationRecordsUpdate(id, queueId, list.get(0).get(Constants.FALSE).toString(), 2);
                return;
            }
        }

        String plugInUrl = map.get("plugInUrl");
        if (StringUtil.isNotBlank(plugInUrl)) {
            Map<String, Object> request = new HashMap<>(1);
            if (!CollectionUtils.isEmpty(objectList)) {
                request.put("data", objectList);
            } else {
                request.put("data", list);
            }
            String plugInUrlResult = kingDeeCommonSynKingDeeApi.sendPlugInUnit(plugInUrl, JsonUtil.toString(request));
            thirdPartyLogUtil.thirdPartyLogCreate(map.get("name") + "执行插件", map.get("docType"), queueId, JsonUtil.toString(request), plugInUrlResult, 1);

            List<Object> temp01List = JsonUtil.toList(plugInUrlResult, Object.class);
            if (!CollectionUtils.isEmpty(temp01List)) {
                list = temp01List.stream().map(m -> JsonUtil.toMap(JsonUtil.toString(m), String.class, Object.class)).collect(Collectors.toList());
            }
        }

        this.purchaseIms(map, list, id, queueId);
    }

    /**
     * 同步至MES
     */
    private void purchaseIms(Map<String, String> map, List<Map<String, Object>> list, Integer id, String queueId) {
        //将数据包装成IMS格式
        Map<String, Object> request = new LinkedHashMap<>(3);
        request.put("docType", map.get("docType"));
        request.put("updateType", "UPDATE");
        request.put("data", list);
        String json = JsonUtil.toString(request);
        String result = kingDeeCommonSynKingDeeApi.sendThirdParty(json);
        //记录IMS日志
        thirdPartyLogUtil.sendThirdPartyLogCreate(map.get("name"), map.get("docType"), queueId, json, result, id);

        Map<String, String> config = formTableStructureConstants.get(map.get("sFormId"));
        Map<String, Object> temp = JsonUtil.toMap(result, String.class, Object.class);
        if (!CollectionUtils.isEmpty(temp)) {
            if (!KingDeeConstants.SUCCESS_CODE.equals(temp.get(KingDeeConstants.CODE_NAME))) {
                if (!CollectionUtils.isEmpty(config)) {
                    kingDeeCommonSynKingDeeApi.databaseTableDataDelete(map.get("sFormId"), queueId);
                }
            }
            if (KingDeeConstants.OVERTIME_CODE.equals(temp.get(KingDeeConstants.CODE_NAME))) {
                Thread.currentThread().interrupt();
            }
        } else {
            if (!CollectionUtils.isEmpty(config)) {
                kingDeeCommonSynKingDeeApi.databaseTableDataDelete(map.get("sFormId"), queueId);
            }
        }
    }


}
