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

import net.northking.cctp.common.cache.EntityNameCache;
import net.northking.cctp.common.cache.EntityNameCatalog;
import net.northking.cctp.common.db.BasicService;
import net.northking.cctp.common.db.Pagination;
import net.northking.cctp.common.db.annotation.DatabaseReadOnly;
import net.northking.cctp.common.db.annotation.DatabaseWriteOnly;
import net.northking.cctp.common.db.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.dw.db.service.DwAtuCaseDesignService;
import net.northking.cctp.dw.db.entity.DwAtuCaseDesign;

import net.northking.cctp.dw.dto.atu.*;
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.*;
import java.util.stream.Collectors;

/**
 * 自动化用例设计同步表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

@Service
@ConditionalOnMissingBean(name = "DwAtuCaseDesignApiServiceImpl")
public class DwAtuCaseDesignApiServiceImpl extends AbstractExcelService<DwAtuCaseDesign> implements DwAtuCaseDesignApiService
{
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(DwAtuCaseDesignApiServiceImpl.class);

  @Autowired
  private DwAtuCaseDesignService dwAtuCaseDesignService;

  @Autowired
  private EntityNameCache entityNameCache;

  //= Excel 导入导出相关代码 start ==================//
  @Override
  public BasicService<DwAtuCaseDesign> getService()
  {
    return this.dwAtuCaseDesignService;
  }

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader tenantId = new ExcelHeader("", "tenantId", String.class);
    ExcelHeader projectId = new ExcelHeader("", "projectId", String.class);
    ExcelHeader createdTime = new ExcelHeader("", "createdTime", Date.class);
    ExcelHeader createdBy = new ExcelHeader("", "createdBy", String.class);
    ExcelHeader caseName = new ExcelHeader("", "caseName", String.class);
    ExcelHeader caseNo = new ExcelHeader("", "caseNo", String.class);
    ExcelHeader caseType = new ExcelHeader("", "caseType", Integer.class);
    ExcelHeader isDelete = new ExcelHeader("", "isDelete", Integer.class);
    // TODO 定义表头及顺序
    return new ExcelHeader[]{};
  }

  /**
   * Excel导入，入库之前的处理
   * @param records 从Excel读取到的记录
   * @return 待入库的记录
   */
  @Override
  protected List<DwAtuCaseDesign> beforeInsertBatch(List<DwAtuCaseDesign> records)
  {
    for (DwAtuCaseDesign record : records)
    {
      record.setId(UUIDUtil.create32UUID());
    }
    return records;
  }

  /**
   * 写入Excel之前的处理<br>
   * 数据的特殊处理在此处加工处理
   *
   * @param record 来自数据库记录
   * @return 待写入Excel的记录
   */
  @Override
  protected DwAtuCaseDesign beforeWriteExcel(DwAtuCaseDesign record)
  {
    return record;
  }

  //= Excel 导入导出相关代码 end =======================//

  //= 增删改查 相关代码 start ==================//
  @Override
  @DatabaseReadOnly
  public Pagination<DwAtuCaseDesignDetailDto> pagingQuery(QueryByPage<DwAtuCaseDesignQueryDto> queryByPage)
  {
    return this.dwAtuCaseDesignService.pagingQuery(queryByPage);
  }

  @Override
  @DatabaseWriteOnly
  public String add(DwAtuCaseDesign dto)
  {
    String uuid = dto.getId();
    this.dwAtuCaseDesignService.insert(dto);
    return uuid;
  }

  @Override
  @DatabaseWriteOnly
  public Integer updateByPK(DwAtuCaseDesignUpdateDto dto) throws IllegalAccessException
  {
    DwAtuCaseDesign entity = new DwAtuCaseDesign();
    BeanUtils.copyProperties(dto, entity);
    return this.dwAtuCaseDesignService.updateByPrimaryKey(entity);
  }

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

    DwAtuCaseDesignDetailDto dto = new DwAtuCaseDesignDetailDto();
    BeanUtils.copyProperties(entitys.get(0), dto);
    return dto;
  }

  @Override
  @DatabaseWriteOnly
  public Integer deleteByPK(String uuid)
  {
    DwAtuCaseDesign entity = new DwAtuCaseDesign();
    entity.setId(uuid);
    return this.dwAtuCaseDesignService.deleteByExample(entity);
  }

  @Override
  public List<String> addBatch(List<DwAtuCaseDesign> batch)
  {
    List<String> result = new ArrayList<>();
    for (DwAtuCaseDesign dto : batch)
    {
      result.add(this.add(dto));
    }
    return result;
  }

  @Override
  public Integer updateBatch(List<DwAtuCaseDesignUpdateDto> batch) throws IllegalAccessException
  {
    int sum = 0;
    for (DwAtuCaseDesignUpdateDto dto : batch)
    {
      sum = sum + this.updateByPK(dto);
    }
    return sum;
  }

  @Override
  public Integer deleteBatch(List<Object> batch)
  {
    return this.dwAtuCaseDesignService.deleteByPrimaryKeys(batch);
  }

  @Override
  public DwAtuDetailTmpDto count(DwAtuCaseDesignQueryDto query) {
    DwAtuDetailTmpDto dwAtuDetailTmpDto=new DwAtuDetailTmpDto();
    List<DwAtuCaseDesignDetailDto> dwAtuCaseDesignDetailDtos = this.dwAtuCaseDesignService.countByGroup(query);
    //翻译成中文名
    for (DwAtuCaseDesignDetailDto dwAtuCaseDesignDetailDto:dwAtuCaseDesignDetailDtos) {
      if (null != entityNameCache.translateById(EntityNameCatalog.WITH_LOGIN_NO, dwAtuCaseDesignDetailDto.getCreatedBy())) {
        dwAtuCaseDesignDetailDto.setCreatedBy(entityNameCache.translateById(EntityNameCatalog.WITH_LOGIN_NO, dwAtuCaseDesignDetailDto.getCreatedBy()));
      }
    }
    //获取类型
    if (dwAtuCaseDesignDetailDtos.size()!=0){
      List<Integer> collect = dwAtuCaseDesignDetailDtos.stream().map(DwAtuCaseDesignDetailDto::getType).distinct().sorted().collect(Collectors.toList());
      //封装对象
      List<String> createdBys = dwAtuCaseDesignDetailDtos.stream().map(DwAtuCaseDesignDetailDto::getCreatedBy).distinct().collect(Collectors.toList());
      Map<String, List<DwAtuCaseDesignDetailDto>> collect1 = dwAtuCaseDesignDetailDtos.stream().collect(Collectors.groupingBy(DwAtuCaseDesignDetailDto::getCreatedBy));
      for (String createdBy:createdBys){
        List<DwAtuCaseDesignDetailDto> dwAtuCaseDesignDetailDtos1 = collect1.get(createdBy);
        List<Integer> collect2 = dwAtuCaseDesignDetailDtos1.stream().map(DwAtuCaseDesignDetailDto::getType).collect(Collectors.toList());
        List<Integer> integers = collect.stream().filter(c -> !collect2.contains(c)).collect(Collectors.toList());
        if (integers.size()!=0){
          DwAtuCaseDesignDetailDto dwAtuCaseDesignDetailDto=null;
          for (Integer type:integers){
            dwAtuCaseDesignDetailDto=new DwAtuCaseDesignDetailDto();
            dwAtuCaseDesignDetailDto.setCreatedBy(createdBy);
            dwAtuCaseDesignDetailDto.setType(type);
            dwAtuCaseDesignDetailDto.setMount(0);
            dwAtuCaseDesignDetailDtos.add(dwAtuCaseDesignDetailDto);
          }
        }
      }
      dwAtuDetailTmpDto.setDwAtuCaseDesignDetailDtos(dwAtuCaseDesignDetailDtos.stream().sorted(Comparator.comparing(DwAtuCaseDesignDetailDto::getType)).collect(Collectors.toList()));
      dwAtuDetailTmpDto.setType(collect);
    }
    return dwAtuDetailTmpDto;
  }

}
