/*
* 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.DwAtuScriptInfoService;
import net.northking.cctp.dw.db.entity.DwAtuScriptInfo;

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.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 脚本信息同步表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private DwAtuScriptInfoService dwAtuScriptInfoService;

  @Autowired
  private EntityNameCache entityNameCache;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader scriptType = new ExcelHeader("", "scriptType", Integer.class);
    ExcelHeader scriptName = new ExcelHeader("", "scriptName", String.class);
    ExcelHeader tenantId = new ExcelHeader("", "tenantId", String.class);
    ExcelHeader projectId = new ExcelHeader("", "projectId", String.class);
    ExcelHeader isDeleted = new ExcelHeader("", "isDeleted", Integer.class);
    // TODO 定义表头及顺序
    return new ExcelHeader[]{};
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

}
