package cn.axzo.workflow.server.xxljob;

import cn.axzo.framework.jackson.utility.JSON;
import cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum;
import cn.axzo.workflow.common.model.request.bpmn.task.ExtHiTaskSearchDTO;
import cn.axzo.workflow.core.repository.entity.ExtAxHiTaskInst;
import cn.axzo.workflow.core.repository.mapper.CommonMapper;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.APPROVED;

/**
 * 操作数据表
 *
 * @author wangli
 * @since 2024/4/28 14:06
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OperationDataJobHandler extends IJobHandler {
    @Resource
    private CommonMapper commonMapper;
    @Resource
    private ExtAxHiTaskInstService extAxHiTaskInstService;

    @Override
    @XxlJob("executeDynamicSql")
    public ReturnT<String> execute(String s) throws Exception {
        if (StringUtils.hasText(s)) {
            XxlJobLogger.log("执行动态 sql");
            List<Map<String, Object>> maps = commonMapper.executeDynamicSQL(s);
            XxlJobLogger.log("result: {}", JSON.toJSONString(maps));
        } else {
            XxlJobLogger.log("仅修复 extAxTaskInst 表数据");
            repairData();
        }
        return ReturnT.SUCCESS;
    }

    private void repairData() {
        ExtHiTaskSearchDTO searchDTO = new ExtHiTaskSearchDTO();
        searchDTO.setTaskDefinitionKey("NODE_STARTER");
        searchDTO.setStatus(BpmnProcessInstanceResultEnum.PROCESSING);
        List<ExtAxHiTaskInst> extAxHiTaskInsts = extAxHiTaskInstService.queryList(searchDTO);
        if (!CollectionUtils.isEmpty(extAxHiTaskInsts)) {
            extAxHiTaskInsts.forEach(i -> {
                i.setStatus(APPROVED.getStatus());
                extAxHiTaskInstService.update(i);
            });
        }
    }
}
