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

import cn.hutool.core.codec.Base64;
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.utils.InviteCodeUtil;
import com.jeequan.jeepay.db.entity.SysUserEntity;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

/**
 * 商户注册
 *
 * @author xiaoyu
 * 
 * @date 2021/12/30 14:59
 */
@RestController
@RequestMapping("/api/anon/register")
public class RegisterController extends CommonCtrl {

	@Autowired private SysUserService sysUserService;
	@Autowired private MchInfoService mchInfoService;
	@Autowired private SmsManager smsManager;

	/** 商户注册接口  **/
	@PostMapping(value = "/mchRegister")
	@MethodLog(remark = "商户注册")
	public ApiRes retrieve() throws BizException {

		// 商户名称, 已做base64处理
		String mchName = getValStringRequired("mchName");
		// 手机号, 已做base64处理
		String phone = Base64.decodeStr(getValStringRequired("phone"));
		// 验证码,  已做base64处理
		String code = Base64.decodeStr(getValStringRequired("code"));
		// 确认密码 confirmPassword,  已做base64处理
        String confirmPwd = Base64.decodeStr(getValStringRequired("confirmPwd"));
		// 商户类型 特约商户、普通商户
//		Byte mchType = getValByteRequired("mchType");
		// 邀请码
		String inviteCode = getValString("inviteCode");

		// 验证短信验证码
		smsManager.checkSmsVercodeThrowBizEx(phone, code, CS.SMS_TYPE_API_ENUM.TYPE_REGISTER);

		// 注册商户信息 *默认注册为特约商户
		mchInfoService.mchRegister(mchName, phone, confirmPwd, CS.MCH_TYPE_ISVSUB, inviteCode);

		return ApiRes.ok();
	}

	/** 处理邀请码  **/
	@PostMapping(value = "/inviteCode")
	public ApiRes inviteCode() throws BizException {
		List<SysUserEntity> sysUserEntityList = sysUserService.list();
		List<SysUserEntity> updateList = new LinkedList<>();

		for (SysUserEntity sysUserEntity : sysUserEntityList) {
			SysUserEntity update = new SysUserEntity();
			update.setSysUserId(sysUserEntity.getSysUserId());
			update.setInviteCode(InviteCodeUtil.idToCode(sysUserEntity.getSysUserId()));

			updateList.add(update);
		}

		sysUserService.updateBatchById(updateList);

		return ApiRes.ok();
	}
}
