package com.ningdatech.pmapi.user.manage;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.pmapi.organization.model.entity.DingEmployeeInfo;
import com.ningdatech.pmapi.organization.model.entity.DingOrganization;
import com.ningdatech.pmapi.organization.service.IDingEmployeeInfoService;
import com.ningdatech.pmapi.organization.service.IDingOrganizationService;
import com.ningdatech.pmapi.sys.model.entity.Role;
import com.ningdatech.pmapi.sys.model.entity.UserRole;
import com.ningdatech.pmapi.sys.service.IRoleService;
import com.ningdatech.pmapi.sys.service.IUserRoleService;
import com.ningdatech.pmapi.user.entity.UserInfo;
import com.ningdatech.pmapi.user.security.auth.model.UserFullInfoDTO;
import com.ningdatech.pmapi.user.service.IUserAuthService;
import com.ningdatech.pmapi.user.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author liuxinxin
 * @date 2023/1/3 上午10:57
 */

@Component
@RequiredArgsConstructor
public class UserAuthLoginManage {

    private final IUserAuthService iUserAuthService;
    private final IUserInfoService iUserInfoService;
    private final IRoleService iRoleService;
    private final IDingOrganizationService iDingOrganizationService;
    private final IDingEmployeeInfoService iDingEmployeeInfoService;
    private final IUserRoleService iUserRoleService;


    /**
     * 根据用户id 获取用户全量信息
     *
     * @param userId
     * @return
     */
    public UserFullInfoDTO getUserFullInfo(Long userId) {
        UserInfo userInfo = iUserInfoService.getById(userId);
        if (Objects.isNull(userInfo)) {
            return null;
        }
        // 返回用户全量信息
        UserFullInfoDTO userFullInfoDTO = new UserFullInfoDTO();
        userFullInfoDTOAssembler(userInfo, userFullInfoDTO);
        return userFullInfoDTO;
    }

    /**
     * 根据用户名获取
     *
     * @param username
     * @return
     */
    public UserFullInfoDTO queryUserInfoInPasswordAuth(String username) {
        // TODO 目前账号密码登陆测试使用 强制用户登录 userId 1L
        UserInfo userInfo = iUserInfoService.getById(username);
        if (Objects.isNull(userInfo)) {
            return null;
        }
        // 返回用户全量信息
        UserFullInfoDTO userFullInfoDTO = new UserFullInfoDTO();
        userFullInfoDTOAssembler(userInfo, userFullInfoDTO);
        return userFullInfoDTO;
    }

    /**
     * 根据手机号获取
     *
     * @param phoneNo
     * @return
     */
    public UserFullInfoDTO queryUserInfoInPhoneNoAuth(String phoneNo) {
        UserInfo userInfo = iUserInfoService.getOne(Wrappers.lambdaQuery(UserInfo.class)
                .eq(UserInfo::getMobile, phoneNo));
        if (Objects.isNull(userInfo)) {
            return null;
        }
        // 返回用户全量信息
        UserFullInfoDTO userFullInfoDTO = new UserFullInfoDTO();
        userFullInfoDTOAssembler(userInfo, userFullInfoDTO);
        return userFullInfoDTO;
    }

    /**
     * 根据accountId(浙政钉扫码登陆)
     *
     * @param accountId
     * @return
     */
    public UserFullInfoDTO queryUserInfoInAccountIdAuth(String accountId) {

        // 获取用户信息
        UserInfo userInfo = iUserInfoService.getOne(Wrappers.lambdaQuery(UserInfo.class)
                .eq(UserInfo::getAccountId, accountId));
        if (Objects.isNull(userInfo)) {
            return null;
        }
        // 返回用户全量信息
        UserFullInfoDTO userFullInfoDTO = new UserFullInfoDTO();
        userFullInfoDTOAssembler(userInfo, userFullInfoDTO);
        return userFullInfoDTO;
    }


    private void userFullInfoDTOAssembler(UserInfo userInfo, UserFullInfoDTO userFullInfoDTO) {
        // 获取浙政钉雇员信息 组织信息
        String employeeCode = userInfo.getEmployeeCode();
        if (StringUtils.isNotBlank(employeeCode)) {
            List<DingEmployeeInfo> dingEmployeeInfoList = iDingEmployeeInfoService
                    .list(Wrappers.lambdaQuery(DingEmployeeInfo.class)
                            .eq(DingEmployeeInfo::getEmployeeCode, employeeCode)
                            .eq(DingEmployeeInfo::getMainJob, "true"));
            DingEmployeeInfo dingEmployeeInfo = dingEmployeeInfoList.get(0);

            String organizationCode = dingEmployeeInfo.getOrganizationCode();
            List<DingOrganization> dingOrganizationList = iDingOrganizationService
                    .list(Wrappers.lambdaQuery(DingOrganization.class)
                            .eq(DingOrganization::getOrganizationCode, organizationCode));
            if (CollectionUtil.isNotEmpty(dingOrganizationList)){
                DingOrganization dingOrganization = dingOrganizationList.get(0);
                userFullInfoDTO.setOrganizationCode(dingOrganization.getOrganizationCode());
                userFullInfoDTO.setOrganizationName(dingOrganization.getOrganizationName());
                userFullInfoDTO.setRegionCode(dingOrganization.getDivisionCode());
            }
        }

        List<Role> roleList = new ArrayList<>();
        // 获取用户角色列表信息
        List<UserRole> userRoleList = iUserRoleService
                .list(Wrappers.lambdaQuery(UserRole.class)
                        .eq(UserRole::getUserId, userInfo.getId()));
        if (CollectionUtil.isNotEmpty(userRoleList)) {
            List<Long> roleIdList = userRoleList.stream()
                    .map(UserRole::getRoleId).distinct()
                    .collect(Collectors.toList());
            roleList = iRoleService.list(Wrappers.lambdaQuery(Role.class).in(Role::getId, roleIdList));
        }
        userFullInfoDTO.setUserRoleList(roleList);

        // 装配返回
        userFullInfoDTO.setUserId(userInfo.getId());
        userFullInfoDTO.setIdentifier(userInfo.getRealName());
        userFullInfoDTO.setRealName(userInfo.getRealName());
        userFullInfoDTO.setUsername(userInfo.getRealName());
    }
}
