package com.testor.workflow.task.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.module.emergency.model.domain.TEmergencyRehearsal;
import com.testor.module.emergency.service.TEmergencyRehearsalService;
import com.testor.workflow.task.model.dto.CompleteTaskChild;
import com.testor.workflow.task.model.dto.TaskCompleteParamsChild;
import com.testor.workflow.task.service.ZTfwTaskService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.exceptions.ApiException;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import com.tongtech.tfw.workflow.apis.task.TaskEnumCode;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTask;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTaskListRequest;
import com.tongtech.tfw.workflow.apis.task.model.dto.HisTaskSqlParam;
import com.tongtech.tfw.workflow.apis.task.service.ActRuTaskService;
import com.tongtech.tfw.workflow.service.dto.TaskServiceResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * WfTaskController
 *
 * @author Created by ivan on 2020/8/20 .
 * @version 1.0
 */
@RestController
@Api(value = "Wf Task Controller", tags = "ZWF流程任务管理扩展接口")
@Slf4j
@RequestMapping("/zwf/task")
public class ZWfTaskController extends SuperController {

  @Autowired
  private ZTfwTaskService ztfwTaskService;

  @Resource
  private TaskService taskService;

  @Autowired
  private TEmergencyRehearsalService rehearsalService;


  @Autowired
  private ActRuTaskService actRuTaskService;

  @ApiOperation(value = "完成任务（可根据processInstanceId，不需要taskId）", notes = "完成任务")
  @PostMapping(value = "/complete")
  public BaseResponse<BizGeneralResponse> completeTask(
          @RequestBody @Valid CompleteTaskChild completeTask) {
    BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
    String userId = getUserId();

    if (StringHelper.isBlank(completeTask.getUserId())) {
      completeTask.setUserId(userId);
    }
    if (StringHelper.isBlank(completeTask.getOrgId())) {
      completeTask.setOrgId(userId);
    }
    if (StringHelper.isBlank(completeTask.getBizId())) {
      completeTask.setBizId(IdHelper.getId32bitTime());
    }
    try {
      TaskCompleteParamsChild taskCompleteParams =
              BeanHelper.beanToBean(completeTask, TaskCompleteParamsChild.class);
      TaskServiceResult taskServiceResult = ztfwTaskService.completeTask(taskCompleteParams);
      baseResponse.setData(
              BizGeneralResponse.builder().result(taskServiceResult.getCode()).build());
    } catch (Exception e) {
      log.error("完成任务 ERROR: " + e);
      throw new ApiException(TaskEnumCode.COMPLETE_FAILED.transform());
    }
    return baseResponse;
  }

  @ApiOperation(value = "根据任务id获取当前任务的信息", notes = "根据任务id获取当前任务的信息")
  @GetMapping(value = "/findRunTaskById")
  public BaseResponse<Task> findRunTaskById(String taskId) {

    BaseResponse<Task> baseResponse = new BaseResponse<>();
    if (StringUtils.isNotEmpty(taskId)) {
      // TODO 按需求添加业务异常判断
      Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
      baseResponse.setData(task);
    }
    return baseResponse;
  }

  @ApiOperation(value = "已办任务", notes = "已办任务")
  @GetMapping({"/history/list"})
  public BaseResponse<BaseResponseList<HisTask>> hisTaskList(HisTaskListRequest hisTaskListRequest) {
    BaseResponse<BaseResponseList<HisTask>> baseResponse = new BaseResponse();
    BaseResponseList<HisTask> resultResList = new BaseResponseList();
    Long page = StringHelper.isEmpty(hisTaskListRequest.getPage()) ? BizConstants.PAGE : Long.valueOf(hisTaskListRequest.getPage());
    Long limit = StringHelper.isEmpty(hisTaskListRequest.getLimit()) ? BizConstants.LIMIT : Long.valueOf(hisTaskListRequest.getLimit());
    Page<HisTask> resultPage = new Page(page, limit);
    HisTaskSqlParam hisTaskSqlParam = new HisTaskSqlParam();
    if (StringHelper.isNotBlank(hisTaskListRequest.getUsername())) {
      hisTaskSqlParam.setUserId(hisTaskListRequest.getUsername());
    } else {
      hisTaskSqlParam.setUserId(this.getUserId());
    }

    if (StringHelper.isNotBlank(hisTaskListRequest.getStartUser())) {
      hisTaskSqlParam.setUserName(hisTaskListRequest.getStartUser());
    }

    if (StringHelper.isNotBlank(hisTaskListRequest.getBizId())) {
      hisTaskSqlParam.setBizId(hisTaskListRequest.getBizId());
    }
    if (StringHelper.isNotBlank(hisTaskListRequest.getProcessInstanceId())) {
      hisTaskSqlParam.setProcessInstanceId(hisTaskListRequest.getProcessInstanceId());
    }
    if (StringHelper.isNotBlank(hisTaskListRequest.getTaskId())) {
      hisTaskSqlParam.setTaskId(hisTaskListRequest.getTaskId());
    }

    if (StringHelper.isNotBlank(hisTaskListRequest.getProcessDefinitionName())) {
      hisTaskSqlParam.setProDefName(hisTaskListRequest.getProcessDefinitionName());
    }

    IPage<HisTask> queryList = this.actRuTaskService.selectHisTaskList(resultPage, hisTaskSqlParam);
    List<HisTask> records = queryList.getRecords();
    records.forEach(r->{
      if ("应急演练".equals(r.getProcessDefinitionName())) {
        int count = rehearsalService.count(new QueryWrapper<TEmergencyRehearsal>()
                .eq("id", r.getBizId())
                .eq("process_id", r.getProcessInstanceId())
                .eq("status", "0")
                .eq("rehearsal_status", "4")
        );
        if (count>0) {
          r.setTaskName("已完成");
        }
      }

    });
    resultResList.setData(queryList.getRecords());
    resultResList.setTotal(queryList.getTotal());
    baseResponse.setData(resultResList);
    return baseResponse;
  }
}
