/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.security.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.PrincipalUtil;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.service.YamiUserDetailsService;
import com.yami.shop.security.comment.dao.AppConnectMapper;
import com.yami.shop.security.comment.exception.UsernameNotFoundException;
import com.yami.shop.security.comment.exception.YamiAuthFilterException;
import com.yami.shop.security.comment.model.AppConnect;
import com.yami.shop.security.comment.service.AppConnectService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 用户详细信息
 *
 * @author
 */
@Slf4j
@Primary
@Service
@AllArgsConstructor
public class YamiUserServiceImpl implements YamiUserDetailsService {

	private final UserMapper userMapper;

	private final AppConnectMapper appConnectMapper;

	private final AppConnectService appConnectService;


	@Override
	public YamiUser loadUserByUsername(String principal) {
		throw new GlobalException("未实现该登陆方法");
	}

	/**
	 * @param principal userNameOrMobile
	 * @param appType 见 APP
	 * @return
	 */
	@Override
	public YamiUser loadUserByMobileOrUserName(String principal, Integer appType, Integer loginType) {

		User user = loadUserByMobileOrUserName(principal, loginType);


		// 如果是手机验证码登陆，直接给他注册一个用户
		if (Objects.equals(loginType, 1) && user == null) {
			user = new User();
			Date now = new Date();
			user.setModifyTime(now);
			user.setUserRegtime(now);
			user.setUserRegip(IPHelper.getIpAddr());
			user.setStatus(1);
			user.setUserMobile(principal);
			user.setUserName(principal);
			// 用户名就是默认的昵称
			user.setNickName(principal);
			appConnectService.registerOrBindUser(user, null, appType);
		}

		if (user == null) {
			throw new UsernameNotFoundException("用户不存在");
		}
		//
		AppConnect appConnect = appConnectMapper.getByUserId(user.getUserId(), appType);
		if (appConnect == null) {
			appConnectService.registerOrBindUser(user, null, appType);
		}
		return getYamiUser(appType, user, appConnect == null? null:appConnect.getBizUserId());
	}

	@Override
	public YamiUser loadUserByAppConnect(AppConnect appConnect) {

		if (StrUtil.isBlank(appConnect.getUserId())) {
			YamiUser yamiUser = new YamiUser();
			yamiUser.setUserId(appConnect.getUserId());
			yamiUser.setBizUserId(appConnect.getBizUserId());
			yamiUser.setAppType(appConnect.getAppId());

			// 没有userId一样可以用，只不过不能进行下单的流程而已咯
			yamiUser.setEnabled(true);
			return yamiUser;
		}
		User user = userMapper.selectById(appConnect.getUserId());
        if (user == null) {
            appConnectMapper.delete(new LambdaQueryWrapper<AppConnect>().eq(AppConnect::getUserId, appConnect.getUserId()));
		}
		return getYamiUser(appConnect.getAppId(), user, appConnect.getBizUserId());
	}

	@Override
	public User loadUserByMobileOrUserName(String mobileOrUserName, Integer loginType) {
		User user = null;
		// 手机验证码登陆，或传过来的账号很像手机号
		if (Objects.equals(loginType, 1) || PrincipalUtil.isMobile(mobileOrUserName)) {
			user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserMobile, mobileOrUserName));
		}
		// 如果不是手机验证码登陆， 找不到手机号就找用户名
		if  (!Objects.equals(loginType, 1) && user == null) {
			user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, mobileOrUserName));
		}
		return user;
	}

	@Override
	public YamiUser getYamiUser(Integer appId, User user, String bizUserId) {
		log.info("用户信息：{}", user);
		log.info("appId：{}", appId);
		log.info("bizUserId：{}", bizUserId);
		YamiUser yamiUser = new YamiUser();
		yamiUser.setEnabled(Boolean.TRUE);
		String nickName = "微信用户";
		if (user != null){
			nickName = StrUtil.isBlank(user.getNickName()) ? user.getRealName():user.getNickName();
			yamiUser.setEnabled(user.getStatus() == 1);
			yamiUser.setUserId(user.getUserId());
            yamiUser.setPic(user.getPic());
			yamiUser.setPassword(user.getLoginPassword());
		}
		yamiUser.setBizUserId(bizUserId);
		yamiUser.setAppType(appId);
		yamiUser.setName(nickName);

		return yamiUser;
	}
}
