package cn.stylefeng.workflow.instance.modular.task.strategy.samesubmit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.roses.kernel.sys.api.OrgApproverServiceApi;
import cn.stylefeng.roses.kernel.sys.api.enums.org.DetectModeEnum;
import cn.stylefeng.roses.kernel.sys.api.enums.org.OrgApproverTypeEnum;
import cn.stylefeng.workflow.api.entity.task.RuTask;
import cn.stylefeng.workflow.api.enums.TaskStatusEnum;
import cn.stylefeng.workflow.api.enums.strategy.SamePersonApprovalPolicyEnum;
import cn.stylefeng.workflow.api.util.WorkFlowStatusUtil;
import cn.stylefeng.workflow.instance.modular.task.strategy.samesubmit.base.SameSubmitRule;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SameSubmitTurnLeaderRule extends SameSubmitRule {

    @Resource
    private OrgApproverServiceApi orgApproverServiceApi;

    @Override
    public SamePersonApprovalPolicyEnum getSameSubmitRuleType() {
        return SamePersonApprovalPolicyEnum.TURN_TO_LEADER;
    }

    @Override
    public RuTask processTask(RuTask originTask, Long applicantUserId, Long applicantOrgId) {

        originTask.setTaskStatus(TaskStatusEnum.TRANSFERRED.getCode());

        List<Long> userMainOrgApprover = orgApproverServiceApi.getDeptOrgApprover(applicantOrgId, OrgApproverTypeEnum.FZR.getCode(), 0, DetectModeEnum.TO_TOP);

        if (ObjectUtil.isEmpty(userMainOrgApprover)) {
            return null;
        }

        Long appointUserId = userMainOrgApprover.get(0);

        RuTask turnTask = new RuTask();
        BeanUtil.copyProperties(originTask, turnTask);
        turnTask.setTaskId(IdWorker.getId());
        turnTask.setApprover(appointUserId);

        WorkFlowStatusUtil.initTaskStatus(turnTask, originTask.getTaskType());

        return turnTask;
    }

}
