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

import com.alibaba.fastjson.JSON;
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.constant.DWBaseConstant;
import net.northking.cctp.dw.db.service.BugStatusStatisticsService;
import net.northking.cctp.dw.db.entity.BugStatusStatistics;

import net.northking.cctp.dw.dto.*;
import net.northking.cctp.dw.feign.ProjectsFeignClient;
import net.northking.cctp.dw.feign.StatusRoleDto;
import net.northking.cctp.platform.db.entity.CltDictItem;
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.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 缺陷状态统计服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private BugStatusStatisticsService bugStatusStatisticsService;
  @Autowired
  private EntityNameCache entityNameCache;
  @Autowired
  private ProjectsFeignClient projectsFeignClient;
  @Autowired
  private RedisTemplate redisTemplate;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader receiverName = new ExcelHeader("分配人", "receiverName", String.class);
    ExcelHeader moduleId = new ExcelHeader("模块", "moduleId", String.class);
    ExcelHeader type = new ExcelHeader("类型", "type", String.class);
    ExcelHeader projectId = new ExcelHeader("系统id", "projectId", String.class);
    ExcelHeader bugStatus = new ExcelHeader("缺陷状态", "bugStatus", String.class);
    ExcelHeader bugStatusCode = new ExcelHeader("缺陷状态码", "bugStatusCode", String.class);
    ExcelHeader amount = new ExcelHeader("数量", "amount", Integer.class);
    ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", String.class);
    ExcelHeader tenantId = new ExcelHeader("租户id", "tenantId", String.class);
    // TODO 定义表头及顺序
    return new ExcelHeader[]{};
  }

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

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

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

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

  @Override
  @DatabaseWriteOnly
  public String add(BugStatusStatisticsAddDto dto)
  {
    String uuid = UUIDUtil.create32UUID();
    BugStatusStatistics entity = new BugStatusStatistics();
    BeanUtils.copyProperties(dto, entity);
    entity.setId(uuid);
    this.bugStatusStatisticsService.insert(entity);
    return uuid;
  }

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

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

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

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

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

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

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

  @Override
  public List<BugStatusStatisticsDetailDto> listQuery(ChartDataGeneQueryDto chartDataGeneQueryDto) {
    List<BugStatusStatisticsDetailDto> page = this.bugStatusStatisticsService.listQuery(chartDataGeneQueryDto);
    //获取中文名
    if(!page.isEmpty()) {
      page.forEach(bugStatisticsChartAddDto -> {
        if (null != bugStatisticsChartAddDto.getReceiverName()) {
          bugStatisticsChartAddDto.setReceiverName(entityNameCache.translateById(EntityNameCatalog.WITH_LOGIN_NO, bugStatisticsChartAddDto.getReceiverName()) == null ? null : entityNameCache.
                  translateById(EntityNameCatalog.WITH_LOGIN_NO, bugStatisticsChartAddDto.getReceiverName()));
        }
      });
    }
    return page;
  }

  @Override
  public List<BugStatusStatistics> queryUnresolvedBugModuleData(String projectId,String tenantId) {
    //获取终态
    StatusRoleDto s=new StatusRoleDto();
    s.setProjectId(projectId);
    s.setFinishedState(true);
    s.setTenantId(tenantId);
    List<String> endStatuss=projectsFeignClient.querySpecialState(s);
    if(endStatuss==null || endStatuss.size()<1)return new ArrayList<>();
    return bugStatusStatisticsService.queryUnresolvedBugModuleData(projectId,endStatuss);
  }

  @Override
  public List<BugStatusStatistics> queryTop5TypeBugDataByTenantId(String tenantId,List<String> projectIds) {
    //缺陷分类:  1.需求缺陷、2.设计缺陷、3.编码缺陷、4.UI缺陷、5.兼容性缺陷、6.环境缺陷、7.用户体验、8移植缺陷;
    List<BugStatusStatistics> bugStatusStatistics = bugStatusStatisticsService.queryTop5TypeBugDataByTenantId(tenantId,projectIds);
    if (null==bugStatusStatistics||bugStatusStatistics.size()==0)return new ArrayList();
    List<CltDictItem> cltDictItems = JSON.parseArray(JSON.toJSONString(
            redisTemplate.opsForValue().get(DWBaseConstant.DICT_REDIS_KEY + tenantId + DWBaseConstant.DICT_BUG_TYPE)), CltDictItem.class);
    Map<String, List<CltDictItem>> collect = cltDictItems.stream().collect(Collectors.groupingBy(CltDictItem::getItemCode));
    for (BugStatusStatistics dto:bugStatusStatistics){
      if (!StringUtils.isEmpty(dto.getBugStatus())) {
            dto.setBugStatus(null==collect.get(dto.getBugStatus())?DWBaseConstant.UN_KNOW_BUG:collect.get(dto.getBugStatus()).get(0).getItemName());
      }else {
            dto.setBugStatus(DWBaseConstant.UN_KNOW_BUG);
      }
    }
    return bugStatusStatistics;
  }

}
