package com.yonge.cooleshow.biz.dal.service.impl;

import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageSendMode;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.enums.UserLockFlag;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {

	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private SysConfigService sysConfigService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TenantStaffService tenantStaffService;

    @Autowired
    private TenantInfoService tenantInfoService;

	@Override
	public boolean verifyValidCode(String mobile, String authCode, String type) {
		MessageTypeEnum typeEnum;
		if ("PASSWD".equals(type)) {
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE_UPDATE_PSW;
		} else if ("LOGIN".equals(type)) {
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE_LOGIN;
		} else if ("REGISTER".equals(type)) {
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE_REGISTER;
		} else if ("BANK".equals(type)){
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE_BANK_CARD;
		} else if ("PHONE".equals(type)) {
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE_UPDATE_PHONE;
		} else {
			typeEnum  = MessageTypeEnum.SMS_VERIFY_CODE;
		}
		String verifyCode = sysMessageService.getSendedVerificationCode(typeEnum, mobile);
		if (StringUtils.isNoneEmpty(verifyCode) && StringUtils.equalsIgnoreCase(verifyCode, authCode)) {
			return true;
		}
		return false;
	}

    @Override
    public boolean sendValidCode(String mobile, String type, ClientEnum platform, String code) {
        return sendValidCode(mobile, type, platform, code, null);
    }

	@Override
	public boolean sendValidCode(String mobile, String type, ClientEnum platform, String code, String client) {

        String configValue = sysConfigService.findConfigValue(SysConfigConstant.SMS_SEND_VERIFY);
        if((StringUtils.isNotEmpty(configValue) && "1".equals(configValue)) || StringUtils.isNotBlank(code)) {
            if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
                throw new BizException("你所使用的不是最新版本，请更新后使用");
            }
            String redisKey = MessageTypeEnum.KAPTCHA_SESSION_KEY + mobile;
            if (redisTemplate.hasKey(redisKey)) {
                if (!StringUtils.equalsIgnoreCase(redisTemplate.opsForValue().get(redisKey), code)) {
                    throw new BizException("图形验证码错误");
                }
            } else {
                throw new BizException("图形验证码错误");
            }
        }
		//SMS_VERIFY_CODE_LOGOFF
		SysUser sysUser = sysUserFeignService.queryUserByMobile(mobile);
		// 修改手机号 有用户了不许修改
		if ("PHONE".equals(type) && sysUser != null) {
			throw new BizException("手机号已经注册过账号");
		}
		Long userId = null;
		if (sysUser != null) {
			userId = sysUser.getId();

            // 如果是登陆，判断账号是否被锁定
            if ("LOGIN".equals(type)) {
                // 判断账号是否被锁定
                if (sysUser.getLockFlag() != 0) {
                    throw new BizException("账号已冻结，请联系管理员");
                }
                // 判断各端账号状态

                //判断用户是否被锁定
                if (ClientEnum.STUDENT == platform || ClientEnum.TENANT_STUDENT == platform) {
                    Student student = studentService.getById(userId);
                    if (student != null && UserLockFlag.LOCKED.equals(student.getLockFlag())) {
                        throw new LockedException("账号已冻结，请联系管理员");
                    }
                }else if(ClientEnum.TEACHER == platform) {
                    Teacher teacher = teacherService.getById(userId);
                    if (teacher !=null && UserLockFlag.LOCKED.equals(teacher.getLockFlag())) {
                        throw new LockedException("账号已冻结，请联系管理员");
                    }
                }else if(ClientEnum.SYSTEM == platform) {
                    Employee employee = employeeService.get(userId);
                    if (employee != null && (UserLockFlag.LOCKED.equals(employee.getLockFlag()))) {
                            throw new LockedException("账号已冻结，请联系管理员");
                    }
                } else if (ClientEnum.TENANT == platform) {
                    TenantStaff tenantStaff = tenantStaffService.getByUserId(userId);
                    if (tenantStaff != null) {
                        TenantInfo tenantInfo = tenantInfoService.getById(Optional.ofNullable(tenantStaff.getTenantId()).orElse(-1L));

                        if (tenantInfo == null) {
                            throw new UsernameNotFoundException("账户不存在");
                        }
                        if (Boolean.FALSE.equals(tenantInfo.getEnableFlag())) {
                            // 机构锁定
                            throw new LockedException("账号已冻结，请联系管理员");
                        }
                        if (UserLockFlag.LOCKED.equals(tenantStaff.getStatus())) {
                            // 账号被锁定
                            throw new LockedException("账号已冻结，请联系管理员");
                        }
                    }
                } else if (ClientEnum.WEBSITE == platform && StringUtils.isNotBlank(client)) {
                    if (client.equals(ClientEnum.STUDENT.name())) {
                        Student student = studentService.getById(userId);
                        if (student != null && UserLockFlag.LOCKED.equals(student.getLockFlag())) {
                            throw new LockedException("账号已冻结，请联系管理员");
                        }
                    } else if (client.equals(ClientEnum.TEACHER.name())) {
                        Teacher teacher = teacherService.getById(userId);
                        if (teacher !=null && UserLockFlag.LOCKED.equals(teacher.getLockFlag())) {
                            throw new LockedException("账号已冻结，请联系管理员");
                        }
                    }
                }
            }
		} else {
			sysUser = sysUserFeignService.queryUserInfo();
			if (sysUser != null) {
				userId = sysUser.getId();
			}
		}
		SysConfig sysConfig = sysConfigService.findByParamName(SysConfigService.SMS_MAX_TIMES);
		int times = 3;
		if (sysConfig != null) {
			times = Integer.parseInt(sysConfig.getParamValue());
		}
		// 十分钟内只能发3条
		List<SysMessage> list = sysMessageService.queryUserInRecentMinList(mobile, 10, MessageSendMode.SMS);
		if (list != null && list.size() >= times) {
			throw new BizException("对不起，您发送太频繁请稍后重试！");
		}
		if ("PASSWD".equals(type)) {
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_UPDATE_PSW, mobile,platform.getMsg());
		} else if ("LOGIN".equals(type)) {
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_LOGIN, mobile,platform.getMsg());
		} else if ("REGISTER".equals(type)) {
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_REGISTER, mobile,platform.getMsg());
		} else if ("BANK".equals(type)){
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_BANK_CARD, mobile,platform.getMsg());
		} else if ("PHONE".equals(type)) {
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_UPDATE_PHONE, mobile,platform.getMsg());
		} else if("LOGOFF".equals(type)){
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE_LOGOFF, mobile, "");
		} else {
			sysMessageService.sendSecurityCode(MessageSenderPluginContext.MessageSender.AWSMS, userId, MessageTypeEnum.SMS_VERIFY_CODE, mobile,platform.getMsg());
		}
		return true;
	}

}
