package com.fs.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.fs.app.param.ChangeUserDeptAndPostParam;
import com.fs.app.service.IAppService;
import com.fs.app.vo.CompanyRoleVO;
import com.fs.app.vo.UserPostVO;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.*;
import com.fs.company.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class AppServiceImpl implements IAppService {

    private final ICompanyUserService companyUserService;
    private final ICompanyDeptService companyDeptService;
    private final ICompanyPostService companyPostService;
    private final ICompanyUserPostService companyUserPostService;
    private final ICompanyRoleService companyRoleService;
    private final ICompanyUserRoleService companyUserRoleService;


    @Override
    public void changeUserDeptAndPost(ChangeUserDeptAndPostParam param) {
        log.debug("change user dept and post param: {}", JSON.toJSONString(param));
        Set<Long> companyUserIds = Arrays.stream(param.getCompanyUserIds().split(",")).map(Long::new).collect(Collectors.toSet());

        List<CompanyUser> companyUsers = companyUserService.selectCompanyUserByIds(companyUserIds);
        if (Objects.isNull(companyUsers) || companyUsers.isEmpty()) {
            throw new CustomException("销售不存在");
        }

        // 修改部门
        if (Objects.nonNull(param.getDeptId())) {
            CompanyDept companyDept = companyDeptService.selectCompanyDeptById(param.getDeptId());
            if (Objects.isNull(companyDept)) {
                throw new CustomException("部门不存在");
            }

            companyUsers.forEach(companyUser -> {
                companyUser.setDeptId(param.getDeptId());
                companyUserService.updateCompanyUser(companyUser);
            });
        }

        // 修改岗位
        if (StringUtils.isNotBlank(param.getPostIds())) {
            List<Long> postIds = Arrays.stream(param.getPostIds().split(",")).map(Long::new).collect(Collectors.toList());
            List<CompanyPost> companyPosts =  companyPostService.selectCompanyPostByIds(postIds);
            if (Objects.nonNull(companyPosts) && !companyPosts.isEmpty()) {
                companyUsers.forEach(companyUser -> {
                    companyUserPostService.deleteCompanyUserPostById(companyUser.getUserId());
                    companyUserPostService.batchInsertCompanyUserPost(companyPosts.stream().map(p -> {
                        CompanyUserPost companyUserPost = new CompanyUserPost();
                        companyUserPost.setPostId(p.getPostId());
                        companyUserPost.setUserId(companyUser.getUserId());
                        return companyUserPost;
                    }).collect(Collectors.toList()));
                });
            }
        }

        // 修改角色
        if (StringUtils.isNotBlank(param.getRoleIds())) {
            List<Long> roleIds = Arrays.stream(param.getRoleIds().split(",")).map(Long::new).collect(Collectors.toList());
            List<CompanyRole> CompanyRoles =  companyRoleService.selectCompanyRoleByIds(roleIds);
            if (Objects.nonNull(CompanyRoles) && !CompanyRoles.isEmpty()) {
                companyUsers.forEach(companyUser -> {
                    companyUserRoleService.deleteCompanyUserRoleById(companyUser.getUserId());
                    companyUserRoleService.batchInsertCompanyUserRole(CompanyRoles.stream().map(p -> {
                        CompanyUserRole companyUserRole = new CompanyUserRole();
                        companyUserRole.setRoleId(p.getRoleId());
                        companyUserRole.setUserId(companyUser.getUserId());
                        return companyUserRole;
                    }).collect(Collectors.toList()));
                });
            }
        }
    }

    /**
     * 获取公司部门树
     * @param companyId 公司ID
     * @return  list
     */
    @Override
    public List<CompanyDeptTreeSelect> getDeptTreeSelect(Long companyId) {
        log.debug("getDeptTreeSelect companyId: {}", companyId);
        if (Objects.isNull(companyId)) {
            throw new CustomException("获取companyId失败, 请重新登录");
        }
        CompanyDept dept = new CompanyDept();
        dept.setCompanyId(companyId);
        dept.setStatus("0");
        List<CompanyDept> depts = companyDeptService.selectCompanyDeptList(dept);
        return companyDeptService.buildDeptTreeSelect(depts);
    }

    /**
     * 获取公司岗位列表
     * @param companyId 公司ID
     * @return list
     */
    @Override
    public List<UserPostVO> postList(Long companyId) {
        log.debug("postList companyId: {}", companyId);
        if (Objects.isNull(companyId)) {
            throw new CustomException("获取companyId失败, 请重新登录");
        }
        CompanyPost companyPost = new CompanyPost();
        companyPost.setCompanyId(companyId);
        return companyPostService.selectCompanyPostList(companyPost).stream().map(p -> {
            UserPostVO userPostVO = new UserPostVO();
            userPostVO.setPostId(p.getPostId());
            userPostVO.setPostName(p.getPostName());
            return userPostVO;
        }).collect(Collectors.toList());
    }

    /**
     * 获取公司角色列表
     * @param companyId 公司ID
     * @return  list
     */
    @Override
    public List<CompanyRoleVO> roleList(Long companyId) {
        log.debug("roleList companyId: {}", companyId);
        if (Objects.isNull(companyId)) {
            throw new CustomException("获取companyId失败, 请重新登录");
        }
        CompanyRole companyRole = new CompanyRole();
        companyRole.setCompanyId(companyId);
        companyRole.setStatus("0");
        companyRole.setDelFlag("0");
        return companyRoleService.selectCompanyRoleList(companyRole).stream().map(r -> {
            CompanyRoleVO companyRoleVO = new CompanyRoleVO();
            companyRoleVO.setRoleId(r.getRoleId());
            companyRoleVO.setRoleName(r.getRoleName());
            return companyRoleVO;
        }).collect(Collectors.toList());
    }
}
