package com.hotwj.platform.flow.controller;

import com.hotwj.platform.flow.domain.SysFlowTask;
import com.hotwj.platform.flow.domain.SysFlowTaskHis;
import com.hotwj.platform.flow.service.ISysFlowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 流程通用接口
 *
 * @author shihongwei
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/flow")
@Tag(name = "通用流程接口", description = "通用流程管理")
public class SysFlowController {

    private final ISysFlowService flowService;

    @GetMapping("/todo")
    @Operation(summary = "获取我的待办")
    public TableDataInfo<SysFlowTask> getTodo(PageQuery pageQuery, String isRead) {
        String userId = LoginHelper.getBusinessUserId();
        if (userId == null) {
            userId = String.valueOf(LoginHelper.getUserId());
        }
        return flowService.getTodoList(userId, pageQuery, isRead);
    }

    @GetMapping("/todo/enterprise")
    @Operation(summary = "获取企业待办")
    public TableDataInfo<SysFlowTask> getEnterpriseTodo(PageQuery pageQuery) {
        return flowService.getEnterpriseTodoList(getCompanyId(), pageQuery);
    }

    @PostMapping("/read/{taskId}")
    @Operation(summary = "标记已读")
    public R<Void> read(@PathVariable String taskId) {
        String userId = LoginHelper.getBusinessUserId();
        if (userId == null) {
            userId = String.valueOf(LoginHelper.getUserId());
        }
        flowService.readTask(taskId, userId);
        return R.ok();
    }

    @GetMapping("/history/{instanceId}")
    @Operation(summary = "获取审批历史")
    public R<List<SysFlowTaskHis>> getHistory(@PathVariable String instanceId) {
        return R.ok(flowService.getHistory(instanceId));
    }

    @PostMapping("/audit")
    @Operation(summary = "审批任务")
    public R<Void> audit(@RequestBody AuditBody body) {
        String userId = LoginHelper.getBusinessUserId();
        if (userId == null) {
            userId = String.valueOf(LoginHelper.getUserId());
        }
        flowService.audit(body.getTaskId(), body.isPass(), body.getComment(), userId);
        return R.ok();
    }

    // 辅助方法获取 CompanyId
    private Long getCompanyId() {
        try {
            return LoginHelper.getLoginUser().getCompanyId();
        } catch (Exception e) {
            return 0L;
        }
    }

    @Data
    public static class AuditBody {
        private String taskId;
        private boolean pass;
        private String comment;
    }
}
