package com.ningdatech.carapi.common.helper;

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

import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.carapi.datascope.model.DataScopeDto;
import com.ningdatech.carapi.datascope.provider.DataScopeContext;
import com.ningdatech.carapi.driver.entity.DriverInfo;
import com.ningdatech.carapi.driver.service.IDriverInfoService;
import com.ningdatech.carapi.sys.convert.UserAuthConverter;
import com.ningdatech.carapi.sys.convert.UserRoleConverter;
import com.ningdatech.carapi.sys.entity.Company;
import com.ningdatech.carapi.sys.entity.Role;
import com.ningdatech.carapi.sys.entity.UserRole;
import com.ningdatech.carapi.sys.entity.vo.UserInfoVO;
import com.ningdatech.carapi.sys.helper.CompaniesCacheHelper;
import com.ningdatech.carapi.sys.service.CompanyService;
import com.ningdatech.carapi.sys.service.RoleService;
import com.ningdatech.carapi.sys.service.UserRoleService;
import com.ningdatech.carapi.user.entity.NdUserAuth;
import com.ningdatech.carapi.user.entity.NdUserInfo;
import com.ningdatech.carapi.user.model.vo.UserBasicInfoVO;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import com.ningdatech.carapi.user.service.INdUserAuthService;
import com.ningdatech.carapi.user.service.INdUserInfoService;
import com.ningdatech.carapi.user.util.LoginUserUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author liuxinxin
 * @date 2022/10/22 上午11:50
 * <p>
 */
@Component
@RequiredArgsConstructor
public class UserInfoHelper {
    private final CompanyService companyService;
    private final INdUserInfoService iNdUserInfoService;
    private final IDriverInfoService driverInfoService;
    private final CompaniesCacheHelper companiesCacheHelper;
    private final INdUserAuthService userAuthService;
    private final UserRoleService userRoleService;
    private final RoleService roleService;

    public Long getUserCompanyId() {
        Long userId = LoginUserUtil.getUserId();
        NdUserInfo userInfo = iNdUserInfoService.getById(userId);
        if (Objects.isNull(userInfo.getCompanyId())) {
            throw new BizException("当前非公司或驾驶员账号");
        }
        return userInfo.getCompanyId();
    }

    public String getUserCompanyName() {
        Company company = companyService.getById(getUserCompanyId());
        return company.getName();
    }

    public Long getUserRegionId() {
        Company company = companyService.getById(getUserCompanyId());
        return company.getRegionId();
    }

    public UserBasicInfoVO getUserFullInfo() {
        UserBasicInfoVO userBasicInfoVO = new UserBasicInfoVO();
        UserInfoDetails user = LoginUserUtil.loginUserDetail();
        Long userId = user.getUserId();
        Long roleId = user.getRoleId();
        Optional<DataScopeDto> dataScope = DataScopeContext.getDataScope(user.getDataScope());
        if(dataScope.isPresent()){
            userBasicInfoVO.setMaxRegion(dataScope.get().getMaxRegion());
        }
        userBasicInfoVO.setNickName(user.getNickName());
        // 获取驾驶员信息
        DriverInfo driverInfo = driverInfoService.getOne(Wrappers.lambdaQuery(DriverInfo.class)
                .eq(DriverInfo::getUserId, userId));
        if (Objects.nonNull(driverInfo)) {
            userBasicInfoVO.setDriverId(driverInfo.getId());
        }
        userBasicInfoVO.setUserId(userId);
        userBasicInfoVO.setRoleId(roleId);
        userBasicInfoVO.setCompanyId(user.getCompanyId());
        Company company = companyService.getById(user.getCompanyId());
        userBasicInfoVO.setCompanyName(company.getName());
        userBasicInfoVO.setRegionId(company.getRegionId());
        userBasicInfoVO.setRegionName(company.getRegionName());

        return userBasicInfoVO;
    }

    public UserInfoVO getUserDetailByUserId(Long userId) {

        NdUserInfo user = iNdUserInfoService.getById(userId);
        if (Objects.isNull(user)) {
            return null;
        }

        UserInfoVO query = BeanUtil.toBean(user, UserInfoVO.class);
        //查出帐号
        searchAuth(query);
        //查出角色
        searchRoleName(query);
        return query;
    }

    private void searchAuth(UserInfoVO user) {
        if(Objects.isNull(user)){
            return;
        }
        //查出帐号
        LambdaQueryWrapper<NdUserAuth> wrapper = Wrappers.lambdaQuery(NdUserAuth.class);
        wrapper.in(NdUserAuth::getUserId, user.getId());
        List<NdUserAuth> auths = userAuthService.list(wrapper);
        if(CollUtil.isNotEmpty(auths)){
            UserAuthConverter.convert(user,auths);
        }
    }

    private void searchRoleName(UserInfoVO user) {
        if(Objects.isNull(user)){
            return;
        }
        //查出角色名
        LambdaQueryWrapper<UserRole> wrapper = Wrappers.lambdaQuery(UserRole.class);
        wrapper.in(UserRole::getUserId, user.getId());
        List<UserRole> userRoles = userRoleService.list(wrapper);
        if(CollUtil.isEmpty(userRoles)){
            return;
        }
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).distinct().collect(Collectors.toList());
        List<Role> roles = roleService.listByIds(roleIds);
        if(CollUtil.isNotEmpty(roles)){
            UserRoleConverter.convert(user,userRoles,roles);
        }
    }
}
