package com.ruoyi.web.work.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.work.domain.Company;
import com.ruoyi.web.work.mapper.CompanyMapper;
import com.ruoyi.web.work.service.ICompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.rmi.ServerException;
import java.util.List;

/**
 * @author lsw
 * @date 2024-04-16
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements ICompanyService {
    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private ISysUserService userService;

    @Override
    public List<Company> selectList(Company company) {
        return companyMapper.selectList(company);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult add(Company company) throws ServerException {
        Company bean = companyMapper.selectByCompanyName(company.getCompanyName());
        if (bean != null) {
            return AjaxResult.error("该企业已存在");
        }
        company.setMoney(BigDecimal.ZERO);
        company.setState(0);
        save(company);
        SysUser user = new SysUser();
        user.setUserName(company.getUserName());
        user.setPassword(company.getPassword());
        user.setRoleIds(new Long[]{2l});
        user.setType(1);
        user.setNickName(company.getDirector());
        user.setCompanyId(company.getId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            throw new ServerException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        userService.insertUser(user);
        return AjaxResult.success();
    }
}
