package com.testor.module.hazard.controller;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.testor.common.util.BeanConverUtil;
import com.testor.common.util.excel.EasyExcelUtil;
import com.testor.module.contractor.ledger.model.template.PersonTemplate;
import com.testor.module.contractor.manage.model.dto.TContractorAllowParam;
import com.testor.module.hazard.model.dto.*;
import com.testor.module.hazard.model.template.THazardWorkPlanTemplate;
import com.testor.module.wf.vo.HisTasksResponseDTO;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.workflow.apis.instance.model.domain.ActHiProcinst;
import com.tongtech.tfw.workflow.apis.instance.service.ActHiProcinstService;
import com.tongtech.tfw.workflow.apis.task.model.dto.*;
import com.tongtech.tfw.workflow.apis.task.service.ActRuTaskService;
import com.tongtech.tfw.workflow.service.TfwCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.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.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;

import com.testor.module.hazard.model.domain.THazardWorkPlan;
import com.testor.module.hazard.service.THazardWorkPlanService;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 危险作业计划Controller
 *
 * @author testor-framework
 * @date 2024-12-19 10:39:26
 */
@RestController
@RequestMapping("/hazard/plan")
@Api(value = "THazardWorkPlan", tags = "危险作业计划")
@Slf4j
public class THazardWorkPlanController extends SuperController
{
    @Autowired
    private THazardWorkPlanService tHazardWorkPlanService;

    /* Generated Method*/
	@ApiOperation(value = "新增 危险作业计划", notes = "Add THazardWorkPlan")
	@PostMapping(value = "/add")
	public BaseResponse<THazardWorkPlan>addEntity(@RequestBody THazardWorkPlan addRequest) {
		BaseResponse<THazardWorkPlan> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(addRequest)){
			THazardWorkPlan data = tHazardWorkPlanService.addEntity(addRequest);
			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 危险作业计划 ", notes = "Get THazardWorkPlan By Id")
	@GetMapping(value = "/get")
	public BaseResponse<THazardWorkPlanDTO> getById(String id){
		BaseResponse<THazardWorkPlanDTO> baseResponse=new BaseResponse<>();
		if(StringHelper.isNotEmpty(id)){
			// TODO 按需求添加业务异常判断
            THazardWorkPlanDTO data= tHazardWorkPlanService.getDetailsById(id);
			baseResponse.setData(data);
		}
		return baseResponse;
	}

	@ApiOperation(
			value = "待办任务(包含待签收)",
			notes = "待办任务(包含待签收)"
	)
	@GetMapping({"/todo/list"})
	public BaseResponse<BaseResponseList<TodoTaskDTO>> toDoTaskList(TodoListRequest todoListRequest) {
		BaseResponse<BaseResponseList<TodoTaskDTO>> baseResponse = new BaseResponse();
		BaseResponseList<TodoTaskDTO> resultResList = new BaseResponseList();
		IPage<TodoTaskDTO> todoTaskDTOIPage = tHazardWorkPlanService.selectToDoList(todoListRequest);
		resultResList.setData(todoTaskDTOIPage.getRecords());
		resultResList.setTotal(todoTaskDTOIPage.getTotal());
		baseResponse.setData(resultResList);
		return baseResponse;
	}

	@ApiOperation(
			value = "已办任务",
			notes = "已办任务"
	)
	@GetMapping({"/history/list"})
	public BaseResponse<BaseResponseList<HisTaskDTO>> hisTaskList(HisTaskListRequest hisTaskListRequest) {
		BaseResponse<BaseResponseList<HisTaskDTO>> baseResponse = new BaseResponse();
		BaseResponseList<HisTaskDTO> resultResList = new BaseResponseList();
		IPage<HisTaskDTO> queryList = this.tHazardWorkPlanService.hisTaskList(hisTaskListRequest);
		resultResList.setData(queryList.getRecords());
		resultResList.setTotal(queryList.getTotal());
		baseResponse.setData(resultResList);
		return baseResponse;
	}

	@ApiOperation(value = "提交", notes = "启动流程")
	@PostMapping(value = "/submit")
	public BaseResponse<BizGeneralResponse> submit(@RequestBody THazardWorkPlanDTO tHazardWorkPlanDTO){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		tHazardWorkPlanService.submit(tHazardWorkPlanDTO);
		return baseResponse;
	}

	@ApiOperation(value = "完成流程", notes = "完成流程 通过")
	@PostMapping(value = "/completeProcess")
	public BaseResponse<BizGeneralResponse> completeProcess(@RequestBody THazardWorkPlanDTO tHazardWorkPlanDTO){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(tHazardWorkPlanDTO)&&StringHelper.isNotEmpty(tHazardWorkPlanDTO.getId())){
			tHazardWorkPlanService.completeProcess(tHazardWorkPlanDTO);
		}
		return baseResponse;
	}


	@ApiOperation(value = "驳回流程", notes = "完成流程 驳回")
	@PostMapping(value = "/rejectedProcess")
	public BaseResponse<BizGeneralResponse> rejectedProcess(@RequestBody THazardWorkPlanDTO tHazardWorkPlanDTO){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(tHazardWorkPlanDTO)){
			tHazardWorkPlanService.rejectedProcess(tHazardWorkPlanDTO);
		}
		return baseResponse;
	}

	@ApiOperation(value = "取消流程", notes = "取消流程")
	@PostMapping(value = "/cancelProcess")
	public BaseResponse<BizGeneralResponse> cancelProcess(@RequestBody @Valid CompleteTask completeTask){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		tHazardWorkPlanService.cancelProcess(completeTask);
		return baseResponse;
	}

	@ApiOperation(value = "发送通知-测试使用", notes = "发送通知-测试使用")
	@GetMapping(value = "/hazardousWorkMessageAlerts")
	public BaseResponse<BizGeneralResponse> hazardousWorkMessageAlerts(){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		tHazardWorkPlanService.hazardousWorkMessageAlerts();
		return baseResponse;
	}



	@ApiOperation(
			value = "根据流程实例ID获取任务历史",
			notes = "根据流程实例ID获取任务历史"
	)
	@GetMapping({"/getHistoryByInstanceId"})
	public BaseResponse<BaseResponseList<HisTasksResponseDTO>> getHistoryByInstanceId(HisTasksRequest hisTasksRequest,String planId) {
		BaseResponse<BaseResponseList<HisTasksResponseDTO>> baseResponse = new BaseResponse<>();
		BaseResponseList<HisTasksResponseDTO> resultResList = new BaseResponseList<>();
		List<HisTasksResponseDTO> hisTasksResponses = tHazardWorkPlanService.getHistoryByInstanceId(hisTasksRequest,planId);
		resultResList.setData(hisTasksResponses);
		baseResponse.setData(resultResList);
		return baseResponse;
	}


	@ApiOperation(
			value = "根据流程实例ID获取任务历史",
			notes = "根据流程实例ID获取任务历史"
	)
	@GetMapping({"/getAllTaskApprovers"})
	public BaseResponse<List<TaskInfoDTO>> getAllTaskApprovers(String processInstanceId,String planId) {
		BaseResponse<List<TaskInfoDTO>> baseResponse = new BaseResponse<>();
		List<TaskInfoDTO> allTaskApprovers = tHazardWorkPlanService.getAllTaskApprovers(processInstanceId, planId);
		baseResponse.setData(allTaskApprovers);
		return baseResponse;
	}

	@ApiOperation(value = "修改 危险作业计划 ", notes = "Update THazardWorkPlan By Id")
	@PutMapping(value = "/update")
	public BaseResponse<THazardWorkPlan> updateEntity(@RequestBody THazardWorkPlan updateRequest){
		BaseResponse<THazardWorkPlan> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(updateRequest)&&StringHelper.isNotEmpty(updateRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
			THazardWorkPlan tHazardWorkPlan = tHazardWorkPlanService.updateEntity(updateRequest);
			baseResponse.setData(tHazardWorkPlan);
		}
		return baseResponse;
	}

	@ApiOperation(value = "删除 危险作业计划 ", notes = "delete THazardWorkPlan By Id")
	@PutMapping(value = "/delete")
	public BaseResponse<BizGeneralResponse> deleteEntity(@RequestBody THazardWorkPlanDelParam deleteRequest){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		if(ObjectHelper.isNotEmpty(deleteRequest)&&StringHelper.isNotEmpty(deleteRequest.getId())){
			// TODO 按需求添加数据去重，特殊值设定，业务异常
            THazardWorkPlan data= new THazardWorkPlan();
			data.setId(deleteRequest.getId());
			data.setStatus(BizConstants.STATUS_DELETE);
			boolean result= tHazardWorkPlanService.updateById(data);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "批量删除危险作业计划", notes = "delete THazardWorkPlan by batch Id")
	@PutMapping(value = "/batch_delete")
	public BaseResponse<BizGeneralResponse> deleteEntityBatch(
			@RequestBody THazardWorkPlanDelParam deleteRequest) {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		if (ObjectHelper.isNotEmpty(deleteRequest) && (!deleteRequest.getIds().isEmpty())) {
            /* 批量删除 */
			List<THazardWorkPlan> tHazardWorkPlanList = new ArrayList<>();
            for(String id: deleteRequest.getIds()){
                THazardWorkPlan data= new THazardWorkPlan();
				data.setId(id);
				data.setStatus(BizConstants.STATUS_DELETE);
                tHazardWorkPlanList.add(data);
			}
			boolean result = tHazardWorkPlanService.updateBatchById(tHazardWorkPlanList);
			baseResponse.setData(
					BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
		}
		return baseResponse;
	}

	@ApiOperation(value = "获取 危险作业计划 分页列表", notes = "List THazardWorkPlan with page")
	@GetMapping(value = "/list")
	public  BaseResponse<BaseResponseList<THazardWorkPlanDTO>>listEntity(THazardWorkPlanParam param){
		BaseResponse<BaseResponseList<THazardWorkPlanDTO>>baseResponse=new BaseResponse<>();
		Page<THazardWorkPlanDTO> resultList= tHazardWorkPlanService.listEntity(param);
		BaseResponseList<THazardWorkPlanDTO> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "获取 危险作业计划 列表", notes = "List THazardWorkPlan all")
	@GetMapping(value = "/datas")
	public  BaseResponse<BaseResponseList<THazardWorkPlanDTO>>listAllEntity(THazardWorkPlanParam param){
		BaseResponse<BaseResponseList<THazardWorkPlanDTO>>baseResponse=new BaseResponse<>();

		List<THazardWorkPlanDTO> resultList=tHazardWorkPlanService.listAllEntity(param);
		BaseResponseList<THazardWorkPlanDTO> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList);
		baseResponseList.setTotal(resultList.size());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}

	@ApiOperation(value = "导出明细", notes = "导出明细")
	@GetMapping(value = "/export")
	public  BaseResponse<BizGeneralResponse> export(HttpServletResponse response, THazardWorkPlanParam param){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		List<THazardWorkPlanDTO> tHazardWorkPlans = tHazardWorkPlanService.listAllEntity(param);
		if (CollectionUtils.isEmpty(tHazardWorkPlans)) {
			baseResponse.setData(BizGeneralResponse.builder().result("无作业计划数据").build());
			return baseResponse;
		}
		List<THazardWorkPlanTemplate> tHazardWorkPlanTemplates = BeanConverUtil.converList(tHazardWorkPlans, THazardWorkPlanTemplate.class);
		int index = 1;
		for(THazardWorkPlanTemplate template : tHazardWorkPlanTemplates){
			template.setNumber(String.valueOf(index++));
		}
		EasyExcelUtil.writeExcel(response, "危险作业计划", "危险作业计划", tHazardWorkPlanTemplates);
		baseResponse.setData(
				BizGeneralResponse.builder().result(TypeHelper.castToString(true)).build());
		return baseResponse;
	}

	@ApiOperation(value = "导出作业票", notes = "导出作业票")
	@GetMapping(value = "/exportJobTicket")
	public  void  exportJobTicket(HttpServletResponse response, THazardWorkPlanParam param) throws BusinessException {
		boolean result = tHazardWorkPlanService.exportJobTicket(response,param);
		if(!result){
			throw new BusinessException(500,"无可导出的作业票数据");
		}
	}

	/*@ApiOperation(value = "危险作业计划时间是否合规", notes = "危险作业计划时间是否合规")
	@GetMapping(value = "/validateOperation")
	public  BaseResponse  validateOperation(String workType, String workLevel, String scheduledStartTime,String scheduledEndTime) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		String result = tHazardWorkPlanService.validateOperation(workType,workLevel,scheduledStartTime,scheduledEndTime);
		baseResponse.setMsg(result);
		return baseResponse;

	}*/

	@ApiOperation(value = "任务转签", notes = "任务转签")
	@GetMapping(value = "/transferTask")
	public  BaseResponse  transferTask(TransferDTO transferDTO) throws BusinessException {
		BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
		transferDTO.setCurrentUserId(getUserId());
		tHazardWorkPlanService.transferTask(transferDTO);
		baseResponse.setMsg("任务转签成功");
		return baseResponse;
	}

	@ApiOperation(value = "任务撤回", notes = "任务撤回")
	@PostMapping(value = "/recallProcess")
	public BaseResponse<BizGeneralResponse> recallProcess(@RequestBody @Valid CompleteTask completeTask){
		BaseResponse<BizGeneralResponse> baseResponse=new BaseResponse<>();
		tHazardWorkPlanService.recallProcess(completeTask);
		return baseResponse;
	}

	@ApiOperation(value = "沿江大区获取 危险作业计划 分页列表", notes = "List THazardWorkPlan with page")
	@GetMapping(value = "/riversideList")
	public  BaseResponse<BaseResponseList<THazardWorkPlanRiverside>>riversideList(THazardWorkPlanParam param){
		BaseResponse<BaseResponseList<THazardWorkPlanRiverside>>baseResponse=new BaseResponse<>();
		Page<THazardWorkPlanRiverside> resultList= tHazardWorkPlanService.riversideList(param);
		BaseResponseList<THazardWorkPlanRiverside> baseResponseList=new BaseResponseList<>();
		baseResponseList.setData(resultList.getRecords());
		baseResponseList.setTotal(resultList.getTotal());
		baseResponse.setData(baseResponseList);
		return baseResponse;
	}


}
