package com.ruoyi.framework.web.service;

import cn.hutool.core.lang.Validator;

import com.ruoyi.bgt.service.IBgtUserService;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.BgtUser;
import com.ruoyi.common.core.domain.entity.SysUser;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.wgz.domain.WgzUser;
import com.ruoyi.wgz.service.IWgzUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.lang.reflect.Field;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class AppUserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(AppUserDetailsServiceImpl.class);

	@Autowired
	private IWgzUserService wgzUserService;

    @Autowired
    private IBgtUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException
    {
		UserDetails userDetailsl = null;
		if(phone.contains(Constants.BGT)){
			BgtUser user = userService.selectUserByPhone(phone.replace(Constants.BGT,""));
			check(user,phone);
			userDetailsl = createLoginUser(user,Constants.BGT);
		} else if (phone.contains(Constants.WGZ)) {
			WgzUser wgzUser = wgzUserService.userLongIn(phone.replace(Constants.WGZ, ""));
			check(wgzUser,phone);
			userDetailsl = createLoginUser(wgzUser,Constants.WGZ);
		}
        return userDetailsl;
    }

    public UserDetails createLoginUser(Object obj,String userType)
    {
		SysUser sysUser = new SysUser();
		try {
			Field phoneField = obj.getClass().getDeclaredField("phone");
			phoneField.setAccessible(true);
			String phone= phoneField.get(obj).toString();

			Field userIdField = obj.getClass().getDeclaredField("userId");
			userIdField.setAccessible(true);
			Long userId = (Long)userIdField.get(obj);

			Field usernameField = obj.getClass().getDeclaredField("username");
			usernameField.setAccessible(true);
			String username = usernameField.get(obj).toString();

			Field passwordField = obj.getClass().getDeclaredField("password");
			passwordField.setAccessible(true);
			String password = passwordField.get(obj).toString();

			sysUser.setPhonenumber(phone);
			sysUser.setUserId(userId);
			sysUser.setUserName(username);
			sysUser.setPassword(password);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		LoginUser loginUser = new LoginUser(sysUser, null);
		loginUser.setUserType(userType);
		return loginUser;
    }


	public void check(Object obj,String phone){
		if (Validator.isNull(obj))
		{
			log.info("登录用户：{} 不存在.", phone);
			throw new UsernameNotFoundException("登录用户：" + phone + " 不存在");
		}
		String status;
		String delFlag;

		try {
			Field statusField = obj.getClass().getDeclaredField("status");
			statusField.setAccessible(true);
			status= statusField.get(obj).toString();
			Field delFlagField = obj.getClass().getDeclaredField("delFlag");
			delFlagField.setAccessible(true);
			delFlag = delFlagField.get(obj).toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		if (UserStatus.DELETED.getCode().equals(delFlag))
		{
			log.info("登录用户：{} 已被删除.", phone);
			throw new BaseException("对不起，您的账号：" + phone + " 已被删除");
		}
		else if (UserStatus.DISABLE.getCode().equals(status))
		{
			log.info("登录用户：{} 已被停用.", phone);
			throw new BaseException("对不起，您的账号：" + phone + " 已停用");
		}
	}
}
