/*
 * Copyright (c) 京北方信息技术股份有限公司 Corporation 2021 . All rights reserved.
 *
 */
package net.northking.cctp.saas.api.tenant.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.excel.AbstractExcelService;
import net.northking.cctp.common.db.excel.ExcelHeader;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.saas.cache.SaaSTenantCache;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.saas.db.entity.SaasTenant;
import net.northking.cctp.saas.db.entity.SaasTenantAdmin;
import net.northking.cctp.saas.db.service.SaasTenantAdminService;
import net.northking.cctp.saas.db.service.SaasTenantService;
import net.northking.cctp.saas.dto.tenant.SaaSTenantDetailDto;
import net.northking.cctp.saas.dto.tenant.SaaSTenantQueryDto;
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.Date;
import java.util.List;

/**
 * 租户服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private SaasTenantService saasTenantService;

  @Autowired
  private SaaSTenantCache tenantCache;

  @Autowired
  private SaasTenantAdminService saasTenantAdminService;

  @Autowired
  private EntityNameCache entityNameCache;

  @Override
  public BasicService<SaasTenant> getService()
  {
    return this.saasTenantService;
  }

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("主键", "id", String.class);
    ExcelHeader tenantCode = new ExcelHeader("租户代码", "tenantCode", String.class);
    ExcelHeader tenantName = new ExcelHeader("租户名称", "tenantName", String.class);
    ExcelHeader memo = new ExcelHeader("描述说明", "memo", String.class);
    ExcelHeader managerName = new ExcelHeader("负责人姓名", "managerName", String.class);
    ExcelHeader managerPhone = new ExcelHeader("负责人电话", "managerPhone", String.class);
    ExcelHeader managerEmail = new ExcelHeader("负责人邮箱", "managerEmail", String.class);
    ExcelHeader onlineUserNum = new ExcelHeader("在线用户数量", "onlineUserNum", String.class);
    ExcelHeader isolationLevel = new ExcelHeader("数据隔离级别", "isolationLevel", 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 deleted = new ExcelHeader("是否删除", "deleted", Boolean.class);

    return new ExcelHeader[]{};
  }

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

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

  //分页查询
  @Override
  @DatabaseReadOnly
  public Pagination<SaaSTenantDetailDto> pagingQuery(QueryByPage<SaaSTenantQueryDto> queryByPage)
  {
    if (queryByPage != null && queryByPage.getQuery() != null) {
      //选择未逻辑删除的租户
      queryByPage.getQuery().setDeleted(false);
    }
    //分页查出所有数据
    Pagination<SaaSTenantDetailDto> page =this.saasTenantService.pagingQuery(queryByPage);
    List<SaaSTenantDetailDto> records = page.getRecords();
    //遍历处理
    for (SaaSTenantDetailDto record : records) {
      SaasTenantAdmin adminQuery = new SaasTenantAdmin();
      adminQuery.setTenantId(record.getId());
      //转换成中文名称的创建人
      record.setCreatedBy((entityNameCache.translateById(EntityNameCatalog.MONSTER_USER, record.getCreatedBy())));
      //查询出该租户下所有管理员
      List<SaasTenantAdmin> resultAdminList = this.saasTenantAdminService.query(adminQuery);
      record.setAdminList(resultAdminList);
    }
    return page;
  }

  //查询租户
  @Override
  @DatabaseReadOnly
  public SaaSTenantDetailDto findByPK(String uuid)
  {
    SaasTenant example = new SaasTenant();
    //设置主键
    example.setId(uuid);
    //查询租户属性
    List<SaasTenant> list = this.saasTenantService.query(example);
    //判断是否为空
    if (list.isEmpty())
    {
      return null;
    }
    SaaSTenantDetailDto dto = new SaaSTenantDetailDto();
    BeanUtils.copyProperties(list.get(0), dto);
    //查询租户管理员
    SaasTenantAdmin admin = new SaasTenantAdmin();
    admin.setTenantId(dto.getId());
    List<SaasTenantAdmin> queryList=this.saasTenantAdminService.query(admin);
    dto.setAdminList(queryList);
    SaasTenantAdmin adminQuery = new SaasTenantAdmin();
    adminQuery.setTenantId(uuid);
    //查询出该租户下所有管理员
    List<SaasTenantAdmin> resultAdminList = this.saasTenantAdminService.query(adminQuery);
    //转换成中文名称的创建人
    if (resultAdminList.size()>0){
      SaasTenantAdmin saasTenantAdmin = resultAdminList.get(resultAdminList.size()-1);
      dto.setTenantCreated(saasTenantAdmin.getAdminLoginNo());
    }
    return dto;
  }

}
