package com.qiaoba.module.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.qiaoba.api.system.entity.dto.SysUserDto;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.common.base.util.ObjectUtil;
import com.qiaoba.module.system.service.SysUserImportService;
import com.qiaoba.module.system.service.SysUserService;
import com.qiaoba.module.system.templates.SysUserImport;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 用户导入 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/18 14:50
 */
@Service
@RequiredArgsConstructor
public class SysUserImportServiceImpl implements SysUserImportService {

    private final SysUserService sysUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer importUser(List<SysUserImport> users) {
        Integer success = 0;

        for (SysUserImport importUser : users) {
            if (!ObjectUtil.isAllFieldNull(importUser)) {
                // 校验数据
                checkParams(importUser);
                sysUserService.saveOrUpdate(createUserDto(importUser), false);
                success++;
            }
        }

        return success;
    }

    private SysUserDto createUserDto(SysUserImport importUser) {
        SysUserDto dto = BeanUtil.copyProperties(importUser, SysUserDto.class);
        if (StrUtil.isNotBlank(importUser.getRole())) {
            String[] roleArr = importUser.getRole().split(BaseConstant.DEFAULT_SPLIT_STR);
            dto.setRoleIds(Arrays.stream(roleArr).collect(Collectors.toSet()));
        }
        if (StrUtil.isNotBlank(importUser.getPost())) {
            String[] postArr = importUser.getPost().split(BaseConstant.DEFAULT_SPLIT_STR);
            dto.setPostIds(Arrays.stream(postArr).collect(Collectors.toSet()));
        }
        return dto;
    }

    private void checkParams(SysUserImport importUser) {
        if (StrUtil.isBlank(importUser.getUsername())) {
            throw new ServiceException("登录账号不能为空");
        }
        if (StrUtil.isBlank(importUser.getPassword())) {
            throw new ServiceException("登录密码不能为空");
        }
        if (StrUtil.isBlank(importUser.getNickname())) {
            throw new ServiceException("用户姓名不能为空");
        }
        if (StrUtil.isBlank(importUser.getRole())) {
            throw new ServiceException("用户角色不能为空");
        }
        if (StrUtil.isBlank(importUser.getStatus())) {
            throw new ServiceException("用户状态不能为空");
        }
    }
}
