package com.qmth.distributed.print.api;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.annotation.BOOL;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.distributed.print.business.bean.params.FlowApproveParam;
import com.qmth.distributed.print.business.bean.params.FlowParam;
import com.qmth.distributed.print.business.bean.result.EditResult;
import com.qmth.distributed.print.business.bean.result.FlowApproveResult;
import com.qmth.distributed.print.business.bean.result.FlowTaskApprovePeopleAllResult;
import com.qmth.distributed.print.business.bean.result.FlowTaskResult;
import com.qmth.distributed.print.business.entity.ExamTask;
import com.qmth.distributed.print.business.entity.TFFlow;
import com.qmth.distributed.print.business.entity.TFFlowApprove;
import com.qmth.distributed.print.business.entity.TFFlowApproveLog;
import com.qmth.distributed.print.business.service.ActivitiService;
import com.qmth.distributed.print.business.service.PrintCommonService;
import com.qmth.distributed.print.business.service.TFFlowApproveLogService;
import com.qmth.distributed.print.business.service.TFFlowService;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.BasicAttachment;
import com.qmth.teachcloud.common.entity.SysUser;
import com.qmth.teachcloud.common.enums.*;
import com.qmth.teachcloud.common.service.BasicAttachmentService;
import com.qmth.teachcloud.common.util.AesUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import com.qmth.teachcloud.common.util.ServletUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 流程表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2021-08-02
 */
@Api(tags = "流程Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/${prefix.url.flow}")
//@Aac(auth = BOOL.FALSE, strict = BOOL.FALSE)
public class TFFlowController {
    private final static Logger log = LoggerFactory.getLogger(TFFlowController.class);

    @Resource
    PrintCommonService printCommonService;

    @Resource
    BasicAttachmentService basicAttachmentService;

    @Resource
    ActivitiService activitiService;

    @Resource
    TFFlowService tfFlowService;

    @Resource
    TFFlowApproveLogService tfFlowApproveLogService;


    @ApiOperation(value = "注册流程")
    @Transactional
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result register(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file,
                           @ApiParam(value = "流程文件名称", required = true) @RequestParam String name) {
        BasicAttachment basicAttachment = null;
        try {
            int temp = file.getOriginalFilename().lastIndexOf(".");
            String fileName = file.getOriginalFilename().substring(0, temp);
            String format = file.getOriginalFilename().substring(temp, file.getOriginalFilename().length());
            if (!format.equalsIgnoreCase(".bpmn")) {
                throw ExceptionResultEnum.ERROR.exception("上传的流程文件格式只能为.bmpn");
            }
            basicAttachment = printCommonService.saveAttachment(file, ServletUtil.getRequestMd5(), UploadFileEnum.FILE);
            if (Objects.isNull(basicAttachment)) {
                throw ExceptionResultEnum.ATTACHMENT_ERROR.exception();
            }
            activitiService.uploadDeployment(file);
            String actFlowId = tfFlowService.findActIdByFlowKey(SystemConstant.GDYKDX_FLOW_KEY);
            SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
            TFFlow tfFlow = new TFFlow(SystemConstant.getHeadOrUserSchoolId(), sysUser.getOrgId(), name, sysUser.getId(), fileName, actFlowId);
            tfFlowService.save(tfFlow);
        } catch (Exception e) {
            log.error("请求出错", e);
            if (Objects.nonNull(basicAttachment)) {
                basicAttachmentService.deleteAttachment(basicAttachment);
            }
            if (e instanceof DuplicateKeyException) {
                String errorColumn = e.getCause().toString();
                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
            } else if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        }
        return ResultUtil.ok(new EditResult(basicAttachment.getId()));
    }

//    @ApiOperation(value = "发布流程")
//    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
//    @RequestMapping(value = "/publish", method = RequestMethod.POST)
//    public Result publish(@ApiParam(value = "流程文件id", required = true) @RequestParam String id) {
//        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
//        UpdateWrapper tfFlowUpdateWrapper = new UpdateWrapper<>();
//        tfFlowUpdateWrapper.lambda().eq(TFFlow::getId, Long.parseLong(id))
//                .set(TFFlow::getPublish, true)
//                .set(TFFlow::getUpdateId, sysUser.getId())
//                .set(TFFlow::getUpdateTime, System.currentTimeMillis());
//        return ResultUtil.ok(tfFlowService.update(tfFlowUpdateWrapper));
//    }

    @ApiOperation(value = "流程逻辑删除")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/enable", method = RequestMethod.POST)
    public Result enable(@Valid @RequestBody FlowParam flowParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultUtil.ok(activitiService.flowDelete(flowParam.getId()));
    }

    @ApiOperation(value = "流程列表")
    @ApiResponses({@ApiResponse(code = 200, message = "流程信息", response = TFFlow.class)})
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result list(@ApiParam(value = "流程名称", required = false) @RequestParam(required = false) String name,
                       @ApiParam(value = "页码", required = true) @RequestParam Integer pageNumber,
                       @ApiParam(value = "数量", required = true) @RequestParam Integer pageSize) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(tfFlowService.list(new Page<>(pageNumber, pageSize), name, SystemConstant.getHeadOrUserSchoolId(), sysUser.getOrgId()));
    }

    @ApiOperation(value = "审批流程")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/task/approve", method = RequestMethod.POST)
    public Result taskApprove(@ApiParam(value = "流程任务id", required = true) @RequestParam String taskId,
                              @ApiParam(value = "流程审批操作", required = false) @RequestParam(required = false) FlowApprovePassEnum approvePass,
                              @ApiParam(value = "流程审核意见", required = false) @RequestParam(required = false) String remark,
                              @ApiParam(value = "流程驳回节点", required = false) @RequestParam(required = false) Integer setup) {
        Map<String, Object> map = new HashMap<>();
        map.computeIfAbsent(SystemConstant.FLOW_TASK_ID, v -> taskId);
        map.computeIfAbsent(SystemConstant.APPROVE_OPERATION, v -> approvePass);
        map.computeIfAbsent(SystemConstant.APPROVE_REMARK, v -> remark);
        map.computeIfAbsent(SystemConstant.APPROVE_SETUP, v -> setup);
        Map<String, Object> objectMap = activitiService.taskApprove(map);
        if (Objects.nonNull(objectMap)) {
            TFFlowApprove tfFlowApprove = (TFFlowApprove) objectMap.get("tfFlowApprove");
            //审核通过，生成pdf
            if (Objects.nonNull(tfFlowApprove) && FlowGdykdxApproveSetupEnum.FINISH.getSetup() == tfFlowApprove.getSetup()) {
                ExamTask examTask = (ExamTask) objectMap.get("examTask");
                SysUser sysUser = (SysUser) objectMap.get("sysUser");
                try {
                    printCommonService.checkData(examTask.getSchoolId(), examTask.getCourseCode(), examTask.getPaperNumber(), sysUser);
                } catch (IOException e) {
                    throw ExceptionResultEnum.ERROR.exception("生成pdf失败");
                }
            }
        }
        return ResultUtil.ok();
    }

    @ApiOperation(value = "流程审批记录列表")
    @ApiResponses({@ApiResponse(code = 200, message = "流程审批记录信息", response = FlowApproveResult.class)})
    @RequestMapping(value = "/approve/list", method = RequestMethod.POST)
    public Result taskApproveList(@ApiParam(value = "发起人名称", required = false) @RequestParam(required = false) String startName,
                                  @ApiParam(value = "页码", required = true) @RequestParam Integer pageNumber,
                                  @ApiParam(value = "数量", required = true) @RequestParam Integer pageSize) {
        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(tfFlowService.flowApproveList(new Page<>(pageNumber, pageSize), startName, SystemConstant.getHeadOrUserSchoolId(), sysUser.getOrgId(), null));
    }

    @ApiOperation(value = "流程审批记录逻辑删除")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/approve/enable", method = RequestMethod.POST)
    public Result enable(@Valid @RequestBody FlowApproveParam flowApproveParam, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        UpdateWrapper<TFFlowApproveLog> tfFlowApproveLogUpdateWrapper = new UpdateWrapper<>();
        tfFlowApproveLogUpdateWrapper.lambda().eq(TFFlowApproveLog::getFlowId, flowApproveParam.getFlowId())
                .set(TFFlowApproveLog::getEnable, flowApproveParam.getEnable());
        return ResultUtil.ok(tfFlowApproveLogService.update(tfFlowApproveLogUpdateWrapper));
    }

    @ApiOperation(value = "流程终止")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/end", method = RequestMethod.POST)
    public Result end(@ApiParam(value = "流程id", required = true) @RequestParam String flowId) {
        activitiService.flowEnd(flowId);
        return ResultUtil.ok();
    }

    @ApiOperation(value = "获取所有流程节点")
    @ApiResponses({@ApiResponse(code = 200, message = "流程节点", response = FlowTaskResult.class)})
    @RequestMapping(value = "/task/all", method = RequestMethod.POST)
    public Result taskAll(@ApiParam(value = "流程id", required = true) @RequestParam String flowId) {
        return ResultUtil.ok(activitiService.getTaskAll(flowId));
    }

    @ApiOperation(value = "获取所有流程节点待审批人")
    @ApiResponses({@ApiResponse(code = 200, message = "流程节点待审批人", response = FlowTaskApprovePeopleAllResult.class)})
    @RequestMapping(value = "/task/approver/people_all", method = RequestMethod.POST)
    public Result taskApproverPeopleAll(@ApiParam(value = "课程编码", required = false) @RequestParam(required = false) String courseCode,
                                        @ApiParam(value = "流程节点id", required = false) @RequestParam(required = false) String taskId) {
        return ResultUtil.ok(activitiService.taskApproverPeopleAll(courseCode, taskId));
    }

    @ApiOperation(value = "流程节点转他人审批")
    @ApiResponses({@ApiResponse(code = 200, message = "常规信息", response = ResultUtil.class)})
    @RequestMapping(value = "/task/approver/exchange", method = RequestMethod.POST)
    public Result taskApproverExchange(@ApiParam(value = "审批人id", required = true) @RequestParam String userId,
                                       @ApiParam(value = "流程节点id", required = true) @RequestParam String taskId) {
        return ResultUtil.ok(activitiService.taskApproverExchange(userId, taskId));
    }

    @ApiOperation(value = "获取转他人审批人")
    @ApiResponses({@ApiResponse(code = 200, message = "流程节点审批人", response = FlowTaskApprovePeopleAllResult.class)})
    @RequestMapping(value = "/task/approver/exchange/people", method = RequestMethod.POST)
    public Result taskApproverExchangePeople(@ApiParam(value = "流程节点id", required = true) @RequestParam String taskId,
                                             @ApiParam(value = "用户姓名", required = false) @RequestParam(required = false) String realName) {
        return ResultUtil.ok(activitiService.taskApproverExchangePeople(taskId, realName));
    }
}
