package com.testor.module.wf;

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.module.hazard.model.dto.THazardWorkPlanDTO;
import com.testor.module.wf.service.RuTaskService;
import com.testor.module.wf.vo.ProcessDefListRequestVO;
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.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.workflow.apis.definition.model.dto.ProcessDefListRequest;
import com.tongtech.tfw.workflow.apis.definition.model.dto.ProcessDefListResponse;
import com.tongtech.tfw.workflow.apis.task.model.dto.*;
import com.tongtech.tfw.workflow.apis.task.service.ActRuTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(
        value = "Wf Task Controller",
        tags = {"WF流程任务管理"}
)
@RequestMapping({"/new/wf/task"})
public class TaskController extends SuperController {

    @Autowired
    private RuTaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ActRuTaskService actRuTaskService;

    @Autowired
    private TEmergencyRehearsalService rehearsalService;

    @ApiOperation(
            value = "已办任务",
            notes = "已办任务"
    )
    @GetMapping({"/getHisTask"})
    public BaseResponse<HisTask> hisTaskList(HisTaskListRequest hisTaskListRequest) {
        BaseResponse<HisTask> taskBaseResponse = new BaseResponse();
        HisTask queryList = this.taskService.getHisTask(hisTaskListRequest);
        taskBaseResponse.setData(queryList);
        return taskBaseResponse;
    }


    @ApiOperation(
            value = "流程定义列表",
            notes = "List Process Definition"
    )
    @GetMapping({"/list"})
    public BaseResponse<BaseResponseList<ProcessDefListResponse>> listAllEntity(ProcessDefListRequestVO param) {
        BaseResponse<BaseResponseList<ProcessDefListResponse>> baseResponse = new BaseResponse<>();
        BaseResponseList<ProcessDefListResponse> processDefList = this.taskService.getProcessDefList(param);
        baseResponse.setData(processDefList);
        return baseResponse;
    }


    @ApiOperation(
            value = "统计用户 每个流程定义中 未处理的个数",
            notes = "统计用户 每个流程定义中 未处理的个数"
    )
    @GetMapping({"/todo/countToDo"})
    public BaseResponse<List<Map>> countToDo() {
        BaseResponse<List<Map>> baseResponse = new BaseResponse();
        UserInfo userInfo = ContextUtils.getLoginUser();
        List<Map> countList = this.taskService.countToDo(userInfo.getUserId(), userInfo.getOrgId());
        baseResponse.setData(countList);
        return baseResponse;
    }

    @ApiOperation(value = "完成流程", notes = "完成流程 通过")
    @PostMapping(value = "/getNextNodeNames")
    public BaseResponse<BizGeneralResponse> getNextNodeNames(@RequestBody THazardWorkPlanDTO tHazardWorkPlanDTO){
        BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
        if(ObjectHelper.isNotEmpty(tHazardWorkPlanDTO)&& StringHelper.isNotEmpty(tHazardWorkPlanDTO.getId())){
            List<String> nodeNames = taskService.getNextNameTasks(tHazardWorkPlanDTO.getProcessId(), tHazardWorkPlanDTO.getMap());
        }
        return baseResponse;
    }


    @ApiOperation(
            value = "待办任务(包含待签收),pc端",
            notes = "待办任务(包含待签收),pc端"
    )
    @GetMapping({"/todo/list"})
    public BaseResponse<BaseResponseList<TodoTask>> toDoTaskList(TodoListRequest todoListRequest) {
        BaseResponse<BaseResponseList<TodoTask>> baseResponse = new BaseResponse();
        BaseResponseList<TodoTask> resultResList = new BaseResponseList();
        Long page = StringHelper.isEmpty(todoListRequest.getPage()) ? BizConstants.PAGE : Long.valueOf(todoListRequest.getPage());
        Long limit = StringHelper.isEmpty(todoListRequest.getLimit()) ? BizConstants.LIMIT : Long.valueOf(todoListRequest.getLimit());
        Page<TodoTask> resultPage = new Page(page, limit);
        TodoTaskSqlParam todoTaskSqlParam = new TodoTaskSqlParam();
        if (StringHelper.isNotBlank(todoListRequest.getUsername())) {
            todoTaskSqlParam.setUserId(todoListRequest.getUsername());
        } else {
            todoTaskSqlParam.setUserId(this.getUserId());
        }

        if (StringHelper.isNotBlank(todoListRequest.getStartUser())) {
            todoTaskSqlParam.setUserName(todoListRequest.getStartUser());
        }

        if (StringHelper.isNotBlank(todoListRequest.getProcessDefinitionName())) {
            todoTaskSqlParam.setProDefName(todoListRequest.getProcessDefinitionName());
        }

        if (StringHelper.isNotBlank(todoListRequest.getProcessDefinitionId())) {
            todoTaskSqlParam.setProDefId(todoListRequest.getProcessDefinitionId());
        }

        if (StringHelper.isNotBlank(todoListRequest.getProcessDefinitionKey())) {
            todoTaskSqlParam.setProDefKey(todoListRequest.getProcessDefinitionKey());
        }

        if (StringHelper.isNotBlank(todoListRequest.getOrgId())) {
            todoTaskSqlParam.setOrgId(todoListRequest.getOrgId());
        } else {
            UserInfo curUser = ContextUtils.getLoginUser();
            todoTaskSqlParam.setOrgId(curUser.getOrgId());
        }

        IPage<TodoTask> queryList = taskService.selectToDoList(resultPage, todoTaskSqlParam);
        List<TodoTask> resultList = queryList.getRecords();
        resultList.forEach((task) -> {
            task.setAssigned(StringHelper.isBlank(task.getAssignee()) ? "0" : "1");
            task.setProcessInstanceSuspended(((ProcessInstance)runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult()).isSuspended());
        });
        resultResList.setData(resultList);
        resultResList.setTotal(queryList.getTotal());
        baseResponse.setData(resultResList);
        return baseResponse;
    }

    @ApiOperation(value = "已办任务(pc端)", notes = "已办任务(pc端)")
    @GetMapping({"/history/list"})
    public BaseResponse<BaseResponseList<HisTask>> hisTaskPcList(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.taskService.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;
    }

}
