/*
* Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
*
*/
package net.northking.cctp.testbug.api.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.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;

import net.northking.cctp.testbug.db.service.OverallViewIndexService;
import net.northking.cctp.testbug.db.entity.OverallViewIndex;

import net.northking.cctp.testbug.dto.OverallViewIndexAddDto;
import net.northking.cctp.testbug.dto.OverallViewIndexDetailDto;
import net.northking.cctp.testbug.dto.OverallViewIndexQueryDto;
import net.northking.cctp.testbug.dto.OverallViewIndexUpdateDto;
import net.northking.cctp.testbug.feign.server.ProjectsFeignServer;
import net.northking.cctp.testbug.util.BeanHelper;
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.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 跨项目级视图索引信息表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private OverallViewIndexService overallViewIndexService;
  @Autowired
  private ProjectsFeignServer projectsFeignServer;
  @Autowired
  private EntityNameCache entityNameCache;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader proIdList = new ExcelHeader("项目id集合", "proIdList", String.class);
    ExcelHeader userId = new ExcelHeader("用户id", "userId", String.class);
    // TODO 定义表头及顺序
    return new ExcelHeader[]{};
  }

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

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

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

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

  @Override
  @DatabaseWriteOnly
  public String add(OverallViewIndexAddDto dto)
  {
    //新增之前先查询
    OverallViewIndex entity = new OverallViewIndex();
    entity.setUserId(NKSecurityContext.getUserId());
    entity.setRecordType(dto.getRecordType());
    String uuid=null;
    List<OverallViewIndex> query = this.overallViewIndexService.query(entity);
    if (null==query||query.size()==0){//新增
      uuid = UUIDUtil.create32UUID();
      entity.setProIdList(dto.getProIdList());
      entity.setId(uuid);
      entity.setRecordType(dto.getRecordType());
      this.overallViewIndexService.insert(entity);
    }else{//更新
      OverallViewIndexUpdateDto updateDto=new OverallViewIndexUpdateDto();
      updateDto.setId(query.get(0).getId());
      updateDto.setProIdList(dto.getProIdList());
      try{
        updateByPK(updateDto);
      }
      catch (Exception e){
        e.getMessage();
      }
    }

    return uuid;
  }

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

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

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

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

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

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

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

  @Override
  public OverallViewIndexDetailDto oneQuery(String userId,String recordType) {
    OverallViewIndex o=new OverallViewIndex();
    o.setUserId(userId);
    o.setRecordType(recordType);
    OverallViewIndexDetailDto overallViewIndexDetailDto=null;
    List<OverallViewIndex> query = this.overallViewIndexService.query(o);
    //做非空校验
    List<String> allProIdList=new ArrayList<>();
    if(query.size()!=0){
      Arrays.asList(query.get(0).getProIdList().split(",")).forEach(
              pid->{
                if(null!=projectsFeignServer.listProject(Collections.singletonList(pid))&&projectsFeignServer.listProject(Collections.singletonList(pid)).size()!=0){
                  if(null!=projectsFeignServer.listProject(Collections.singletonList(pid)).get(0).getDeleted()) {
                    allProIdList.add(pid);
                  }
                }
              }
      );
    }
    if(allProIdList.size()!=0){
      overallViewIndexDetailDto=BeanHelper.copyProperties(query.get(0),OverallViewIndexDetailDto.class);

      StringBuilder sb=new StringBuilder();
      StringBuilder sbProIdList=new StringBuilder();
      List<String> noExistProList=new ArrayList<>();

      allProIdList.forEach(proId->{
        //通过项目id查项目名
        if(projectsFeignServer.listProject(Collections.singletonList(proId)).get(0).getDeleted()){
          noExistProList.add(proId);
        }
        else{
          sb.append(entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM, proId));
          sb.append(",");
        }
      });
      //筛选
      for (int i = 0; i <allProIdList.size() ; i++) {
        Boolean isEqual = false;
        for (int j = 0; j < noExistProList.size(); j++) {
          if (allProIdList.get(i).equals(noExistProList.get(j))) {
            isEqual = true;
            break;
          }
        }
        if (!isEqual) {
          sbProIdList.append(allProIdList.get(i));
          sbProIdList.append(",");
        }
      }
      //新增
      String s = new String(sb);
      String sProIdList = new String(sbProIdList);
      if(s.length()!=0){
        overallViewIndexDetailDto.setProNameList(s.substring(0,s.length()-1));
        overallViewIndexDetailDto.setProIdList(sProIdList.substring(0,sProIdList.length()-1));
      }
    }
    return overallViewIndexDetailDto;
  }

}
