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

import net.northking.cctp.common.db.BasicService;
import net.northking.cctp.common.db.DefaultPagination;
import net.northking.cctp.common.db.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.project.bus.feign.PlatformForHzBankFeign;
import net.northking.cctp.project.config.TaskSyncConfig;
import net.northking.cctp.project.constants.ProjectAppError;
import net.northking.cctp.project.db.entity.CpProjectSoftware;
import net.northking.cctp.project.db.service.CpProjectSoftwareService;
import net.northking.cctp.project.dto.software.Software;
import net.northking.cctp.project.enums.OperateType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统软件关联表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private CpProjectSoftwareService cpProjectSoftwareService;
  @Autowired
  private PlatformForHzBankFeign platformFeign;
  @Autowired
  private TaskSyncConfig taskSyncConfig;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("主键", "id", String.class);
    ExcelHeader projectId = new ExcelHeader("系统主键", "projectId", String.class);
    ExcelHeader softwareId = new ExcelHeader("系统选中的软件", "softwareId", String.class);
    ExcelHeader createdBy = new ExcelHeader("创建人", "createdBy", String.class);
    ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", Date.class);
    ExcelHeader updatedBy = new ExcelHeader("修改人", "updatedBy", String.class);
    ExcelHeader updatedTime = new ExcelHeader("修改时间", "updatedTime", Date.class);
    ExcelHeader tenantId = new ExcelHeader("租户id", "tenantId", String.class);
    return new ExcelHeader[]{};
  }

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

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


  @Override
  public void addProjectSoftware(String projectId,String operateType) {
    if (StringUtils.equals(operateType, OperateType.ADD.name())){
      QueryByPage<Map<String, Object>> queryPage = new QueryByPage<>();
      queryPage.setPageNo(1);
      queryPage.setPageSize(30);
      HashMap<String, Object> paramMap = new HashMap<>();
      paramMap.put("status", "p");
      queryPage.setQuery(paramMap);
      ResultWrapper<DefaultPagination<Software>> platformWrapper = platformFeign.querySoftwareForHzBank(queryPage);
      if (platformWrapper.isSuccess()
              && platformWrapper.getData() != null
              && platformWrapper.getData().getRecords() != null
              && platformWrapper.getData().getRecords().size() > 0) {
        List<Software> softwareList = platformWrapper.getData().getRecords().stream().filter(software -> StringUtils.equals("UAT", software.getSoftwareCode())).collect(Collectors.toList());
        CpProjectSoftware cpProjectSoftware = new CpProjectSoftware();
        cpProjectSoftware.setId(UUIDUtil.create32UUID());
        cpProjectSoftware.setProjectId(projectId);
        if (!CollectionUtils.isEmpty(softwareList)) {
          cpProjectSoftware.setSoftwareId(softwareList.get(0).getSoftwareId());
        }
        cpProjectSoftware.setTenantId(taskSyncConfig.getTenantId());
        this.cpProjectSoftwareService.saveProjectSoftware(cpProjectSoftware);

      } else {
        throw new PlatformRuntimeException(ProjectAppError.PROJECT_SOFTWARE_FAIL);
      }
    }
    if (StringUtils.equals(operateType,OperateType.DELETE.name())) {
      this.cpProjectSoftwareService.deleteByProjectId(projectId);
    }

  }

}
