package org.springblade.modules.member.controller.wx;


import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.jwt.JwtUtil;
import org.springblade.core.jwt.props.JwtProperties;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.member.service.IMemberAccountService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 登录注册
 *
 * @author Chensl
 */
@NonDS
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping("yuecai-wx/member/login")
@Api(value = "登录注册", tags = "微信相关登录注册")
public class WXLoginController {

	private final BladeRedis bladeRedis;
	private final JwtProperties jwtProperties;
	private final IMemberAccountService accountService;



	/**
	 * 微信小程序登录
	 * @param clientCode
	 * @param code
	 * @return
	 */
	@ApiLog("微信小程序登录")
	@PostMapping("/miniapp")
	@ApiOperation(value = "微信小程序登录", notes =
			"1、请求头暂为固定数据：Authorization - Basic c2FiZXI6c2FiZXJfc2VjcmV0" +
		 	"2、如无注册则先注册" +
			"3、不获取用户详细信息，静默登录" +
			"4、无返回则是授权报错，需重新授权登录")
	public R<Kv> wxminiappLogin(@Valid @RequestParam String clientCode, @Valid @RequestParam String code, @RequestHeader("Tenant-Id")String tenantId) {
		return R.data(accountService.doWxMiniappLogin(clientCode, code, tenantId));
	}

	/**
	 * 微信小程序刷新token
	 * @param refreshToken
	 * @return
	 */
	@ApiLog("微信小程序刷新token")
	@PostMapping("/refresh")
	@ApiOperation(value = "微信小程序刷新token", notes =
			"1、请求头暂为固定数据：Authorization - Basic c2FiZXI6c2FiZXJfc2VjcmV0" +
					"2、如无注册则先注册" +
					"3、不获取用户详细信息，静默登录" +
					"4、无返回则是授权报错，需重新授权登录")
	public R<Kv> refresh( @Valid @RequestParam String refreshToken, @RequestHeader("Tenant-Id")String tenantId) {
		return R.data(accountService.doWxMiniappLogin("clientCode", refreshToken, tenantId));
	}

	public R<Kv> wxminiappRegister(@Valid @RequestParam String clientCode, @Valid @RequestParam String code){
		return R.data(accountService.doWxMiniappRegister(clientCode, code));
	}


//	/**
//	 * 微信小程序-会员注册
//	 *
//	 * @param wxcode    微信登录返回的 code
//	 * @param encrypted 消息密文
//	 * @param iv        加密算法的初始向量
//	 */
//	@ApiLog("微信小程序-会员注册")
//	@PostMapping("/register")
//	@ApiOperation(value = "微信小程序-会员注册", notes = "")
//	public Kv doRegister(@ApiParam(value = "门店id", required = true) @RequestParam Long shopId,
//						 @ApiParam(value = "微信编码", required = true) @RequestParam String wxcode,
//						 @ApiParam(value = "消息密文", required = true) @RequestParam String encrypted,
//						 @ApiParam(value = "加密算法的初始向量", required = true) @RequestParam String iv) {
//		Kv authInfo = Kv.create();
//		if (Func.isBlank(wxcode) || Func.isBlank(encrypted) || Func.isBlank(iv)) {
//			return authInfo.set("code", HttpServletResponse.SC_BAD_REQUEST).set("msg", "微信编码/消息密文/加密算法的初始向量不能为空").set("success", Boolean.FALSE);
//		}
//		WxMaUserInfo userInfo;
//		try {
//			String appid = properties.getConfigs().get(0).getAppid();
//			final WxMaService wxService = WxMaConfiguration.getMaService(appid);
//
//			WxMaUserService mauserBiz = wxService.getUserService();
//			WxMaJscode2SessionResult session = mauserBiz.getSessionInfo(wxcode);
//			// 解密用户信息
//			userInfo = mauserBiz.getUserInfo(session.getSessionKey(), encrypted, iv);
//			if (Func.isEmpty(userInfo)) {
//				return authInfo.set("code", HttpServletResponse.SC_BAD_REQUEST).set("msg", "登录失败，请重新登录").set("success", Boolean.FALSE);
//			}
//		} catch (Exception e) {
//			return authInfo.set("code", HttpServletResponse.SC_BAD_REQUEST).set("msg", "登录失败，请重新登录").set("success", Boolean.FALSE);
//		}
//		try {
//			// 校验用户是否已经注册过
//			LoginTokenDTO loginToken = accountService.register(AccountTypeEnum.WX_MINI_APP.getCode(), userInfo.getOpenId(), userInfo.getUnionId(),
//				null, userInfo.getAvatarUrl(), userInfo.getNickName());
//			return TokenUtil.createAuthInfo(loginToken);
//		} catch (Exception e) {
//			return authInfo.set("code", HttpServletResponse.SC_BAD_REQUEST).set("msg", "登录失败，请重新登录").set("success", Boolean.FALSE);
//		}
//		return null;
//	}

	@GetMapping("/oauth/logout")
	@ApiOperation(value = "退出登录")
	public Kv logout() {
		BladeUser user = AuthUtil.getUser();
		if (user != null && jwtProperties.getState()) {
			String token = JwtUtil.getToken(WebUtil.getRequest().getHeader(TokenConstant.HEADER));
			JwtUtil.removeAccessToken(user.getTenantId(), String.valueOf(user.getUserId()), token);
		}

		// 移除存储的redis数据，用于实时统计在线人数
		String ONLINE_LOGIN = "online:login:";

		List<Object> list = bladeRedis.mGet(ONLINE_LOGIN);
		String cache = (String) this.bladeRedis.get(ONLINE_LOGIN + user.getAccount());
		if (StringUtil.isNotBlank(user.getAccount()) && StringUtil.equalsIgnoreCase(cache, user.getAccount())) {
			this.bladeRedis.del(ONLINE_LOGIN + user.getAccount());
		}
		return Kv.create().set("code", "200").set("msg", "success").set("success", Boolean.TRUE);
	}


}
