package com.ads.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.ads.business.dao.TypeRoleDao;
import com.ads.business.entity.DocType;
import com.ads.business.entity.TypeRole;
import com.ads.business.service.ApiUserService;
import com.ads.business.service.TypeRoleService;
import com.ads.common.dingTalk.domain.UserDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hou
 * @since 2021-10-21
 */
@Service
@Slf4j
public class TypeRoleServiceImpl extends ServiceImpl<TypeRoleDao, TypeRole> implements TypeRoleService {

    @Resource
    private TypeRoleDao typeRoleDao;

    @Resource
    private ApiUserService apiUserService;

    @Override
    @Async
    public void insertAsync(List<String> role, DocType docType) {
        ArrayList<TypeRole> typeRoles = new ArrayList<>();
        List<UserDTO> userDTOS = apiUserService.allUsers();
        if (CollectionUtil.isEmpty(userDTOS)){
            log.info("钉钉用户不存在");
            return;
        }
        List<String> collect = userDTOS.stream().map(UserDTO::getMobile).distinct().collect(Collectors.toList());
        if (CollectionUtil.isEmpty(collect)){
            log.info("钉钉用户手机号为空");
            return;
        }
        role.stream().distinct().forEach(e -> {
            if (collect.contains(e)){
                TypeRole typeRole = new TypeRole();
                typeRole.setTypeId(docType.getTypeId());
                typeRole.setMobile(e);
                typeRoles.add(typeRole);
            }
        });
        if (CollectionUtil.isEmpty(typeRoles)){
            return;
        }
        typeRoleDao.insertBatch(typeRoles);
    }

    @Override
    public List<TypeRole> getMobileList(Long typeId) {
        return typeRoleDao.getMobileList(typeId);
    }
}
