package com.izouma.jiashanxia.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.izouma.jiashanxia.domain.Company;
import com.izouma.jiashanxia.domain.User;
import com.izouma.jiashanxia.dto.PageQuery;
import com.izouma.jiashanxia.enums.AuthorityName;
import com.izouma.jiashanxia.exception.BusinessException;
import com.izouma.jiashanxia.repo.CompanyRepo;
import com.izouma.jiashanxia.repo.UserRepo;
import com.izouma.jiashanxia.security.Authority;
import com.izouma.jiashanxia.utils.JpaUtils;
import com.izouma.jiashanxia.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@AllArgsConstructor
public class CompanyService {

    private CompanyRepo companyRepo;
    private UserRepo    userRepo;

    public Page<Company> all(PageQuery pageQuery, User user) {
        pageQuery.setSort("createdAt,desc");
        Set<Authority> authorities = user.getAuthorities();
        if (!authorities.contains(Authority.get(AuthorityName.ROLE_ADMIN)) && authorities.contains(Authority.get(AuthorityName.ROLE_CREATOR))) {
            Map<String, Object> query = pageQuery.getQuery();
            query.put("userId", user.getId());
        }
        return companyRepo.findAll(JpaUtils.toSpecification(pageQuery, Company.class), JpaUtils.toPageRequest(pageQuery));
    }

    /*
    添加员工
    */
    public void addUser(Long userId, Long companyId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));
        user.setCompanyId(companyId);
        userRepo.save(user);
    }

    /*
    删除员工
     */
    public void removeUser(Long userId, Long companyId) {
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));
        if (companyId.equals(user.getCompanyId())) {
            user.setCompanyId(null);
            userRepo.save(user);
        }
    }

    /*
    员工列表
     */
    public List<User> employee(Long userId) {
        Company company = companyRepo.findByUserId(userId);
        if (ObjectUtil.isEmpty(company)) {
            return null;
        }
        return userRepo.findAllByCompanyIdAndDelFalse(company.getId());
    }

    /*
    批量增加员工
     */
    public void batchEmployee(List<Long> employee, Long companyId) {
        List<User> employees = userRepo.findAllById(employee);
        employees.forEach(yee -> {
            if (yee.getCompanyId() == null || !yee.getCompanyId().equals(companyId)) {
                yee.setCompanyId(companyId);
                userRepo.save(yee);
            }
        });
    }

    /*
    新建企业
     */
    public Company save(Company record) {
        // 团队权限
        Authority creator = Authority.get(AuthorityName.ROLE_CREATOR);
        // 修改
        if (record.getId() != null) {
            Company orig = companyRepo.findById(record.getId()).orElseThrow(new BusinessException("无记录"));
            // 更换团队管理人
            if (!record.getUserId().equals(orig.getUserId())) {
                userRepo.findById(orig.getUserId()).ifPresent(user1 -> {
                    user1.setTeamFounder(false);
                    Set<Authority> authorities1 = user1.getAuthorities();
                    authorities1.remove(creator);
                    userRepo.save(user1);
                });
                // 新团队管理人增加权限
                this.teamFounder(record.getUserId(), creator, record.getId());
            }
            ObjUtils.merge(orig, record);
            List<Long> employee = record.getEmployee();
            // 员工加入团队
            if (CollUtil.isNotEmpty(employee)) {
                this.batchEmployee(record.getEmployee(), record.getId());
            }
            return companyRepo.save(orig);
        }

        // 增加
        Company save = companyRepo.save(record);
        this.teamFounder(save.getUserId(), creator, save.getId());
        return save;
    }

    /*
    修改团队权限
     */
    public void teamFounder(Long userId, Authority creator, Long companyId) {
        // 新团队管理人增加权限
        User user = userRepo.findById(userId).orElseThrow(new BusinessException("无用户"));
        Set<Authority> authorities = user.getAuthorities();
        if (!authorities.contains(creator) || !user.getTeamFounder()) {
            authorities.add(creator);
            user.setTeamFounder(true);
            user.setCompanyId(companyId);
            userRepo.save(user);
        }
    }

}
