package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysTenant;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysTenantMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * All rights Reserved, Designed By www.sunseagear.com
 *
 * @version V1.0
 * @package sys
 * @title: 租户管理控制器
 * @description: 租户管理控制器
 * @author: 未知
 * @date: 2019-11-28 06:24:52
 * @copyright: www.sunseagear.com Inc. All rights reserved.
 */
@Transactional
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean save(SysTenant entity) {
        entity.setTenantId(StringUtils.randomNumber(8));
        SysDept dept = new SysDept();
        dept.setDeptName(entity.getName());
        dept.setTenantId(entity.getTenantId());
        sysDeptService.insertDept(dept);
        SysUser user = new SysUser();
        user.setUserName(entity.getUserName());
        user.setNickName(entity.getName());
        user.setPhonenumber(entity.getPhone());
        user.setDeptId(dept.getDeptId());
        user.setTenantId(entity.getTenantId());
        user.setPassword(SecurityUtils.encryptPassword(entity.getTenantId()));
        sysUserService.insertUser(user);
        Long[] roleIds = {2L};
        sysUserService.insertUserAuth(user.getUserId(), roleIds);
        entity.setUserId(user.getUserId());
        return super.save(entity);
    }
}
