/*
* Copyright (c) 京北方信息技术股份有限公司 Corporation 2022 . All rights reserved.
*
*/
package net.northking.cctp.platform.api.comlibrary.service;

import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.QueryOrderBy;

import net.northking.cctp.platform.constants.PlatformConstants;
import net.northking.cctp.platform.db.entity.CpComponentLibrary;
import net.northking.cctp.platform.db.entity.CpComponentParamter;
import net.northking.cctp.platform.db.service.CpComponentLibraryService;
import net.northking.cctp.platform.db.service.CpComponentListService;
import net.northking.cctp.platform.db.entity.CpComponentList;

import net.northking.cctp.platform.db.service.CpComponentParamterService;
import net.northking.cctp.platform.dto.comlibrary.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 组件清单服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "CpComponentListApiServiceImpl")
public class CpComponentListApiServiceImpl implements CpComponentListApiService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(CpComponentListApiServiceImpl.class);

  @Autowired
  private CpComponentListService cpComponentListService;

  @Autowired
  private CpComponentLibraryService cpComponentLibraryService;

  @Autowired
  private CpComponentParamterService cpComponentParamterService;

  @Override
  @DatabaseReadOnly
  public Pagination<CpComponentListDetailDto> pagingQuery(QueryByPage<CpComponentListQueryDto> queryByPage)
  {
    List<QueryOrderBy> orderList = queryByPage.getOrderByList();
    // 用例列表默认按照用例编号倒序排列
    if (orderList.isEmpty()) {
      QueryOrderBy queryOrderBy = new QueryOrderBy();
      queryOrderBy.desc(PlatformConstants.COM_NAME);
      orderList.add(queryOrderBy);
    }
    return this.cpComponentListService.pagingQuery(queryByPage);
  }


  @Override
  @DatabaseReadOnly
  public CpComponentListDetailDto findByPK(String uuid)
  {
    CpComponentList example = new CpComponentList();
    example.setId(uuid);
    List<CpComponentList> entitys = this.cpComponentListService.query(example);
    if (entitys.isEmpty())
    {
      return null;
    }

    CpComponentListDetailDto dto = new CpComponentListDetailDto();
    BeanUtils.copyProperties(entitys.get(0), dto);
    //获取参数
    CpComponentParamter param = new CpComponentParamter();
    param.setComId(dto.getId());
    List<CpComponentParamter> parList = cpComponentParamterService.query(param);
    dto.setParamList(parList);
    return dto;
  }

  /**
   * 获取组件列表
   * @param target
   * @return
   */
  @Override
  public List<CpComLibraryTree> getComponentTree(CpComponentLibraryQueryDto target) {
    CpComponentList query = new CpComponentList();
    query.setLibraryId(target.getLibId());
    query.setComCategory(target.getComCategory());
    return cpComponentListService.queryComListTree(query);
  }

  @Override
  public Pagination<CpComponentListDetailDto> pagingQueryNew(QueryByPage<CpComponentListQueryDto> queryByPage) {
    List<QueryOrderBy> orderList = queryByPage.getOrderByList();
    // 用例列表默认按照用例编号倒序排列
    if (orderList.isEmpty()) {
      QueryOrderBy queryOrderBy = new QueryOrderBy();
      queryOrderBy.desc(PlatformConstants.COM_NAME);
      orderList.add(queryOrderBy);
    }
    return this.cpComponentListService.pagingQueryNew(queryByPage);
  }



  @Override
  public List<RecordComTreeDto> getComTreeByType(RecordComTreeQueryDto query) {
    //脚本录制查询类别接口只能查接口加基础，其他都可以查接口加基础
    //根据组件的类别去逆向还原组件库
    CpComponentList entity = new CpComponentList();
    entity.setLibraryId(query.getTreeId());
    entity.setComCategory(PlatformConstants.COM_CATEGORY);//查询组件
    String att = PlatformConstants.KEYWORD_INFO_COMATTRIBUTES;//默认会查基础组件
    if(query.getRecordType().equals(PlatformConstants.INT_ONE)){
      entity.setComAttributes(att + PlatformConstants.STR_OR_ONE);
    }else{
      entity.setComAttributes(att + PlatformConstants.STR_OR_ONE_OR + query.getRecordType());
    }
    List<RecordComTreeDto> result = new ArrayList<>();
    if (PlatformConstants.TREE_NODE_TOP.equals(query.getTreeId())){
      //查目录
      List<CpComponentLibrary>  list = cpComponentLibraryService.queryRecordList(entity);
      for (CpComponentLibrary tree : list) {
        RecordComTreeDto record = new RecordComTreeDto();
        record.setTreeId(tree.getId());
        record.setTreeName(tree.getLibraryName());
        record.setVersion(tree.getLibraryVersion());
        record.setTreeAlias(tree.getLibraryAlias());
        record.setIsLeaf(PlatformConstants.STR_ZERO);//非叶子节点
        record.setIsCom(PlatformConstants.STR_ZERO);//为目录
        record.setMemo(tree.getLibraryIntro());
        record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
        result.add(record);
      }
    }else{
      //查组件
      List<CpComponentList> list = cpComponentListService.queryRecordList(entity);
      List<String> ids = new ArrayList<>();
      list.forEach(com -> ids.add(com.getId()));
      List<CpComponentParamter> paramList = cpComponentParamterService.queryParamByComIds(ids);
      Map<String,List<RecordComParamDto>> map = new HashMap<>();
      for (CpComponentParamter param : paramList) {
        RecordComParamDto dto = new RecordComParamDto();
        BeanUtils.copyProperties(param,dto);
        if(map.containsKey(param.getComId())){
          map.get(param.getComId()).add(dto);
        }else{
          List<RecordComParamDto> one = new ArrayList<>();
          one.add(dto);
          map.put(param.getComId(),one);
        }
      }
      Map<String,CpComponentLibrary> libMap = getLibName();
      for (CpComponentList com : list) {
        RecordComTreeDto record = new RecordComTreeDto();
        record.setTreeId(com.getId());
        record.setTreeName(com.getComName());
        record.setTreeAlias(com.getComAlias());
        record.setIsLeaf(PlatformConstants.STR_ONE);//叶子节点
        record.setIsCom(PlatformConstants.STR_ONE);//组件
        record.setMemo(com.getComIntro());
        record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
        record.setParamList(map.get(com.getId()));
        record.setLibraryName(libMap.get(com.getLibraryId()).getLibraryName());
        record.setVersion(libMap.get(com.getLibraryId()).getLibraryVersion());
        result.add(record);
      }
    }
    return result;
  }

  @Override
  public List<RecordComTreeDto> getComTreeForLike(RecordComTreeQueryDto query) {
    CpComponentList entity = new CpComponentList();
    entity.setComCategory(PlatformConstants.STR_ZERO);//查询组件
    entity.setComAlias(query.getSelectName());
    String att = PlatformConstants.STR_ZERO;//默认会查基础组件
    if(query.getRecordType()==1){
      entity.setComAttributes(att+PlatformConstants.STR_OR_ONE);
    }else{
      entity.setComAttributes(att+PlatformConstants.STR_OR_ONE_OR +query.getRecordType());
    }
    List<RecordComTreeDto> result = new ArrayList<>();

    List<CpComponentList> list = cpComponentListService.queryRecordList(entity);
    Map<String,List<RecordComTreeDto>> comMap = new HashMap<>();
    if(list.size()>0){
      List<String> ids = new ArrayList<>();
      list.forEach(com -> ids.add(com.getId()));
      List<CpComponentParamter> paramList = cpComponentParamterService.queryParamByComIds(ids);
      Map<String,List<RecordComParamDto>> map = new HashMap<>();
      for (CpComponentParamter param : paramList) {
        RecordComParamDto dto = new RecordComParamDto();
        BeanUtils.copyProperties(param,dto);
        if(map.containsKey(param.getComId())){
          map.get(param.getComId()).add(dto);
        }else{
          List<RecordComParamDto> one = new ArrayList<>();
          one.add(dto);
          map.put(param.getComId(),one);
        }
      }
      Map<String,CpComponentLibrary> libMap = getLibName();
      for (CpComponentList com : list) {
        RecordComTreeDto record = new RecordComTreeDto();
        record.setTreeId(com.getId());
        record.setTreeName(com.getComName());
        record.setTreeAlias(com.getComAlias());
        record.setIsLeaf(PlatformConstants.STR_ONE);//叶子节点
        record.setIsCom(PlatformConstants.STR_ONE);//组件
        record.setMemo(com.getComIntro());
        record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
        record.setLibraryName(libMap.get(com.getLibraryId()).getLibraryName());
        record.setVersion(libMap.get(com.getLibraryId()).getLibraryVersion());
        record.setParamList(map.get(com.getId()));

        if(comMap.containsKey(com.getLibraryId())){
          comMap.get(com.getLibraryId()).add(record);
        }else{
          List<RecordComTreeDto> one = new ArrayList<>();
          one.add(record);
          comMap.put(com.getLibraryId(),one);
        }
      }
    }

    //组装目录树
    List<CpComponentLibrary>  treeList = cpComponentLibraryService.queryRecordList(entity);
    for (CpComponentLibrary tree : treeList) {
      if(comMap.containsKey(tree.getId())){
        RecordComTreeDto record = new RecordComTreeDto();
        record.setTreeId(tree.getId());
        record.setTreeName(tree.getLibraryName());
        record.setTreeAlias(tree.getLibraryAlias());
        record.setVersion(tree.getLibraryVersion());
        record.setIsLeaf(PlatformConstants.STR_ZERO);//非叶子节点
        record.setIsCom(PlatformConstants.STR_ZERO);//为目录
        record.setMemo(tree.getLibraryIntro());
        record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
        record.setChildList(comMap.get(tree.getId()));
        result.add(record);
      }
    }
    return result;
  }

  @Override
  public List<RecordComTreeDto> getCommonlyUseList(RecordComTreeQueryDto query) {
    List<RecordComTreeDto> result = new ArrayList<>();
    CpComponentList select = new CpComponentList();
    select.setIsCommonlyUse(PlatformConstants.INT_ONE);
    select.setComCategory(PlatformConstants.STR_ZERO);
    select.setComAttributes(PlatformConstants.STR_ZERO_OR + query.getRecordType());
    select.setComName(query.getSelectName());
    List<CpComponentList> list = cpComponentListService.queryRecordList(select);
    if (list.size() < PlatformConstants.INT_ONE) return result;
    List<String> ids = new ArrayList<>();
    list.forEach(one -> ids.add(one.getId()));
    List<CpComponentParamter> paramList = cpComponentParamterService.queryParamByComIds(ids);
    Map<String, List<RecordComParamDto>> map = new HashMap<>();
    for (CpComponentParamter param : paramList) {
      RecordComParamDto dto = new RecordComParamDto();
      BeanUtils.copyProperties(param, dto);
      if (map.containsKey(param.getComId())) {
        map.get(param.getComId()).add(dto);
      } else {
        List<RecordComParamDto> one = new ArrayList<>();
        one.add(dto);
        map.put(param.getComId(), one);
      }
    }
    Map<String, CpComponentLibrary> libMap = getLibName();
    for (CpComponentList com : list) {
      RecordComTreeDto record = new RecordComTreeDto();
      record.setTreeId(com.getId());
      record.setTreeName(com.getComName());
      record.setTreeAlias(com.getComAlias());
      record.setMemo(com.getComIntro());
      record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
      record.setParamList(map.get(com.getId()));
      record.setLibraryName(libMap.get(com.getLibraryId()).getLibraryName());
      record.setVersion(libMap.get(com.getLibraryId()).getLibraryVersion());
      result.add(record);
    }
    return result;
  }

  @Override
  public List<RecordComTreeDto> getComInfoByIdList(List<String> ids) {
    List<RecordComTreeDto> result = new ArrayList<>();
    List<Object> idsNew = new ArrayList<>(ids);
    List<CpComponentList> list = cpComponentListService.findByPrimaryKeys(idsNew);
    Map<String,CpComponentLibrary> libMap = getLibName();
    List<CpComponentParamter> paramList = cpComponentParamterService.queryParamByComIds(ids);
    Map<String,List<RecordComParamDto>> map = new HashMap<>();
    for (CpComponentParamter param : paramList) {
      RecordComParamDto dto = new RecordComParamDto();
      BeanUtils.copyProperties(param,dto);
      if(map.containsKey(param.getComId())){
        map.get(param.getComId()).add(dto);
      }else{
        List<RecordComParamDto> one = new ArrayList<>();
        one.add(dto);
        map.put(param.getComId(),one);
      }
    }
    for (CpComponentList com : list) {
      RecordComTreeDto record = new RecordComTreeDto();
      record.setTreeId(com.getId());
      record.setTreeName(com.getComName());
      record.setTreeAlias(com.getComAlias());
      record.setMemo(com.getComIntro());
      record.setComFlag(PlatformConstants.STR_ZERO);//基础组件
      record.setParamList(map.get(com.getId()));
      record.setLibraryName(libMap.get(com.getLibraryId()).getLibraryName());
      record.setLibraryStatus(libMap.get(com.getLibraryId()).getLibraryStatus());
      record.setVersion(libMap.get(com.getLibraryId()).getLibraryVersion());
      result.add(record);
    }
    return result;
  }

  @Override
  public CpComponentListDetailDto getComInfoByName(RecordComInfoByNameDto query) {
    CpComponentListDetailDto result = new CpComponentListDetailDto();
    CpComponentLibrary lib = new CpComponentLibrary();
    lib.setLibraryName(query.getLibraryName());
    List<CpComponentLibrary> libList = cpComponentLibraryService.query(lib);
    if(libList!=null && libList.size()>0){
      CpComponentList com = new CpComponentList();
      com.setComName(query.getComName());
      com.setLibraryId(libList.get(0).getId());
      List<CpComponentList> comList= cpComponentListService.query(com);
      if(comList!=null && comList.size()>0){
        BeanUtils.copyProperties(comList.get(0),result);
        List<String> ids = new ArrayList<>();
        ids.add(result.getId());
        List<CpComponentParamter> paramList = cpComponentParamterService.queryParamByComIds(ids);
        result.setParamList(paramList);
      }
    }
    return result;
  }

  @Override
  public List<Map<String,List<String>>> getComBasicInfoByIdList(List<String> ids) {
    List<Map<String,List<String>>> result = new ArrayList<>();
    List<CpComponentLibrary> libList = cpComponentLibraryService.queryLibListByNames(ids);
    for (CpComponentLibrary library : libList) {
      Map<String ,List<String>> one = new HashMap<>();
      CpComponentList oneQuery = new CpComponentList();
      oneQuery.setLibraryId(library.getId());
      List<CpComponentList> oneList = cpComponentListService.query(oneQuery);
      List<String> value = new ArrayList<>();
      oneList.forEach(str->value.add(str.getComName()));
      one.put(library.getLibraryName(),value);
      result.add(one);
    }
    return result;
  }


  /**
   * 获取组件库名
   * @return
   */
  private Map<String,CpComponentLibrary> getLibName(){
    List<CpComponentLibrary> list = cpComponentLibraryService.findAll();
    Map<String,CpComponentLibrary> result = new HashMap<>();
    list.forEach(one->result.put(one.getId(),one));
    return result;
  }
}
