package com.jeequan.jeepay.agent.ctrl.anon;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.agent.ctrl.CommonCtrl;
import com.jeequan.jeepay.bizcommons.manage.sms.SmsManager;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBsecurityConfig;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.service.impl.SysUserAuthService;
import com.jeequan.jeepay.service.impl.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/*
* 登录密码接口
*
* @author xiaoyu
* @date 2021/6/8 17:09
*/
@RestController
@RequestMapping("/api/anon/cipher")
public class RetrieveController extends CommonCtrl {

	@Autowired private SysUserService sysUserService;
	@Autowired private SysUserAuthService sysUserAuthService;
	@Autowired private SysConfigService sysConfigService;
	@Autowired private SmsManager smsManager;


	/** 密码找回接口  **/
	@RequestMapping(value = "/retrieve", method = RequestMethod.POST)
	@MethodLog(remark = "密码找回")
	public ApiRes retrieve() throws BizException {

		// 手机号, 已做base64处理
		String phone = Base64.decodeStr(getValStringRequired("phone"));
		// 验证码,  已做base64处理
		String code = Base64.decodeStr(getValStringRequired("code"));
		// 新密码 password,  已做base64处理
        String newPwd = Base64.decodeStr(getValString("newPwd"));

		// 验证手机号
		smsManager.checkSmsVercodeThrowBizEx(phone, code, CS.SMS_TYPE_API_ENUM.TYPE_RETRIEVE);

		SysUserEntity dbUser = sysUserService.getOne(SysUserEntity.gw().eq(SysUserEntity::getTelphone, phone).eq(SysUserEntity::getSysType, CS.SYS_ROLE_TYPE.AGENT));
		if (dbUser == null) {
			throw new BizException("用户不存在");
		}
		if (StringUtils.isNotEmpty(newPwd)) {
			// 更新用户登录密码
			sysUserAuthService.resetAuthInfo(dbUser.getSysUserId(), null, null, true, newPwd, CS.SYS_ROLE_TYPE.AGENT);
			// TODO mq更新用户密码
		}

		return ApiRes.ok();
	}

	/** 获取密码校验规则正则  **/
	@RequestMapping(value = "/pwdRulesRegexp", method = RequestMethod.GET)
	public ApiRes getPwdRulesRegexp() throws BizException {


		DBsecurityConfig.PasswordRegexp passwordRegexp = sysConfigService.getDBSecurityConfig().getPasswordRegexp();
		JSONObject resultJson = null;
		if (passwordRegexp != null) {
			resultJson = (JSONObject) JSONObject.toJSON(passwordRegexp);
			// 查询是否需要审核
			String subIsAudit = sysConfigService.getDBDefaultConfig().getAgentNewSubIsAudit();
			resultJson.put("subIsAudit", subIsAudit);
		}
		return ApiRes.ok(resultJson);
	}

}
