package com.xdap.self_development.service.impl;


import com.xdap.api.moudle.department.pojo.entity.XdapDepartments;
import com.xdap.api.moudle.department.pojo.entity.XdapDeptUsers;
import com.xdap.api.moudle.user.pojo.XdapUsers;
import com.xdap.self_development.common.BusinessDatabase;
import com.xdap.self_development.domain.view.UserInfoView;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.XdapDeptUsersService;
import groovy.util.logging.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * XDAP部门用户服务实现类
 *
 * @version 1.0
 * @since 2025
 */
@Slf4j
@Service
public class XdapDeptUsersServiceImpl implements XdapDeptUsersService {

    private static final Logger log = Logger.getLogger(XdapDeptUsersServiceImpl.class);

    @Resource
    private BusinessDatabase bd;

    /**
     * 根据ID查询部门
     *
     * @param deptId 部门ID
     * @return 部门对象
     */
    @Override
    public XdapDepartments selectDeptByID(String deptId) {
        if (ObjectUtils.isEmpty(deptId)) {
            return null;
        }
        List<XdapDepartments> departmentsPojos = bd.getSystemDatabase()
                .eq("id", deptId)
                .doQuery(XdapDepartments.class);
        if (ObjectUtils.isNotEmpty(departmentsPojos)) {
            return departmentsPojos.get(0);
        }
        return null;
    }

    /**
     * 根据名称查询部门
     *
     * @param deptName 部门名称
     * @return 部门对象
     */
    @Override
    public XdapDepartments selectDeptByName(String deptName) {
        if (ObjectUtils.isEmpty(deptName)) {
            return null;
        }
        List<XdapDepartments> departmentsPojos = bd.getSystemDatabase()
                .eq("name", deptName)
                .doQuery(XdapDepartments.class);
        if (ObjectUtils.isNotEmpty(departmentsPojos)) {
            return departmentsPojos.get(0);
        }
        return null;
    }

    /**
     * 根据部门名称查询用户
     *
     * @param deptName 部门名称
     * @return 用户列表
     */
    @Override
    public List<XdapUsers> selectUserByName(String deptName) {
        XdapDepartments xdapDepartmentsPojo = selectDeptByName(deptName);
        List<XdapUsers> xdapUsersPojos = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(xdapDepartmentsPojo)) {
            List<XdapDeptUsers> xdapDeptUsersPojos = bd.getSystemDatabase()
                    .eq("department_id", xdapDepartmentsPojo.getId())
                    .doQuery(XdapDeptUsers.class);
            if (ObjectUtils.isNotEmpty(xdapDeptUsersPojos)) {
                for (XdapDeptUsers xdapDeptUsersPojo : xdapDeptUsersPojos) {
                    List<XdapUsers> usersPojos = bd.getSystemDatabase()
                            .eq("id", xdapDeptUsersPojo.getUserId())
                            .doQuery(XdapUsers.class);
                    if (ObjectUtils.isNotEmpty(usersPojos)) {
                        xdapUsersPojos.add(usersPojos.get(0));
                    }
                }
            }
        }else {
            log.warn("无部门数据");
        }

        return xdapUsersPojos;
    }

    /**
     * 根据人员姓名查询用户
     *
     * @param personName 人员姓名
     * @return 用户列表
     */
    @Override
    public List<XdapUsers> selectUserByPersonName(String personName) {
        if (ObjectUtils.isEmpty(personName)) {
            return Collections.emptyList();
        }
        return bd.getSystemDatabase()
                .eq("username", personName)
                .doQuery(XdapUsers.class);
    }

    /**
     * 根据用户列表和部门名称查询用户
     *
     * @param xdapUsersPojos 用户对象列表
     * @param dpName 部门对象
     * @return 匹配的用户对象
     */
    @Override
    public XdapUsers selectUserByUserListAndDeptName(List<XdapUsers> xdapUsersPojos, XdapDepartments dpName) {

        if (ObjectUtils.isNotEmpty(xdapUsersPojos) && ObjectUtils.isNotEmpty(dpName)) {
            //提取用户ID集合
            List<String> idList = xdapUsersPojos.stream().map(XdapUsers::getId).collect(Collectors.toList());
            //根据用户ID查找对应关系表
            List<XdapDeptUsers> departmentsPojos = bd.getSystemDatabase()
                    .in("user_id", idList)
                    .doQuery(XdapDeptUsers.class);
            //关系表筛选部门
            List<XdapDeptUsers> collect = departmentsPojos.stream().filter(x -> x.getDepartmentId().equals(dpName.getId())).collect(Collectors.toList());
            //筛选完成后查到对应的人员
            if (ObjectUtils.isNotEmpty(collect)) {
                String userId = collect.get(0).getUserId();
                List<XdapUsers> usersPojo = bd.getSystemDatabase()
                        .eq("id", userId)
                        .doQuery(XdapUsers.class);
              if (ObjectUtils.isNotEmpty(usersPojo)) {
                  return usersPojo.get(0);
              }

            }
        }
        return null;
    }


    /**
     * 根据ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象
     */
    @Override
    public XdapUsers selectUserByID(String userId) {

        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        List<XdapUsers> userPojos = bd.getSystemDatabase()
                .eq("id", userId)
                .doQuery(XdapUsers.class);
        if (ObjectUtils.isNotEmpty(userPojos)) {
            return userPojos.get(0);
        }
        return null;
    }

    /**
     * 根据用户编码查询用户
     *
     * @param userCode 用户编码
     * @return 用户对象
     */
    @Override
    public XdapUsers selectUserByCode(String userCode) {

        if (ObjectUtils.isEmpty(userCode)) {
            return null;
        }
        List<XdapUsers> userPojos = bd.getSystemDatabase()
                .eq("user_number", userCode)
                .doQuery(XdapUsers.class);
        if (ObjectUtils.isNotEmpty(userPojos)) {
            return userPojos.get(0);
        }
        return null;
    }

    @Override
    public UserInfoView getUserInfo(String userId) {
        UserInfoView userInfoView = new UserInfoView();
        XdapUsers user = bd.getSystemDatabase()
                .eq("id", userId)
                .doQueryFirst(XdapUsers.class);
        if (user == null) {
            throw new CommonException("找不到当前用户");
        }
        userInfoView.setUsername(user.getUsername());
        List<XdapDeptUsers> depts = bd.getSystemDatabase()
                .eq("user_id", user.getId())
                .doQuery(XdapDeptUsers.class);
        XdapDepartments commonDept = bd.getSystemDatabase()
                .eq("name", "研发总院")
                .doQueryFirst(XdapDepartments.class);
        if (depts.isEmpty() || commonDept == null) {
            return userInfoView;
        }
        List<String> deptIds = depts.stream().map(XdapDeptUsers::getDepartmentId).collect(Collectors.toList());
        List<XdapDepartments> xdapDepartments = bd.getSystemDatabase()
                .in("id", deptIds)
                .eq("parent_id", commonDept.getId())
                .doQuery(XdapDepartments.class);
        if (xdapDepartments.isEmpty()) {
            userInfoView.setDepartments(new ArrayList<>());
            return userInfoView;
        }
        List<String> deptNames = xdapDepartments.stream().map(XdapDepartments::getName).collect(Collectors.toList());
        userInfoView.setDepartments(deptNames);
        return userInfoView;
    }

    @Override
    public List<XdapUsers> selectUserByIds(Set<String> userIds) {
        List<XdapUsers> users = bd.getSystemDatabase()
                .in("id", userIds)
                .doQuery(XdapUsers.class);
        if (users.isEmpty()) {
            return Collections.emptyList();
        } else {
            return users;
        }
    }
}
