package com.bonus.material.approval.service.impl;

import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.approval.domain.ApprovalInstance;
import com.bonus.material.approval.domain.ApprovalRecord;
import com.bonus.material.approval.mapper.ApprovalInstanceMapper;
import com.bonus.material.approval.mapper.ApprovalRecordMapper;
import com.bonus.material.approval.service.IApprovalInstanceService;
import com.bonus.system.api.domain.SysRole;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 审批实例服务实现
 * 
 * @author bonus
 * @date 2024-11-18
 */
@Service
public class ApprovalInstanceServiceImpl implements IApprovalInstanceService {

    @Resource
    private ApprovalInstanceMapper instanceMapper;

    @Resource
    private ApprovalRecordMapper recordMapper;

    @Override
    public List<ApprovalInstance> selectInstanceList(ApprovalInstance instance) {
        return instanceMapper.selectInstanceList(instance);
    }

    @Override
    public ApprovalInstance selectInstanceById(Long id) {
        ApprovalInstance instance = instanceMapper.selectInstanceById(id);
        if (instance != null) {
            // 查询审批记录
            List<ApprovalRecord> recordList = recordMapper.selectRecordListByInstanceId(id);
            instance.setRecordList(recordList);
        }
        return instance;
    }

    @Override
    public ApprovalInstance selectInstanceByBusiness(String businessType, String businessId) {
        return instanceMapper.selectInstanceByBusiness(businessType, businessId);
    }

    @Override
    public List<ApprovalInstance> selectMyTodoList() {
        Long userId = SecurityUtils.getUserId();
        List<Long> roleIds = SecurityUtils.getLoginUser().getSysUser().getRoles()
                .stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());
        return instanceMapper.selectMyTodoList(userId, roleIds);
    }

    @Override
    public List<ApprovalInstance> selectMyDoneList() {
        Long userId = SecurityUtils.getUserId();
        return instanceMapper.selectMyDoneList(userId);
    }

    @Override
    public int insertInstance(ApprovalInstance instance) {
        return instanceMapper.insertInstance(instance);
    }

    @Override
    public int updateInstance(ApprovalInstance instance) {
        return instanceMapper.updateInstance(instance);
    }

    @Override
    public int deleteInstanceById(Long id) {
        // 删除审批记录
        recordMapper.deleteRecordByInstanceId(id);
        // 删除实例
        return instanceMapper.deleteInstanceById(id);
    }
}

