package com.yunzhupaas.flowable.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.flowable.entity.TemplateJsonEntity;
import com.yunzhupaas.flowable.entity.TemplateNodeEntity;
import com.yunzhupaas.flowable.enums.NodeEnum;
import com.yunzhupaas.flowable.model.trigger.TriggerDataFo;
import com.yunzhupaas.flowable.model.trigger.TriggerDataModel;
import com.yunzhupaas.flowable.model.trigger.TriggerModel;
import com.yunzhupaas.flowable.service.TemplateJsonService;
import com.yunzhupaas.flowable.service.TemplateNodeService;
import com.yunzhupaas.flowable.util.TriggerUtil;
import com.yunzhupaas.workflow.service.TriggerApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类的描述
 *
 * @author YUNZHUPAASYUNZHUPAAS开发组
 * @version 5.0.x
 * @since 2024/9/11 10:39
 */
@Tag(name = "流程触发", description = "trigger")
@RestController
@RequestMapping("/api/workflow/trigger")
@Slf4j
public class TriggerController implements TriggerApi {
    @Autowired
    private TriggerUtil triggerUtil;
    @Autowired
    private TemplateNodeService templateNodeService;
    @Autowired
    private TemplateJsonService templateJsonService;

    /**
     * 任务流程触发
     *
     * @param model 参数
     */
    @PostMapping("/Execute")
    public ActionResult execute(@RequestBody TriggerModel model) throws Exception {
        for (TriggerDataModel dataModel : model.getDataList()) {
            try {
                triggerUtil.handleTrigger(dataModel, model.getUserInfo());
            } catch (Exception e) {
                log.error("触发异常", e);
                // triggerUtil.createErrorRecord();
            }
        }
        return ActionResult.success();
    }

    /**
     * 定时触发
     *
     * @param triggerModel 参数
     */
    @PostMapping("/TimeExecute")
    public ActionResult timeExecute(@RequestBody TriggerModel triggerModel) {
        try {
            triggerUtil.handleTimeTrigger(triggerModel);
        } catch (Exception e) {
            log.error("定时触发异常", e);
            // triggerUtil.createErrorRecord();
        }
        return ActionResult.success();
    }

    /**
     * 通知触发
     *
     * @param triggerModel 参数
     */
    @PostMapping("/MsgExecute")
    public ActionResult msgExecute(@RequestBody TriggerModel triggerModel) {
        String msgId = triggerModel.getId();
        UserInfo userInfo = triggerModel.getUserInfo();

        QueryWrapper<TemplateNodeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateNodeEntity::getNodeType, NodeEnum.noticeTrigger.getType())
                .eq(TemplateNodeEntity::getFormId, msgId);
        List<TemplateNodeEntity> triggerNodeList = templateNodeService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(triggerNodeList)) {
            List<String> flowIds = triggerNodeList.stream().map(TemplateNodeEntity::getFlowId).distinct()
                    .collect(Collectors.toList());

            QueryWrapper<TemplateJsonEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(TemplateJsonEntity::getState, 1).in(TemplateJsonEntity::getId, flowIds);
            List<TemplateJsonEntity> jsonEntityList = templateJsonService.list(wrapper);

            for (TemplateNodeEntity triggerNode : triggerNodeList) {
                String flowId = triggerNode.getFlowId();
                TemplateJsonEntity jsonEntity = jsonEntityList.stream()
                        .filter(e -> ObjectUtil.equals(e.getId(), flowId)).findFirst().orElse(null);
                if (null == jsonEntity) {
                    continue;
                }
                try {
                    triggerUtil.msgTrigger(triggerNode, userInfo);
                } catch (Exception e) {
                    log.error("通知触发异常", e);
                    // triggerUtil.createErrorRecord();
                }
            }
        }
        return ActionResult.success();
    }

    @Override
    public List<TriggerDataModel> getTriggerDataModel(TriggerDataFo fo) {
        return triggerUtil.getTriggerDataModel(fo);
    }
}
