package tech.easyflow.admin.controller.ai;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.ai.entity.WorkflowExecResult;
import tech.easyflow.ai.entity.WorkflowExecStep;
import tech.easyflow.ai.service.WorkflowExecResultService;
import tech.easyflow.ai.service.WorkflowExecStepService;
import tech.easyflow.ai.utils.WorkFlowUtil;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.controller.BaseCurdController;

import javax.annotation.Resource;
import java.math.BigInteger;

/**
 * 工作流执行记录
 */
@RestController
@RequestMapping("/api/v1/workflowExecResult")
@UsePermission(moduleName = "/api/v1/workflow")
public class WorkflowExecResultController extends BaseCurdController<WorkflowExecResultService, WorkflowExecResult> {

    @Resource
    private WorkflowExecStepService recordStepService;

    public WorkflowExecResultController(WorkflowExecResultService service) {
        super(service);
    }

    @GetMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    @SaCheckPermission("/api/v1/workflow/remove")
    public Result<Void> del(BigInteger id) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        WorkflowExecResult record = service.getById(id);
        if (!account.getId().toString().equals(record.getCreatedBy())) {
            return Result.fail(1, "非法请求");
        }
        service.removeById(id);
        QueryWrapper w = QueryWrapper.create();
        w.eq(WorkflowExecStep::getRecordId, id);
        recordStepService.remove(w);
        return Result.ok();
    }

    @Override
    protected Page<WorkflowExecResult> queryPage(Page<WorkflowExecResult> page, QueryWrapper queryWrapper) {
        queryWrapper.eq(WorkflowExecResult::getCreatedBy, SaTokenUtil.getLoginAccount().getId().toString());
        Page<WorkflowExecResult> res = super.queryPage(page, queryWrapper);
        for (WorkflowExecResult record : res.getRecords()) {
            record.setWorkflowJson(WorkFlowUtil.removeSensitiveInfo(record.getWorkflowJson()));
        }
        return res;
    }
}