package com.iformall.controller.workflow;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.domain.po.WxFlowConfig;
import com.iformall.domain.po.WxFlowModel;
import com.iformall.domain.po.WxFlowRecord;
import com.iformall.enums.EnumFlowRecordStatus;
import com.iformall.service.WxFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@Api(description = "工作流相关接口")
@RequestMapping(value = "workflow")
public class WxFlowAbleController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxFlowService wxFlowService;

    @ApiOperation(value = "启动流程",notes = "{\"businessId\":\"221178539888607232\",\"businessType\":1,\"remark\":\"意见意见。\",\"taskAssignee\":[{\"taskKey\":\"firstTaskUser\",\"assignee\":\"243650055783841792\"},{\"taskKey\":\"secondTaskUser\",\"assignee\":\"\"}],\"variables\":[{\"key\":\"contractType\",\"value\":\"1\"},{\"key\":\"contractNumber\",\"value\":\"1111\"}]}")
    @PostMapping("/start")
    @SystemControllerLog(description = "工作流-启动流程")
    public ResultData start(@RequestBody Map<String, Object> params) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::start");
        MallUserInfo user = getUser();
        return wxFlowService.start(params, user.getId(),user.getName(),user.getTenantId());
    }

    /**
     * 用户代办列表
     */
    @ApiOperation("用户代办列表")
    @GetMapping(value = "/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "flowType", value = "流程类型,1合同流程 2账单流程", dataType = "string", paramType = "query", required = true)
    })
    @SystemControllerLog(description = "工作流-用户代办列表")
    public ResultData list(String flowType,Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::list");
        return wxFlowService.list(flowType,pageNum,pageSize,getUserId(),getTenantId());
    }

    /**
     * 我的申请列表
     */
    @ApiOperation("我的申请列表")
    @GetMapping(value = "/myApplyList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-我的申请列表")
    public ResultData myApplyList(@ModelAttribute WxFlowRecord record, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::myApplyList");
        record.setUserId(getUserId());
        record.setStatus(EnumFlowRecordStatus.NEW.getCode());

        PageInfo<WxFlowRecord> pageInfo = wxFlowService.listAsPage(record,pageNum,pageSize);
        List<WxFlowRecord> recordList = pageInfo.getList();
        for (WxFlowRecord wxFlowRecord:recordList) {
            if(StringUtils.isBlank(wxFlowRecord.getVariables())){
                wxFlowRecord.setVariables("{}");
            }
        }
        return new ResultData(pageInfo);
    }

    /**
     * 我的审批列表
     */
    @ApiOperation("我的审批列表")
    @GetMapping(value = "/myHandleList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-我的审批列表")
    public ResultData myHandleList(@ModelAttribute WxFlowRecord record, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::myHandelList");
        record.setUserId(getUserId());
        record.setStatus(EnumFlowRecordStatus.NEW.getCode());
        PageInfo<WxFlowRecord> pageInfo = wxFlowService.myHandelList(record,pageNum,pageSize);
        List<WxFlowRecord> recordList = pageInfo.getList();
        for (WxFlowRecord wxFlowRecord:recordList) {
            if(StringUtils.isBlank(wxFlowRecord.getVariables())){
                wxFlowRecord.setVariables("{}");
            }
        }
        return new ResultData(pageInfo);
    }

    /**
     * 审批历史
     */
    @ApiOperation("审批历史")
    @GetMapping(value = "/applyHistory")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessId", value = "业务id", dataType = "long", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-审批历史")
    public ResultData applyHistory(Long businessId) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::applyHistory");
        return wxFlowService.applyHistory(businessId,super.getTenantId());
    }

    /**
     * 审批历史和代办
     */
    @ApiOperation("审批历史和代办")
    @GetMapping(value = "/applyHistoryAndAssignee")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "businessId", value = "业务id", dataType = "long", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-审批历史和代办")
    public ResultData applyHistoryAndAssignee(Long businessId) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::applyHistoryAndAssignee");
        return wxFlowService.getTaskStatusList(businessId,super.getTenantId());
    }

    /**
     * 审批
     */
    @ApiOperation(value = "审批",notes = "{\"taskId\":\"\",\"processInstanceId\":\"\",\"remark\":\"\"}")
    @PostMapping(value = "apply")
    public ResultData apply(@RequestBody Map<String, String> params) {
        MallUserInfo user = getUser();
        return wxFlowService.apply(params,user.getId(),user.getName(),user.getTenantId());
    }

    /**
     * 驳回
     */
    @ApiOperation(value = "驳回",notes = "{\"taskId\":\"\",\"processInstanceId\":\"\",\"remark\":\"\"}")
    @PostMapping(value = "reject")
    @SystemControllerLog(description = "工作流-驳回")
    public ResultData reject(@RequestBody Map<String, Object> params) {
        MallUserInfo user = getUser();
        return wxFlowService.reject(params,user.getId(),user.getName(),user.getPhone(),user.getTenantId());
    }


    /**
     * 撤回
     */
    @ApiOperation(value = "撤回",notes = "{\"taskId\":\"\",\"processInstanceId\":\"\",\"remark\":\"\"}")
    @PostMapping(value = "setBack")
    @SystemControllerLog(description = "工作流-撤回")
    public ResultData setBack(@RequestBody Map<String, Object> params) {
        MallUserInfo user = getUser();
        return wxFlowService.setBack(params,user.getId(),user.getName());
    }


    /**
     * 创建模板
     */
    @ApiOperation(value = "创建模板")
    @PostMapping(value = "createModel")
    @SystemControllerLog(description = "工作流-创建模板")
    public ResultData createModel(@RequestBody WxFlowModel wxFlowModel) {
        wxFlowModel.setTenantId(getTenantId());
        wxFlowModel.setCreateUser(getUserId());
        return wxFlowService.createModel(wxFlowModel);
    }

    /**
     * 根据id查询模板
     */
    @ApiOperation(value = "根据id查询模板",notes = "")
    @GetMapping(value = "findModelById")
    @SystemControllerLog(description = "工作流-根据id查询模板")
    public ResultData findById(@ModelAttribute WxFlowModel wxFlowModel){
        wxFlowModel.setTenantId(getTenantId());
        return wxFlowService.findModelById(wxFlowModel);
    }

    /**
     * 删除模板
     */
    @ApiOperation(value = "删除模板")
    @PostMapping(value = "delModel")
    @SystemControllerLog(description = "工作流-删除模板")
    public ResultData delModel(@RequestBody WxFlowModel wxFlowModel) {
        wxFlowModel.setTenantId(getTenantId());
        return wxFlowService.delModel(wxFlowModel);
    }

    /**
     * 模板列表
     */
    @ApiOperation("模板列表")
    @GetMapping(value = "/modelList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-模板列表")
    public ResultData modelList(@ModelAttribute WxFlowModel wxFlowModel,Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::modelList");
        wxFlowModel.setTenantId(getTenantId());
        return new ResultData(wxFlowService.modelList(wxFlowModel,pageNum,pageSize));
    }

    /**
     * 根据业务查询模板
     */
    @ApiOperation("根据业务查询模板")
    @GetMapping(value = "/getModelBybusiness")
    @SystemControllerLog(description = "工作流-模板列表")
    public ResultData getModelBybusiness(@ModelAttribute WxFlowModel wxFlowModel) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::getModelBybusiness");
        wxFlowModel.setTenantId(getTenantId());
        return new ResultData(wxFlowService.getModelBybusiness(wxFlowModel));
    }


    /**
     * 配置列表
     */
    @ApiOperation("配置列表")
    @GetMapping(value = "/configList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true),
    })
    @SystemControllerLog(description = "工作流-配置列表")
    public ResultData configList(@ModelAttribute WxFlowConfig wxFlowConfig, Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] FlowAbleController::modelList");
        wxFlowConfig.setTenantId(getTenantId());
        if(pageSize == null){
            pageSize = Integer.MAX_VALUE;
        }
        if(pageNum == null){
            pageNum = 1;
        }

        wxFlowConfig.setParentId(0l);
        PageInfo<WxFlowConfig> pageInfo = wxFlowService.configList(wxFlowConfig,pageNum,pageSize);
        List<WxFlowConfig> list = pageInfo.getList();
        for (WxFlowConfig c:list) {
            if(CollectionUtils.isNotEmpty(c.getChilds())){
                for (WxFlowConfig ch:c.getChilds()) {
                    if(ch.getModelId() != null){
                        WxFlowModel query = new WxFlowModel();
                        query.setId(ch.getModelId());
                        ch.setWxFlowModel((WxFlowModel)wxFlowService.findModelById(query).data);
                    }
                }
            }
        }
        pageInfo.setList(list);
        return new ResultData(pageInfo);
    }

    /**
     * 类型设置
     */
    @ApiOperation(value = "类型设置")
    @PostMapping(value = "updateConfig")
    @SystemControllerLog(description = "工作流-类型设置")
    public ResultData updateConfig(@RequestBody WxFlowConfig wxFlowConfig) {
        wxFlowConfig.setTenantId(getTenantId());
        return wxFlowService.updateConfig(wxFlowConfig);
    }


}