/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */

package com.qunzhixinxi.hnqz.admin.handler;

import com.qunzhixinxi.hnqz.admin.api.dto.UserDTO;
import com.qunzhixinxi.hnqz.admin.api.dto.UserInfo;
import com.qunzhixinxi.hnqz.admin.api.vo.UserVO;
import com.qunzhixinxi.hnqz.admin.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hnqz
 * @date 2018/11/18
 */
@Slf4j
@Component("SMS")
@AllArgsConstructor
public class SmsLoginHandler extends AbstractLoginHandler {

	private final SysUserService sysUserService;

	private final RedisTemplate redisTemplate;

	/**
	 * 验证码登录传入为手机号 不用不处理
	 *
	 * @param mobile
	 * @return
	 */
	@Override
	public String identify(String mobile) {
		return mobile;
	}

	/**
	 * 通过mobile 获取用户信息
	 *
	 * @param identify
	 * @return
	 */
	@Override
	public UserInfo info(String identify) {
		UserDTO userDTO = new UserDTO();
		userDTO.setPlatId(identify);

		List<Integer> roleList = new ArrayList<>();
		roleList.add(5);
		roleList.add(6);
		roleList.add(10);

		userDTO.setRole(roleList);

		List<UserVO> user = sysUserService.getUserVoByPlatId(userDTO);

		if (user == null) {
			log.info("手机号未注册:{}", identify);
			return null;
		}

		String mobileEnt = redisTemplate.opsForValue().get("SMS@" + identify + "ent") + "";
		if (!"".equals(mobileEnt) && !"null".equals(mobileEnt)) {
			if (user.size() > 1) {
				for (int i = 0; i < user.size(); i++) {
					if (mobileEnt.equals(user.get(i).getDrugEntId())) {
						redisTemplate.delete("SMS@" + identify + "ent");
						return sysUserService.findUserInfo(sysUserService.getById(user.get(i).getUserId()));
					}
					if (mobileEnt.equals(user.get(i).getUserId() + "")) {
						redisTemplate.delete("SMS@" + identify + "ent");
						return sysUserService.findUserInfo(sysUserService.getById(user.get(i).getUserId()));
					}
				}
			}
		}


		return sysUserService.findUserInfo(sysUserService.getById(user.get(0).getUserId()));
	}

}
