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

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.common.db.Pagination;
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.flowable.api.sm.service.StateProcessDefApiService;
import net.northking.cctp.flowable.common.exception.FlowAppError;
import net.northking.cctp.flowable.db.entity.SpDefProcess;
import net.northking.cctp.flowable.db.jpa.SpDefProcessRepository;
import net.northking.cctp.flowable.dto.sm.StateProcessDefDto;
import net.northking.cctp.flowable.sm.StateProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 状态流程定义
 *
 * @author : xiusong.xie
 * @version : 1.0
 */
@Api(tags = "状态流程定义")
@RequestMapping("/v1")
@RestController
public class StateProcessDefCtrl {
  /**
   * 资源名称
   */
  private static final String RESOURCE_NAME = "/def/sp";
  /**
   * 日志
   */
  private final static Logger logger = LoggerFactory.getLogger(StateProcessDefCtrl.class);

  @Autowired
  private StateProcessDefApiService apiService;

  /**
   * 流程仓库
   */
  @Autowired
  private SpDefProcessRepository processRepository;


  /**
   * Restful接口-post： 保存状态流程定义
   *
   * @param dto 接口数据传输对象
   * @return 主键
   */
  @ApiOperation(value = "保存：状态流程定义")
  @PostMapping(
          value = RESOURCE_NAME,
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<String> save(
          @RequestBody @Validated StateProcessDefinition dto) {
    // 参数校验
    try {
      if (dto.getUsedEnumState() != null && dto.getUsedEnumState()) {
        if (StringUtils.isBlank(dto.getCatalogCode())) {
          throw new PlatformRuntimeException(FlowAppError.CATA_CODE_IS_EMPTY);
        }
      }
      if (dto.getAllowedAnyToAny()) {
        if (dto.getAnyAuthorities() == null || dto.getAnyAuthorities().isEmpty()) {
          throw new PlatformRuntimeException(FlowAppError.ANY_TO_ANY_ROLE_IS_EMPTY);
        }
      }
      if (dto.getEvents() == null || dto.getEvents().isEmpty()) {
        throw new PlatformRuntimeException(FlowAppError.EVENTS_IS_EMPTY);
      }
      // 具体校验
      dto.flowCheck();
    } catch (PlatformRuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new PlatformRuntimeException(FlowAppError.SAVE_FAILED, e);
    }
    ResultWrapper<String> wrapper = new ResultWrapper<>();
    String uuid = apiService.save(dto);
    return wrapper.success(uuid);
  }

  /**
   * Restful接口-get： 获取状态流程定义
   *
   * @param uuid 主键
   * @return 接口数据传输对象
   */
  @ApiOperation(value = "获取：状态流程定义")
  @GetMapping(
          value = RESOURCE_NAME + "/{uuid}",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<StateProcessDefinition> findByPK(
          @PathVariable("uuid") String uuid) {
    ResultWrapper<StateProcessDefinition> wrapper = new ResultWrapper<>();
    StateProcessDefinition dto = apiService.findByPK(uuid);
    return wrapper.success(dto);
  }

  /**
   * Restful接口-delete： 删除状态流程定义
   *
   * @param uuid 主键
   * @return 删除的记录数量
   */
  @ApiOperation(value = "删除：状态流程定义")
  @DeleteMapping(
          value = RESOURCE_NAME + "/{uuid}",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Integer> deleteByPK(
          @PathVariable("uuid") String uuid) {
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    Integer count = apiService.deleteByPK(uuid);
    return wrapper.success(count);
  }

  /**
   * Restful接口-post： 批量删除状态流程定义
   *
   * @param batch 集合
   * @return 成功的数量
   */
  @ApiOperation(value = "批量删除：状态流程定义")
  @PostMapping(
          value = "/batch" + RESOURCE_NAME + "/delete",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Integer> deleteBatch(
          @RequestBody @Validated List<String> batch) {
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    Integer count = apiService.deleteBatch(batch);
    return wrapper.success(count);
  }

  /**
   * 分页查询
   *
   * @param queryByPage 查询条件
   * @return 数据列表
   */
  @ApiOperation(value = "分页查询列表：状态流程定义")
  @PostMapping(value = "/paging/query" + RESOURCE_NAME,
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
          consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Pagination<StateProcessDefDto>> pagingQuery(
          @RequestBody @Validated QueryByPage<SpDefProcess> queryByPage) {
    ResultWrapper<Pagination<StateProcessDefDto>> wrapper = new ResultWrapper<>();
    Pagination<StateProcessDefDto> page = apiService.pagingQuery(queryByPage);
    return wrapper.success(page);
  }


  /**
   * 更改流程是否默认
   */
  @ApiOperation(value = "更改流程是否默认")
  @GetMapping(value = RESOURCE_NAME + "default/{uuid}",
          produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public ResultWrapper<Integer> updateDefault(@PathVariable("uuid") String uuid) {
    Integer result = apiService.updateDefault(uuid);
    ResultWrapper<Integer> wrapper = new ResultWrapper<>();
    return wrapper.success(result);
  }

}
