/*
 *    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.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.qunzhixinxi.hnqz.admin.api.dto.UserDTO;
import com.qunzhixinxi.hnqz.admin.api.entity.SysRole;
import com.qunzhixinxi.hnqz.admin.api.vo.UserVO;
import com.qunzhixinxi.hnqz.admin.mapper.SysUserMapper;
import com.qunzhixinxi.hnqz.admin.service.MobileService;
import com.qunzhixinxi.hnqz.admin.util.SendSms;
import com.qunzhixinxi.hnqz.common.core.constant.CacheConstants;
import com.qunzhixinxi.hnqz.common.core.constant.SecurityConstants;
import com.qunzhixinxi.hnqz.common.core.constant.enums.LoginTypeEnum;
import com.qunzhixinxi.hnqz.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author hnqz
 * @date 2018/11/14
 * <p>
 * 手机登录相关业务实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class MobileServiceImpl implements MobileService {

	private final RedisTemplate redisTemplate;

	private final SysUserMapper userMapper;

	/**
	 * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
	 *
	 * @param mobile mobile
	 * @return code
	 */
	@Override
	public R<Boolean> sendSmsCode(String mobile) {
		UserDTO userDTO = new UserDTO();
		userDTO.setPlatId(mobile);
		List<UserVO> userListNew = userMapper
				.getUserVoByPlatId(userDTO);


		List<UserVO> userList = new ArrayList<>();

		/**
		 * 解决验证码问题
		 * 20201225
		 */
		Boolean sendFlag = false;

		if (userListNew.size() > 0) {
			for (UserVO userVO : userListNew) {
				if (null != userVO.getRoleList() && userVO.getRoleList().size() > 0) {
					boolean isLevel2 = false;
					boolean isLevel3 = false;
					boolean isLevel4 = false;
					boolean isLevel5 = false;
					boolean isLevel6 = false;
					boolean isLevel10 = false;
					boolean isLevel13 = false;

					for (SysRole sysRole : userVO.getRoleList()) {
						if (sysRole.getRoleId() == 2) {
							isLevel2 = true;
						} else if (sysRole.getRoleId() == 3) {
							isLevel3 = true;
						} else if (sysRole.getRoleId() == 4) {
							isLevel4 = true;
						} else if (sysRole.getRoleId() == 5) {
							isLevel5 = true;
						} else if (sysRole.getRoleId() == 6) {
							isLevel6 = true;
						}else if (sysRole.getRoleId() == 10) {
							isLevel10 = true;
						}else if (sysRole.getRoleId() == 13) {
							// 患者教育-HCP角色
							isLevel13 = true;
						}

						if (isLevel5 || isLevel6 || isLevel10 || isLevel13) {
							userList.add(userVO);
						}
					}
				}
				if(!sendFlag&&StringUtils.isNotEmpty(userVO.getTemp4())){
					if("1".equals(userVO.getTemp4())){
						sendFlag  = true;
					}
				}
			}
		}

		if (CollUtil.isEmpty(userList)) {
			log.info("请联系管理员为您开通账号:{}", mobile);
			return R.ok(Boolean.FALSE, "请联系管理员为您开通账号");
		}

		Object codeObj = redisTemplate.opsForValue()
				.get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile);

		if (codeObj != null) {
			log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
			return R.ok(Boolean.FALSE, "验证码发送过频繁");
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));

		if(sendFlag){
			code = "5657";
		}

		try {
			if (!sendFlag) {
				SendSms.sendSmsCode(mobile, code);
			}
			log.debug("手机号生成验证码成功:{},{}", mobile, code);
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		redisTemplate.opsForValue().set(
				CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile, code,
				SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		return R.ok(Boolean.TRUE, "验证码发送成功");
	}


	/**
	 * 发送手机验证码 TODO: 调用短信网关发送验证码,测试返回前端
	 *
	 * @param mobile mobile
	 * @return code
	 */
	@Override
	public R<Boolean> sendSmsCodePc(String mobile) {
		UserDTO userDTO = new UserDTO();
		userDTO.setPlatId(mobile);
		List<UserVO> userListNew = userMapper
				.getUserVoByPlatId(userDTO);


		List<UserVO> userList = new ArrayList<>();
		if (userListNew.size() > 0) {
			for (UserVO userVO : userListNew) {
				if (null != userVO.getRoleList() && userVO.getRoleList().size() > 0) {
					boolean isLevel2 = false;
					boolean isLevel3 = false;
					boolean isLevel4 = false;
					boolean isLevel5 = false;
					boolean isLevel6 = false;
					boolean isLevel7 = false;
					boolean isLevel9 = false;

					for (SysRole sysRole : userVO.getRoleList()) {
						if (sysRole.getRoleId() == 2) {
							isLevel2 = true;
						} else if (sysRole.getRoleId() == 3) {
							isLevel3 = true;
						} else if (sysRole.getRoleId() == 4) {
							isLevel4 = true;
						} else if (sysRole.getRoleId() == 5) {
							isLevel5 = true;
						} else if (sysRole.getRoleId() == 6) {
							isLevel6 = true;
						} else if (sysRole.getRoleId() == 7) {
							isLevel7 = true;
						} else if (sysRole.getRoleId() == 9) {
							isLevel9 = true;
						}

						if (isLevel2 || isLevel3 || isLevel4 ||isLevel7 || isLevel9) {
							userList.add(userVO);
						}
					}
				}
			}
		}

		if (CollUtil.isEmpty(userList)) {
			log.info("请联系管理员为您开通账号:{}", mobile);
			return R.ok(Boolean.FALSE, "请联系管理员为您开通账号");
		}

		Object codeObj = redisTemplate.opsForValue()
				.get(CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile);

		if (codeObj != null) {
			log.info("手机号验证码未过期:{}，{}", mobile, codeObj);
			return R.ok(Boolean.FALSE, "验证码发送过频繁");
		}

		String code = RandomUtil.randomNumbers(Integer.parseInt(SecurityConstants.CODE_SIZE));
		try {
			SendSms.sendSmsCode(mobile, code);
			log.debug("手机号生成验证码成功:{},{}", mobile, code);
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		redisTemplate.opsForValue().set(
				CacheConstants.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + StringPool.AT + mobile, code,
				SecurityConstants.CODE_TIME, TimeUnit.SECONDS);
		return R.ok(Boolean.TRUE, "验证码发送成功");
	}
}
