/*
* 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.OverallViewIndex2Service;
import net.northking.cctp.testbug.db.entity.OverallViewIndex2;

import net.northking.cctp.testbug.dto.*;
import net.northking.cctp.testbug.feign.server.ProjectsFeignServer;
import net.northking.cctp.testbug.util.BeanHelper;
import org.apache.commons.lang.StringUtils;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

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

  @Autowired
  private OverallViewIndex2Service overallViewIndex2Service;
  @Autowired
  private EntityNameCache entityNameCache;
  @Autowired
  private ProjectsFeignServer projectsFeignServer;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader viewname = new ExcelHeader("图名称", "viewname", String.class);
    ExcelHeader userId = new ExcelHeader("用户id", "userId", String.class);
    // TODO 定义表头及顺序
    return new ExcelHeader[]{};
  }

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

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

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

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

  @Override
  @DatabaseWriteOnly
  public String add(OverallViewIndex2AddDto dto)
  {
    OverallViewIndex2 entity = new OverallViewIndex2();
    BeanUtils.copyProperties(dto, entity);
    //先排除重复的视图
    OverallViewIndex2 tmpEntity = new OverallViewIndex2();
    tmpEntity.setUserId(NKSecurityContext.getUserId());
    //后续改成必填
    if (null!=entity.getProId()) {
      tmpEntity.setProId(entity.getProId());
    }
    tmpEntity.setRecordType(entity.getRecordType());
    tmpEntity.setViewName(entity.getViewName());
    List<OverallViewIndex2> query = overallViewIndex2Service.query(tmpEntity);
    if(query.size()!=0&&null!=dto.getId()&&(!dto.getId().equals(query.get(0).getId()))){
      return "该用户已存在该类型的相同名称的视图，无法更新";
    }
    if(query.size()!=0&&null==dto.getId()){
      return "该用户已存在该类型的相同名称的视图，无法新增";
    }
    //更新
    if(null!=dto.getId()){
      try {
        return String.valueOf(updateByPK(BeanHelper.copyProperties(entity, OverallViewIndex2UpdateDto.class)));
      } catch (IllegalAccessException e) {
        logger.error("更新失败",e);
      }
    }
    //新增
    StringBuilder uuidList = new StringBuilder();
    String userId = NKSecurityContext.getUserId();
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = sdf.format(new Date());

    List<OverallViewIndex2> overallViewIndex2s=new ArrayList<>();
    String split[]= StringUtils.split(dto.getViewName(),',');
    String viewIds[]= StringUtils.split(dto.getViewId(),',');
    for (int i=0;i<split.length;i++){
        OverallViewIndex2 overallViewIndex2 = new OverallViewIndex2();
        overallViewIndex2.setViewName(split[i]);
        overallViewIndex2.setViewId(viewIds[i]);
        String uuid = UUIDUtil.create32UUID();
        uuidList.append(uuid+",");
        overallViewIndex2.setId(uuid);
        overallViewIndex2.setUserId(userId);
        overallViewIndex2.setCreateTime(date);
        overallViewIndex2.setProId(entity.getProId());
        overallViewIndex2.setRecordType(entity.getRecordType());
        overallViewIndex2s.add(overallViewIndex2);
    }
    this.overallViewIndex2Service.insertByBatch(overallViewIndex2s);
    return uuidList.toString();
  }

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

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

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

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

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

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

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

  @Override
  public List<OverallViewIndex2> oneQuery(String userId,OverallViewIndex2QueryDto queryDto) {
    OverallViewIndex2 o = new OverallViewIndex2();
    o.setUserId(userId);
    o.setProId(queryDto.getProId());
    o.setRecordType(queryDto.getRecordType());
    List<OverallViewIndex2> overallViewIndex2s = this.overallViewIndex2Service.queryByCreateTimeAsc(o);
    //根据项目id获取项目名，过滤已删除项目的相关数据
    for (OverallViewIndex2 overallViewIndex2:overallViewIndex2s) {
      List<String> proNameList=new ArrayList<>();
      String[] split = overallViewIndex2.getProId().split(",");
      Integer len=split.length;
      Integer count=0;
      for (String proId: split) {
        if(null==projectsFeignServer.listProject(Collections.singletonList(proId))||projectsFeignServer.listProject(Collections.singletonList(proId)).size()==0||
                null==projectsFeignServer.listProject(Collections.singletonList(proId)).get(0).getDeleted()||projectsFeignServer.listProject(Collections.singletonList(proId)).get(0).getDeleted()){
          count++;
          continue;
        }
        proNameList.add(entityNameCache.translateById(EntityNameCatalog.MONSTER_SYSTEM, proId));
      }
      if (!count.equals(len)) {
        overallViewIndex2.setProNameList(proNameList);
      }else {
        overallViewIndex2.setProNameList(null);
      }
    }
    return overallViewIndex2s.stream().filter((OverallViewIndex2 overallViewIndex2)->(null!=overallViewIndex2.getProNameList())).collect(Collectors.toList());
  }

}
