package com.eleadmin.oa.server.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eleadmin.common.core.exception.BusinessException;
import com.eleadmin.common.system.entity.Role;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.common.system.entity.UserRole;
import com.eleadmin.common.system.param.UserImportParam;
import com.eleadmin.common.system.service.RoleService;
import com.eleadmin.common.system.service.UserRoleService;
import com.eleadmin.common.system.service.UserService;
import com.eleadmin.oa.entity.AssetsData;
import com.eleadmin.oa.entity.Tenant;
import com.eleadmin.oa.mapper.TenantMapper;
import com.eleadmin.oa.server.TenantService;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

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

/**
 * 租户Service实现
 *
 * @author gxwebsoft.com
 * @since 2020-03-14 11:29:03
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
    @Resource
    private TenantService tenantService;

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private UserRoleService userRoleService;

    @Transactional(rollbackFor = {Exception.class}, isolation = Isolation.SERIALIZABLE)
    @Override
    public boolean saveTenant(Tenant tenant) {
      boolean result = baseMapper.insert(tenant) > 0;
      if (result) {
        // 添加用户
        User user = new User();
        user.setTenantId(tenant.getTenantId());
        user.setUsername("admin");
        user.setNickname("admin");
        user.setPassword(userService.encodePassword("gxwebsoft.com"));
        boolean resUser = userService.save(user);
        if(!resUser){
          throw new BusinessException("租户添加失败");
        }
        // 添加角色
        Role role = new Role();
        role.setTenantId(tenant.getTenantId());
        role.setRoleName("管理员");
        role.setRoleCode("admin");
        role.setComments("管理员");
        boolean resRole = roleService.save(role);
        if(!resRole){
          throw new BusinessException("租户添加失败");
        }
      }
      return result;
    }

}
