package com.yifu.cloud.plus.v1.yifu.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.yifu.cloud.plus.v1.yifu.admin.api.dto.UserInfo;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ServiceNameConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.CheckedException;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 手机验证码登录（）
 */
@Slf4j
@EnableConfigurationProperties(DaprUpmsProperties.class)
@Service
@AllArgsConstructor
public class WxUserDetailService implements UserDetailsService {

    private CacheManager cacheManager;

	private final DaprUpmsProperties daprUpmsProperties;

    /**
     * 手机验证码登录
     *
     * @param wxUserName 微信用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String wxUserName) throws UsernameNotFoundException {
        Cache cache = cacheManager.getCache(ServiceNameConstants.UMPS_SERVICE + "_user_details_wx");
        if (null != cache && null != cache.get(wxUserName)) {
            return (YifuUser) cache.get(wxUserName).get();
        }
        //根据手机号获取用户
		R<UserInfo> result = HttpDaprUtil.invokeMethodGet(daprUpmsProperties.getAppUrl(),daprUpmsProperties.getAppId(), "/user/getInfoByWxUsername", "?username="+wxUserName, UserInfo.class, SecurityConstants.FROM_IN);
		UserDetails userDetails = getUserDetails(result);
        if (cache == null) {
            throw new CheckedException("缓存为空");
        }
        cache.put(wxUserName, userDetails);
        return userDetails;
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfo> result) {
		if (result == null || result.getData() == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		UserInfo info = result.getData();
		Set<String> dbAuthsSet = new HashSet<>();

		if (ArrayUtil.isNotEmpty(info.getRoles())) {
			// 获取角色
			Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
			// 获取资源
			dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

		}
		Collection<? extends GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		SysUser user = info.getSysUser();
		// 构造security用户
		return new YifuUser(user.getUserId(), user.getDeptId(),user.getDeptName(), user.getUsername(),
				user.getNickname(),user.getSystemFlag(), SecurityConstants.BCRYPT + user.getPassword(),
				user.getPhone(), true, true, true,
				StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL),
				user.getUserGroup(),authorities, user.getLdapDn(),info.getClientRoleMap(),
				info.getSettleIdList(),user.getType(),null);
    }
}
