package com.yunzhupaas.flowable.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.flowable.entity.LaunchUserEntity;
import com.yunzhupaas.flowable.mapper.LaunchUserMapper;
import com.yunzhupaas.flowable.service.LaunchUserService;
import com.yunzhupaas.flowable.util.ServiceUtil;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.util.RandomUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 类的描述
 *
 * @author YUNZHUPAASYUNZHUPAAS开发组
 * @version 5.0.x
 * @since 2024/4/18 9:46
 */
@Service
public class LaunchUserServiceImpl extends SuperServiceImpl<LaunchUserMapper, LaunchUserEntity>
        implements LaunchUserService {
    @Resource
    private ServiceUtil serviceUtil;

    @Override
    public LaunchUserEntity getInfoByTask(String taskId) {
        QueryWrapper<LaunchUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LaunchUserEntity::getTaskId, taskId);
        return this.getOne(queryWrapper);
    }

    @Override
    public void createLaunchUser(String taskId, String userId) {
        LaunchUserEntity launchUserEntity = this.getInfoByTask(taskId);
        if (null != launchUserEntity) {
            return;
        }
        UserEntity user = serviceUtil.getUserInfo(userId);
        if (null != user) {
            LaunchUserEntity entity = new LaunchUserEntity();
            entity.setId(RandomUtil.uuId());
            entity.setTaskId(taskId);
            entity.setOrganizeId(user.getOrganizeId());
            entity.setPositionId(user.getPositionId());
            entity.setManagerId(user.getManagerId());
            List<UserEntity> list = serviceUtil.getListByManagerId(user.getId());
            String subordinate = list.stream().map(UserEntity::getId).collect(Collectors.joining(","));
            entity.setSubordinate(subordinate);
            entity.setSuperior(user.getManagerId());
            // Department用到时，再递归获取 serviceUtil.getDepartmentAll
            this.save(entity);
        }
    }

    @Override
    public void delete(String taskId) {
        QueryWrapper<LaunchUserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(LaunchUserEntity::getTaskId, taskId);
        List<LaunchUserEntity> list = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            this.removeByIds(list);
        }
    }
}
