package com.persagy.proxy.migration.service.Impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.persagy.dmp.basic.model.QueryCriteria;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.define.client.DigitalGraphDefineFacade;
import com.persagy.dmp.define.client.DigitalRelationDefineFacade;
import com.persagy.dmp.define.entity.GraphDefine;
import com.persagy.dmp.define.entity.RelationDefine;
import com.persagy.dmp.migrate.client.DigitalMigrateLogFacade;
import com.persagy.dmp.rwd.migrate.entity.SyncData;
import com.persagy.proxy.adm.constant.AdmCommonConstant;
import com.persagy.proxy.adm.request.AdmQueryCriteria;
import com.persagy.proxy.adm.request.AdmResponse;
import com.persagy.proxy.adm.utils.AdmQueryCriteriaHelper;
import com.persagy.proxy.common.entity.DmpResult;
import com.persagy.proxy.common.entity.InstanceUrlParam;
import com.persagy.proxy.migration.constant.MigrationTable;
import com.persagy.proxy.migration.service.MigrationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author lvxianyun
 * @title: MigrationLogServiceImpl
 * @projectName digital-delivery
 * @description: 数据迁移日志服务
 * @date 2022/1/5 17:22
 */
@Service
@Slf4j
public class MigrationLogServiceImpl implements MigrationLogService {
    @Override
    public AdmResponse queryMigrationLog(InstanceUrlParam context, AdmQueryCriteria request) {
        QueryCriteria queryCriteria = AdmQueryCriteriaHelper.toDmpCriteria(request);
        String groupCode = context.getGroupCode();
        String projectId = context.getProjectId();
        CommonResult<List<SyncData>> result = DigitalMigrateLogFacade.query(groupCode, projectId, context.getAppId(), context.getUserId(),queryCriteria);
        if(result.getResult().equals(DmpResult.SUCCESS)){
            if(CollUtil.isEmpty(result.getData())){
                return AdmResponse.success();
            }
            // 处理返回值
            List<SyncData> syncDatas = result.getData();
            processSynDatas(groupCode, projectId, syncDatas);
            AdmResponse response = AdmResponse.success(syncDatas);
            Long total = result.getCount() == null ? null : result.getCount().longValue();
            if(request.isOnlyCount()){
                response.setTotal(null);
                response.setCount(total);
            }else {
                response.setTotal(total);
            }
            response.setPageNumber(request.getPageNumber());
            response.setPageSize(request.getPageSize());
            return response;
        } else {
            return AdmResponse.failure(result.getMessage());
        }
    }


    /***
     * Description: 查询所有关系类型

     * @return : java.util.Map<java.lang.String,com.persagy.dmp.define.entity.RelationDefine>
     * @author : lijie
     * @date :2021/10/15 11:22
     * Update By lijie 2021/10/15 11:22
     */
    private Map<String, RelationDefine> queryAllRelationDefineMap(String groupCode,String projectId) {
        List<RelationDefine> relationDefines = DigitalRelationDefineFacade.query(groupCode, projectId,
                AdmCommonConstant.APP_ID, AdmCommonConstant.USER_ID, new QueryCriteria());
        if (CollUtil.isEmpty(relationDefines)){
            return new HashMap<>();
        }
        return relationDefines.stream()
                .collect(Collectors.toMap(relationDefine ->
                                relationDefine.getGraphCode() + StrUtil.DASHED + relationDefine.getCode(),
                        relationDefine -> relationDefine, (k1, k2) -> k1));
    }

    /**
     * 将同步日志中的relcode graphCode 翻译成name组合
     * @param groupCode
     * @param projectId
     * @param syncDatas
     */
    private void processSynDatas(String groupCode, String projectId, List<SyncData> syncDatas){
        // 1.获取所有的一级,二级图类型定义
        QueryCriteria parentCriteria = new QueryCriteria();
        List<GraphDefine> graphDefines = DigitalGraphDefineFacade.query(groupCode, projectId,
                AdmCommonConstant.APP_ID, AdmCommonConstant.USER_ID, parentCriteria);
        if (!CollUtil.isEmpty(graphDefines)){
            // 2.查询所有的边类型定义
            Map<String, RelationDefine> relationDefineMap = queryAllRelationDefineMap(groupCode,projectId);
            Map<String, GraphDefine> graphDefineMap = CollUtil.fieldValueMap(graphDefines, "code");
            for(SyncData syncData : syncDatas){
                if(!syncData.getTableName().equals(MigrationTable.DTRELATION.getCode())){
                   continue;
                }
                String code = syncData.getCode();
                if(StrUtil.isEmpty(code) || !code.contains(StrUtil.DASHED)){
                    continue;
                }
                //excel.setCode(String.join(StrUtil.DASHED, objectRelation.getGraphCode(), objectRelation.getRelCode()));
                String tempName = null;
                String graphName = graphDefineMap.get(code.split(StrUtil.DASHED)[0]).getName();
                String relName = relationDefineMap.get(code).getName();
                if(StrUtil.isAllNotEmpty(graphName, relName)){
                    tempName = String.join(StrUtil.DASHED, graphName, relName);
                }
                syncData.setName(tempName==null?"":tempName);
            }

        }

    }
}
