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

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.exception.PlatformRuntimeException;
import net.northking.cctp.common.http.QueryByPage;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.scriptcase.constants.ScriptConstant;
import net.northking.cctp.scriptcase.db.entity.AtuGlobalVariable;
import net.northking.cctp.scriptcase.db.service.AtuGlobalVariableService;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuGlobalVariableAddDto;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuGlobalVariableDetailDto;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuGlobalVariableQueryDto;
import net.northking.cctp.scriptcase.dto.atuscriptrecord.AtuGlobalVariableUpdateDto;
import net.northking.cctp.scriptcase.enums.ScriptCaseAppError;
import net.northking.cctp.scriptcase.pub.variable.dto.VariableDto;
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.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 全局变量表服务实现类
 *
 * @author maven-cctp-plugin
 * @since 1.0
 */

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

  @Autowired
  private AtuGlobalVariableService atuGlobalVariableService;

  @Autowired
  private RedisTemplate redisTemplate;

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

  @Override
  public ExcelHeader[] excelHeaders()
  {
    ExcelHeader id = new ExcelHeader("", "id", String.class);
    ExcelHeader name = new ExcelHeader("变量名称", "name", String.class);
    ExcelHeader dataType = new ExcelHeader("数据类型", "dataType", String.class);
    ExcelHeader defaultValue = new ExcelHeader("默认值", "defaultValue", String.class);
    ExcelHeader memo = new ExcelHeader("描述", "memo", String.class);
    ExcelHeader delete = new ExcelHeader("是否被删除：0-未删除、1-已删除", "delete", Boolean.class);
    ExcelHeader variableType = new ExcelHeader("变量类型：0-全局变量、1-脚本变量", "variableType", Boolean.class);
    ExcelHeader scriptId = new ExcelHeader("脚本变量时必填、全局变量时为空", "scriptId", String.class);
    ExcelHeader tenantId = new ExcelHeader("租户id", "tenantId", String.class);
    ExcelHeader projectId = new ExcelHeader("系统id", "projectId", String.class);
    ExcelHeader updatedBy = new ExcelHeader("更新人", "updatedBy", String.class);
    ExcelHeader updatedTime = new ExcelHeader("更新时间", "updatedTime", Date.class);
    ExcelHeader createdBy = new ExcelHeader("创建人", "createdBy", String.class);
    ExcelHeader createdTime = new ExcelHeader("创建时间", "createdTime", Date.class);
    return new ExcelHeader[]{};
  }

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

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

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

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

  @Override
  @DatabaseWriteOnly
  public ResultWrapper<String> add(AtuGlobalVariableAddDto dto)
  {
    ResultWrapper<String> wrapper=new ResultWrapper<>();
    //名称合法性校验：名称组成： 字母、数字、下划线且不能以数字开头
    String regexName= ScriptConstant.REGEX_NAME;
    Pattern p = Pattern.compile(regexName);
    Matcher m = p.matcher(dto.getName());
    if(!m.matches()){
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_REGEX_ERR);
    }
    //名称唯一性校验 系统内变量名唯一
    AtuGlobalVariable tmp = new AtuGlobalVariable();
    tmp.setProjectId(dto.getProjectId());
    tmp.setName(dto.getName());
    tmp.setDelete(false);
    List<AtuGlobalVariable> atuGlobalVariables = atuGlobalVariableService.query(tmp);
    if (atuGlobalVariables.size()!=0){
      throw new PlatformRuntimeException(ScriptCaseAppError.DATA_HAS_SAME);
    }
    //插入
    String uuid = UUIDUtil.create32UUID();
    AtuGlobalVariable entity = new AtuGlobalVariable();
    BeanUtils.copyProperties(dto, entity);
    entity.setId(uuid);
    Date date = new Date();
    String userId = NKSecurityContext.getUserId();
    entity.setCreatedBy(userId);
    entity.setCreatedTime(date);
    entity.setTenantId(NKSecurityContext.getTenantId());
    entity.setUpdatedBy(userId);
    entity.setUpdatedTime(date);
    entity.setVariableType(false);//全局变量
    entity.setDataType(dto.getType());
    entity.setMemo(dto.getDesc());
    this.atuGlobalVariableService.insert(entity);
    return wrapper.success(uuid);
  }

  @Override
  @DatabaseWriteOnly
  public Integer updateByPK(AtuGlobalVariableUpdateDto dto) throws IllegalAccessException
  {
    AtuGlobalVariable entity = new AtuGlobalVariable();
    BeanUtils.copyProperties(dto, entity);
    entity.setUpdatedBy(NKSecurityContext.getUserId());
    entity.setUpdatedTime(new Date());
    entity.setMemo(dto.getDesc());
    return this.atuGlobalVariableService.updateByPrimaryKey(entity);
  }

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

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

  @Override
  @DatabaseWriteOnly
  public Integer deleteByPK(String uuid)
  {
    AtuGlobalVariable entity = new AtuGlobalVariable();
    entity.setId(uuid);
    entity.setUpdatedBy(NKSecurityContext.getUserId());
    entity.setUpdatedTime(new Date());
    entity.setDelete(true);
    return this.atuGlobalVariableService.updateByPrimaryKey(entity);
  }

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

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

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


  @Override
  public AtuGlobalVariable queryVariable(AtuGlobalVariable var) {
    AtuGlobalVariable result =  atuGlobalVariableService.queryVariable(var);
    return result;
  }

  /**
   * 更新全局变量值
   *
   * @param update
   * @return
   */
  @Override
  public int updateGlobal(VariableDto update) {
    int count = 0;
    try {
      count = atuGlobalVariableService.updateGlobalValue(update);
    } catch (Exception e) {
      logger.error("更新全局参数值失败", e);
    }
    return count;
  }

}
