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.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.work.domain.Company;
import com.ruoyi.web.work.domain.dto.LockDto;
import com.ruoyi.web.work.domain.vo.CompanyListVo;
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;

    @Autowired
    private SysPermissionService permissionService;


    @Override
    public Company selectCompanyById(Long id) {
        return companyMapper.selectCompanyById(id);
    }

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

    @Override
    public List<CompanyListVo> selectCompanyList(Company company) {
        return companyMapper.selectCompanyList(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);
        if (!save(company)) {
            throw new ServerException("新增企业失败,请联系管理员");
        }
        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.setPhonenumber(company.getPhone());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
            throw new ServerException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (userService.insertUser(user) == 0) {
            throw new ServerException("新增用户失败,请联系管理员");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult edit(Company company) throws ServerException {
        company.setMoney(null);
        if (!updateById(company)) {
            throw new ServerException("编辑企业失败,请联系管理员");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult lock(LockDto dto) throws ServerException {
        Company company = new Company();
        company.setId(dto.getId());
        company.setState(dto.getState());
        if (!updateById(company)) {
            throw new ServerException("锁定/解锁企业失败,请联系管理员");
        }
        //更新企业旗下用户权限
        SysUser user = new SysUser();
        user.setCompanyId(company.getId());
        List<SysUser> list = userService.selectUserList(user);
        list.forEach(e -> {
            e.setStatus(dto.getState().toString());
            if (userService.updateUser(e) > 0) {
                permissionService.refreshUserPermission(e.getUserId());
            }
        });
        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult remove(Long id) throws ServerException {
        if (!removeById(id)) {
            throw new ServerException("删除企业失败,请联系管理员");
        }
        SysUser user = new SysUser();
        user.setCompanyId(id);
        List<SysUser> list = userService.selectUserList(user);
        list.forEach(e -> {
            if (userService.deleteUserById(e.getUserId()) == 0) {
                throw new RuntimeException("删除企业失败,请联系管理员");
            }
            permissionService.refreshUserPermission(e.getUserId());
        });
        return AjaxResult.success();
    }
}
