package com.cyksj.web.controller.manage.mirrorshop.manage;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.annotation.NoSubmit;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.snowflake.Sequence;
import com.cyksj.common.util.Codec;
import com.cyksj.common.util.Jsons;
import com.cyksj.config.wxlogin.WxOpenPlatYHLXLoginConfig;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.model.dto.AuthRedirect;
import com.cyksj.model.dto.AuthToken;
import com.cyksj.model.dto.CpsAuthDto;
import com.cyksj.model.dto.GzhOAuth2UserInfo;
import com.cyksj.model.entity.User;
import com.cyksj.model.entity.UserMirrorShop;
import com.cyksj.model.request.LoginReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.authorization.AuthorizationService;
import com.cyksj.service.mirrorshop.CmsUserMirrorShopService;
import com.cyksj.service.wechat.WeChatService;
import com.cyksj.web.util.StpUserMirrorShopManageUser;
import com.cyksj.web.util.StpUserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * admin/镜像店铺后台/登录
 * 项目名: yhlxj2
 * 文件名: CmsUserMirrorShopLoginController
 * 创建者: JavaZou
 * 创建时间:2024/11/7 12:03
 */
@RestController
@RequestMapping("/mirrorShop/manage")
@RequiredArgsConstructor
public class CmsUserMirrorShopLoginController {
	private final CmsUserMirrorShopService cmsUserMirrorShopService;

	private final RedisService redisService;

	private final static Sequence SEQUENCE = new Sequence(0);

	private final WxOpenPlatYHLXLoginConfig wxOpenPlatYHLXLoginConfig;

	private final AuthorizationService authorizationService;

	private final WeChatService weChatService;

	private final UserMapper userMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	/**
	 * 获取登录验证码
	 */
	@GetMapping("/get/LoginCode")
	@NoSubmit
	public Result getLoginCode(@RequestParam(defaultValue = "1") Integer type, String login, Integer cid, String verifyCode, String ticket, String randSt) {
		cmsUserMirrorShopService.getLoginCode(type, login, cid, verifyCode, ticket, randSt);
		return GatewayResponse.SUCCESS.newBuilder().toResult();
	}

	/**
	 * 跳转店铺后台 是否是店铺主
	 */
	@GetMapping("/redirect")
	public void yhShopManageRedirect(String redirectUrl, HttpServletResponse response) throws IOException {
		//银河官网token值
		long userId = StpUserUtil.getLoginIdAsLong();
		cmsUserMirrorShopService.yhShopManageRedirect(userId);
		//校验通过重定向
		StpUserMirrorShopManageUser.login(userId);
		response.sendRedirect(redirectUrl.contains("?") ? redirectUrl + "&t=" + StpUserMirrorShopManageUser.getTokenValue() : redirectUrl + "?t=" + StpUserMirrorShopManageUser.getTokenValue());
	}


	/**
	 * 手机号、邮箱登录
	 */
	@PostMapping("/login")
	public Result login(@RequestBody LoginReq loginReq) {
		User user = cmsUserMirrorShopService.login(loginReq.getType(), loginReq.getLogin(), loginReq.getCode());
		StpUserMirrorShopManageUser.login(user.getId());
		String yhShopToken = StpUserMirrorShopManageUser.getTokenValue();
		JSONObject re = new JSONObject();
		re.putOpt("satoken-ump", yhShopToken);
		re.putOpt("img", user.getHeadimgurl());
		re.putOpt("nickname", user.getNickname());
		return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
	}

	/**
	 * 小店后台微信授权登录
	 */
	@GetMapping("/wx/authLogin")
	public Result<CpsAuthDto> wxAuthorize() throws Exception {
		Object authUrlObj = redisService.get(RedisService.key.WX_LOGIN_AUTH_URI.getNameFormat("ump", wxOpenPlatYHLXLoginConfig.getAppId()));
		if (authUrlObj != null) {
			CpsAuthDto cpsAuthDto = Jsons.parseObject(authUrlObj.toString(), CpsAuthDto.class);
			return GatewayResponse.SUCCESS.newBuilder().toResult(cpsAuthDto);
		}
		CpsAuthDto cpsAuthDto = new CpsAuthDto();
		Long mappingId = SEQUENCE.nextId();
		String authState = mappingId.toString();
		redisService.set(authState, authState, 60 * 60 * 24L);
		AuthRedirect redirect = new AuthRedirect().setMappingId(mappingId);
		String state = Codec.DoBase64.custom().setData(Jsons.toJson(redirect)).encodeAsText();
		String wxAuthUrl = authorizationService.createWxAuthLoginUrl(state, wxOpenPlatYHLXLoginConfig.getAppId(), wxOpenPlatYHLXLoginConfig.getUserMirrorShopRedirectUri());
		cpsAuthDto.setAuthUrl(wxAuthUrl);
		cpsAuthDto.setAuthState(authState);
		redisService.set(RedisService.key.WX_LOGIN_AUTH_URI.getNameFormat("ump", wxOpenPlatYHLXLoginConfig.getAppId()), Jsons.toJson(cpsAuthDto), RedisService.key.WX_LOGIN_AUTH_URI.getTimeout());
		return GatewayResponse.SUCCESS.newBuilder().toResult(cpsAuthDto);
	}

	/**
	 * 网页微信授权后跳转
	 */
	@GetMapping("/wx/authLogin/baseRedirect")
	public void wxAuthLoginRedirect(String code, String state, HttpServletResponse response) throws Exception {
		if (StrUtil.isEmpty(state)) throw BusinessRuntimeException.getInstance("授权错误,请重新授权");
		String json = Codec.DoBase64.custom().setData(state).decodeAsText();
		AuthRedirect re = Jsons.parseObject(json, AuthRedirect.class);
		AuthToken token = weChatService.getAuthToken(code, wxOpenPlatYHLXLoginConfig.getAppId());
		GzhOAuth2UserInfo userinfo = weChatService.getUserInfo(token.getAccessToken(), token.getOpenid());
		String unionId = userinfo.getUnionid();
		String openId = userinfo.getOpenid();
		User user = Optional.ofNullable(
						userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUnionid, unionId)
								.orderByAsc(User::getId)
								.last("limit 1")))
				.orElseGet(() -> userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId)
						.orderByAsc(User::getId)
						.last("limit 1")));
		if (user == null) throw BusinessRuntimeException.getInstance("用户信息不存在");
		//是否是店铺主
		UserMirrorShop shop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, user.getId()).last("limit 1"));
		if (shop == null) {
			throw BusinessRuntimeException.getInstance("您不是小店店铺主");
		}
		JSONObject res = new JSONObject();
		StpUserMirrorShopManageUser.login(user.getId());
		String cpsToken = StpUserMirrorShopManageUser.getTokenValue();
		res.putOpt("satoken-ump", cpsToken);
		res.putOpt("img", user.getHeadimgurl());
		res.putOpt("nickname", user.getNickname());
		redisService.set(RedisService.key.USER_MIRROR_SHOP_AUTH_SUCCESS_KEY.getNameFormat(re.getMappingId()), res.toString(), RedisService.key.USER_MIRROR_SHOP_AUTH_SUCCESS_KEY.getTimeout());
		response.sendRedirect(wxOpenPlatYHLXLoginConfig.getUserMirrorShopLoginUrl());
	}

	/**
	 * 店铺用户是否已授权
	 */
	@GetMapping("/get/userInfo")
	public Result<String> getCpsUserInfo(String authState) {
		String key = RedisService.key.USER_MIRROR_SHOP_AUTH_SUCCESS_KEY.getNameFormat(authState);
		Object o = redisService.get(key);
		if (o == null) return GatewayResponse.SUCCESS.newBuilder().toResult();
		redisService.del(key);
		return GatewayResponse.SUCCESS.newBuilder().toResult(o.toString());
	}
}
