package org.springblade.face.controller;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.springblade.auth.enums.ThirdPartyLoginType;
import org.springblade.auth.model.ThirdPartyLogin;
import org.springblade.common.utils.DigestUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.secure.utils.WebUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.face.data.WxSessionData;
import org.springblade.face.util.HttpSendPost;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenGranterBuilder;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.*;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IThirdBindCountRecordService;
import org.springblade.modules.system.service.IThirdLoginConfigService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "WechatController", tags = {"微信接口管理"})
@RequestMapping("wxapi")
@Slf4j
public class WechatController extends BladeController {

	@Autowired
	private IUserService userService;

	@Autowired
	private ITenantService tenantService;

	@Autowired
	private IThirdBindCountRecordService thirdBindCountRecordService;

	@Autowired
	private IThirdLoginConfigService thirdLoginConfigService;

	@Autowired
	private BladeRedis bladeRedis;

	public static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";


	@Value("${wxPay.wxAppid}")
	private String wxAppid;

	@Value("${wxPay.jscodeUrl}")
	private String jscodeUrl;

	@Value("${wxPay.authorizeUrl}")
	private String authorizeUrl;

	@Value("${wxPay.baseUrl}")
	private String baseUrl;

	@Value("${wxPay.wxSecret}")
	private String wxSecret;


	/**
	 * jscode 换取openId
	 * @param wxSessionData
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "jscode 换取openId", notes = "jscode 换取openId")
	@PostMapping("/code2Session")
		public R code2Session(@RequestBody WxSessionData wxSessionData) throws Exception {
		if (StrUtil.isBlank(wxSessionData.getCode())) {
			return R.fail("参数异常");
		}
		log.info("jscode 换取openId code2Session ====== appSecret{},code{}", wxSecret, wxSessionData.getCode());
		String url = jscodeUrl + "?appid=" + wxAppid + "&secret=" + wxSecret + "&js_code=" + wxSessionData.getCode() + "&grant_type=authorization_code";
		log.info("code2Session url = " + url);
		String res = HttpSendPost.send(url);
		log.info("code2Session res = " + res);
		JSONObject parse = JSONObject.parseObject(res);
		log.info("返回结果==={}", parse);
		String openid = parse.getString("openid");

		if(StringUtils.isNotBlank(openid)){
			return R.success(openid);
		}else {
			return R.fail("openid 获取失败");
		}
	}


	/**
	 * 微信登录
	 * @param wxSessionData
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "微信登录", notes = "微信登录")
	@PostMapping("/loginApp")
	public Kv loginApp(@RequestBody WxSessionData wxSessionData) throws Exception {
		Kv authInfo = Kv.create();
		String openId = wxSessionData.getOpenId();
		if (StrUtil.isBlank(openId)) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "参数异常");
		}
		User user = userService.getOne(new LambdaQueryWrapper<User>()
			.eq(User::getOpenId, openId)
			.eq(User::getIsDeleted,0)
		);
		if(user != null && user.getOpenId().equals(openId)){
			return weChatLogin(openId);
		}
		return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "登录失败");
	}



	@ApiOperation(value = "用户绑定openID", notes = "用户绑定openID")
	@PostMapping("/bindOpenId")
	public R bindOpenId(@RequestBody WxSessionData wxSessionData) throws Exception {
		if (StrUtil.isBlank(wxSessionData.getOpenId()) || StrUtil.isBlank(wxSessionData.getAccount()) || StrUtil.isBlank(wxSessionData.getPassword()) ) {
			return R.fail("参数异常");
		}
		User haveUser = userService.getOne(new LambdaQueryWrapper<User>()
			.eq(User::getAccount,wxSessionData.getAccount())
			.eq(User::getPassword, DigestUtil.hex(wxSessionData.getPassword()))
			.eq(User::getIsDeleted,0)
			.last("limit 1")
		);
		if (haveUser == null) {
			return R.fail("用户名或密码不正确");
		}
		if(StringUtils.isNotBlank(haveUser.getOpenId())){
			return R.fail("该微信已经绑定账号,不能重复绑定");
		}
		haveUser.setOpenId(wxSessionData.getOpenId());
		if(userService.updateById(haveUser)){
			ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
					.eq(ThirdBindCountRecord::getUserId, haveUser.getId()));
				if (countRecord != null && countRecord.getId() > 0) {
					if (StrUtil.isEmpty(countRecord.getMicroAppOpenId())) {
						countRecord.setMicroAppOpenId(wxSessionData.getOpenId());
						thirdBindCountRecordService.updateById(countRecord);
					}
				} else {
					countRecord = new ThirdBindCountRecord();
					countRecord.setMicroAppOpenId(wxSessionData.getOpenId());
					countRecord.setUserId(haveUser.getId());
					thirdBindCountRecordService.save(countRecord);
				}
			return R.success("绑定成功");
		}
		return R.fail("绑定失败");
	}


	@ApiOperation(value = "用户解除绑定openID", notes = "用户解除绑定openID")
	@PostMapping("/relieveOpenId")
	public R relieveOpenId() throws Exception {
		if(AuthUtil.getUser() == null){
			return R.fail("未登录");
		};
		log.info("relieveOpenId - user = " + AuthUtil.getUser().getUserId());
		User haveUser = userService.getById(AuthUtil.getUser().getUserId());
		if (haveUser == null) {
			return R.fail("用户不存在");
		}
		if(StringUtils.isNotBlank(haveUser.getOpenId())){
			haveUser.setOpenId("");
			if(userService.updateById(haveUser)){
				log.info("relieveOpenId - haveUser = " + haveUser);
				ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
						.eq(ThirdBindCountRecord::getUserId, haveUser.getId()));
				if (countRecord != null && countRecord.getId() > 0) {
					if (StrUtil.isNotBlank(countRecord.getMicroAppOpenId())) {
						countRecord.setMicroAppOpenId("");
						thirdBindCountRecordService.updateById(countRecord);
					}
				}
				return R.success("解绑成功");
			}
			return R.fail("解绑失败");
		}else {
			return R.fail("已解绑,不能重复解绑");
		}
	}


	@ApiOperation(value = "生成小程序二维码", notes = "生成小程序二维码")
	@GetMapping("/createQrcode")
	@ApiImplicitParam(name = "userId", value = "用户userId  非绑定指定用户情况下不需要传递", required = false, dataTypeClass = String.class)
	public R createQrcode(String userId) throws Exception {
		log.info("createQrcode - userId = {}", userId);
		String token = bladeRedis.get("wechat:token");
		if(StringUtils.isBlank(token)){
			String result = HttpUtil.get(String.format(GET_ACCESS_TOKEN_URL,wxAppid,wxSecret));
			if(StringUtils.isNotBlank(result)){
				JSONObject parse = (JSONObject) JSONObject.parse(result);
				String accessToken = parse.getString("access_token");
				bladeRedis.setEx("wechat:token",accessToken,7000L);
				token = accessToken;
			}
		}
		JSONObject jsonObject = new JSONObject();
		String sendUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token;
		String scene = RandomUtil.randomString(5)+System.currentTimeMillis();
		if(StringUtils.isNotBlank(userId)){
			scene = userId;
			jsonObject.put("scene", scene +"@910");
		}else {
			jsonObject.put("scene", scene);
		}
		log.info("token1 = {} scene = {}",token,scene);
		jsonObject.put("width", "280");
		//正式版
		//jsonObject.put("env_version", "release");
		//体验版
		jsonObject.put("env_version", "trial");

		PrintWriter out = null;
		InputStream in = null;
		URL realUrl = new URL(sendUrl);
		URLConnection urlConnection = realUrl.openConnection();
		// 设置通用请求属性
		urlConnection.setRequestProperty("accept", "*/*");
		urlConnection.setRequestProperty("connection", "Keep-Alive");
		urlConnection.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		//发送POST请求必设
		urlConnection.setDoOutput(true);
		urlConnection.setDoInput(true);

		try {
			out = new PrintWriter(urlConnection.getOutputStream());
			out.print(jsonObject);
			out.flush();
			//获取URL的输入流
			in = urlConnection.getInputStream();
			String s = inputStream2Base64(in);
			bladeRedis.setEx(scene,"0",300L);
			Map<String, Object> map = new HashMap<>();
			map.put("scene",scene);
			map.put("base64",s);
			return R.data(map);
		}catch (Exception e){
			e.printStackTrace();
			return R.fail("生成二维码失败");
		}
	}


	public String inputStream2Base64(InputStream is) throws Exception {
		byte[] data = null;
		try {
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[100];
			int rc = 0;
			while ((rc = is.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					throw new Exception("输入流关闭异常");
				}
			}
		}
		return Base64.getEncoder().encodeToString(data);
	}


	@GetMapping("/CustomBindScan")
	@ApiOperation("扫小程序二维码绑定指定帐号 userid 和 openid （权限未校验）")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "scene", value = "二维码唯一标识", required = true, dataTypeClass = String.class),
			@ApiImplicitParam(name = "openId", value = "用户openId", required = true, dataTypeClass = String.class)
	})
	public R CustomBindScan(String scene,String openId) {
		if(StringUtils.isBlank(scene) || StringUtils.isBlank(openId)){
			return R.fail("参数异常");
		}
		User haveUser = userService.getById(scene);
		if (haveUser == null) {
			return R.fail("用户信息不存在");
		}
		if (StringUtils.isNotBlank(haveUser.getOpenId())) {
			return R.fail("该账号已绑定openId");
		}
		List<User> list = userService.list(new LambdaQueryWrapper<User>()
				.eq(User::getOpenId, openId));
		if(list != null && list.size() > 0){
			return R.fail("该微信号已绑定其他账号,不能重复绑定");
		}
		haveUser.setOpenId(openId);
		if(userService.updateById(haveUser)){
			ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
					.eq(ThirdBindCountRecord::getUserId, haveUser.getId()));
			if (countRecord != null && countRecord.getId() > 0) {
				if (StrUtil.isEmpty(countRecord.getMicroAppOpenId())) {
					countRecord.setMicroAppOpenId(openId);
					thirdBindCountRecordService.updateById(countRecord);
				}
			} else {
				countRecord = new ThirdBindCountRecord();
				countRecord.setMicroAppOpenId(openId);
				countRecord.setUserId(haveUser.getId());
				thirdBindCountRecordService.save(countRecord);
			}
			return R.success("绑定成功");
		}
		return R.fail("绑定失败");
	}



	@GetMapping("/scan")
	@ApiOperation("扫二维码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "scene", value = "二维码唯一标识", required = true, dataTypeClass = String.class),
			@ApiImplicitParam(name = "openId", value = "用户openId", required = true, dataTypeClass = String.class)
	})
	public R scan(String scene,String openId) {
		if(StringUtils.isBlank(scene) || StringUtils.isBlank(openId)){
			return R.fail("参数异常");
		}

		String sys = (String) bladeRedis.get(scene);
		if(StringUtils.isBlank(sys)){
			return R.fail("二维码已失效，请重新生成");
		}

		if("0".equals(sys)){
			bladeRedis.setEx(scene,openId,300L);
			return R.success("扫码成功");
		}else {
			return R.fail("二维码已使用");
		}
	}



	@GetMapping("/bindScan")
	@ApiOperation("扫二维码绑定openid")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "scene", value = "二维码唯一标识", required = true, dataTypeClass = String.class),
			@ApiImplicitParam(name = "openId", value = "用户openId", required = true, dataTypeClass = String.class)
	})
	public R bindScan(String scene,String openId) {
		if(AuthUtil.getUser() == null){
			return R.fail("未登录");
		};
		if(StringUtils.isBlank(scene) || StringUtils.isBlank(openId)){
			return R.fail("参数异常");
		}
		User haveUser = userService.getById(AuthUtil.getUser().getUserId());
		if (haveUser == null) {
			return R.fail("用户不存在");
		}
		if (StringUtils.isNotBlank(haveUser.getOpenId())) {
			return R.fail("该账号已绑定openId");
		}
		List<User> list = userService.list(new LambdaQueryWrapper<User>()
				.eq(User::getOpenId, openId));
		if(list != null && list.size() > 0){
			return R.fail("该微信号已绑定其他账号,不能重复绑定");
		}
		haveUser.setOpenId(openId);
		if(userService.updateById(haveUser)){
			ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
					.eq(ThirdBindCountRecord::getUserId, haveUser.getId()));
			if (countRecord != null && countRecord.getId() > 0) {
				if (StrUtil.isEmpty(countRecord.getMicroAppOpenId())) {
					countRecord.setMicroAppOpenId(openId);
					thirdBindCountRecordService.updateById(countRecord);
				}
			} else {
				countRecord = new ThirdBindCountRecord();
				countRecord.setMicroAppOpenId(openId);
				countRecord.setUserId(haveUser.getId());
				thirdBindCountRecordService.save(countRecord);
			}
			return R.success("绑定成功");
		}
		return R.fail("绑定失败");
	}


	@GetMapping("/verifyScan")
	@ApiOperation("校验扫码状态")
	@ApiImplicitParam(name = "scene", value = "二维码唯一标识", required = true, dataTypeClass = String.class)
	public R verifyScan(String scene) {
		if(StringUtils.isBlank(scene)){
			return R.fail("参数异常");
		}
		String sys = (String) bladeRedis.get(scene);
		return R.data(sys);
	}



	public Kv weChatLogin(String openId) {
		Kv authInfo = Kv.create();
		log.info("weChatLogin === openId {}", openId);
		User user = userService.getOne(new LambdaQueryWrapper<User>()
			.eq(User::getOpenId, openId)
			.eq(User::getIsDeleted, 0));
		log.info("faceLogin === user {}", user);
		if (user == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "用户不存在");
		}
		UserInfo userInfo = grant(user);

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "用户名或密码不正确");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "未获得用户的角色信息");
		}

		return TokenUtil.createAuthInfo(userInfo);
	}

	public Kv userLogin(Long userId) {
		Kv authInfo = Kv.create();
		log.info("userLogin === userId {}", userId);
		User user = userService.getOne(new LambdaQueryWrapper<User>()
				.eq(User::getId, userId)
				.eq(User::getIsDeleted, 0));
		log.info("faceLogin === user {}", user);
		if (user == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "用户不存在");
		}
		UserInfo userInfo = grant(user);

		if (userInfo == null || userInfo.getUser() == null) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "用户名或密码不正确");
		}

		if (Func.isEmpty(userInfo.getRoles())) {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "未获得用户的角色信息");
		}

		return TokenUtil.createAuthInfo(userInfo);
	}

	public UserInfo grant(User user) {
		String tenantId = user.getTenantId();
		String username = user.getAccount();
		String password = user.getPassword();
		UserInfo userInfo = null;
		if (StrUtil.isNotBlank(username) && StrUtil.isNotBlank(password)) {
			// 获取租户信息
			Tenant tenant = tenantService.getByTenantId(tenantId);
			if (TokenUtil.judgeTenant(tenant)) {
				throw new ServiceException(TokenUtil.USER_HAS_NO_TENANT_PERMISSION);
			}
			// 根据不同用户类型调用对应的接口返回数据，用户可自行拓展
			userInfo = userService.userInfo(tenantId, username, password, UserEnum.APP);
		}
		return userInfo;
	}


	@GetMapping("/getAuthorize")
	@ApiOperation("获取授权地址")
	public R getAuthorize(String state,String redirectUrl) throws Exception {
		if(StringUtils.isBlank(state)){
			state = "STATE";
		}
		if(StringUtils.isBlank(redirectUrl)){
			return R.fail("参数异常");
		}
		String appid = "";
		List<ThirdLoginConfig> list = thirdLoginConfigService.list(Wrappers.<ThirdLoginConfig>lambdaQuery()
				.eq(ThirdLoginConfig::getLoginType, "publicAccount")
				.eq(ThirdLoginConfig::getStatus, 1));
		if (CollectionUtil.isNotEmpty(list)) {
			ThirdLoginConfig loginConfig = list.get(0);
			String loginConf = loginConfig.getLoginConf();
			JSONObject loginConfJson = JSONObject.parseObject(loginConf);
			log.info("AuthorizeLogin - loginConfJson = {}", loginConfJson);
			appid = loginConfJson.getString("clientId");
			//String redirectUrl = "https://windata.platomix.net/bind.html";
			String url = authorizeUrl + "?appid=" + appid + "&redirect_uri=" + URLEncoder.encode(redirectUrl,"UTF-8") + "&response_type=code" + "&scope=snsapi_base" + "&state=" + state + "#wechat_redirect";
			log.info("getAuthorize url = " + url);
			return R.data(url);
		}else {
			return R.fail("公众号参数未配置");
		}
	}


	@GetMapping("/AuthorizeLogin")
	@ApiOperation("授权绑定 - 取消登录功能")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "code", value = "code码", required = true, dataTypeClass = String.class),
			@ApiImplicitParam(name = "state", value = "自定义参数",required = false, dataTypeClass = String.class)
	})
	public Kv AuthorizeLogin(String code,String state) throws Exception {
		Kv authInfo = Kv.create();
		if(StringUtils.isBlank(code)){
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "参数异常");
		}
		String appid = "";
		String secret = "";
		List<ThirdLoginConfig> list = thirdLoginConfigService.list(Wrappers.<ThirdLoginConfig>lambdaQuery()
				.eq(ThirdLoginConfig::getLoginType, "publicAccount")
				.eq(ThirdLoginConfig::getStatus, 1));
		if (CollectionUtil.isNotEmpty(list)) {
			ThirdLoginConfig loginConfig = list.get(0);
			String loginConf = loginConfig.getLoginConf();
			JSONObject loginConfJson = JSONObject.parseObject(loginConf);
			log.info("AuthorizeLogin - loginConfJson = {}", loginConfJson);
			appid = loginConfJson.getString("clientId");
			secret = loginConfJson.getString("clientSecret");
		}else {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "公众号参数未配置");
		}

		String url = baseUrl + "?appid=" + appid + "&secret=" +secret + "&&code=" + code + "&grant_type=authorization_code";
		String res = HttpSendPost.send(url);
		log.info("AuthorizeLogin - res = " + res);
		JSONObject parse = JSONObject.parseObject(res);
		log.info("AuthorizeLogin - parse = {}", parse);
		String openid = parse.getString("openid");
		if(StringUtils.isNotBlank(openid)){
			//静默绑定
			if(StringUtils.isNotBlank(state)){
				List<ThirdBindCountRecord> bindRecordList = thirdBindCountRecordService.list(Wrappers.<ThirdBindCountRecord>lambdaQuery()
						.eq(ThirdBindCountRecord::getPublicAccountOpenid,openid)
				);
				if (bindRecordList != null && bindRecordList.size() > 0) {
					if (bindRecordList.get(0).getUserId() == null) {
						return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "绑定信息缺少userID");
					}
					return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "已绑定帐号，不能重复绑定");
				}

				ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
						.eq(ThirdBindCountRecord::getUserId,state)
				);
				if (countRecord != null && countRecord.getId() > 0) {
					if (StringUtils.isBlank(countRecord.getPublicAccountOpenid())) {
						countRecord.setPublicAccountOpenid(openid);
						thirdBindCountRecordService.updateById(countRecord);
						return authInfo.set("error_code", HttpServletResponse.SC_OK).set("error_msg", "绑定成功");
						//return userLogin(countRecord.getUserId());
					}
					return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "该微信号已绑定，不能重复绑定");
				} else {
					//新增
					countRecord = new ThirdBindCountRecord();
					countRecord.setPublicAccountOpenid(openid);
					countRecord.setUserId(Long.valueOf(state));
					thirdBindCountRecordService.save(countRecord);
					return authInfo.set("error_code", HttpServletResponse.SC_OK).set("error_msg", "绑定成功");
					//return userLogin(countRecord.getUserId());
				}
			}else {
				ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
						.eq(ThirdBindCountRecord::getPublicAccountOpenid,openid)
				);
				//正常提示
				if (countRecord != null && countRecord.getId() > 0) {
					if (countRecord.getUserId() == null) {
						return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "绑定信息缺少userID");
					}
					return userLogin(countRecord.getUserId());
				} else {
					return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "未绑定").set("openid",openid);
				}
			}
		}else {
			return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_msg", "获取授权信息异常");
		}
	}


	@GetMapping("/bindRelieve")
	@ApiOperation("解除绑定 - （管理员专用版-未校验）")
	private R getThirdPartyLogin(ThirdPartyLoginType loginType,String userId) {
		log.info("getThirdPartyLogin - loginType = {} , userId = {}",loginType,userId);
		if(StringUtils.isBlank(userId) || loginType == null){
			return R.fail("参数异常");
		}
		ThirdBindCountRecord countRecord = thirdBindCountRecordService.getOne(Wrappers.<ThirdBindCountRecord>lambdaQuery()
				.eq(ThirdBindCountRecord::getUserId, userId));
		log.info("getThirdPartyLogin - countRecord = {}",countRecord);
		if(countRecord != null){
			//钉钉
			if(loginType.getValue().equals(ThirdPartyLoginType.dingTalk.getValue())){
				countRecord.setDingOpenid("");
			}
			//微信
			if(loginType.getValue().equals(ThirdPartyLoginType.weChat.getValue())){
				countRecord.setWechatOpenId("");
			}
			//企业微信
			if(loginType.getValue().equals(ThirdPartyLoginType.qiWeChat.getValue())){
				countRecord.setQyWechatOpenId("");
			}
			//飞书
			if(loginType.getValue().equals(ThirdPartyLoginType.feiShu.getValue())){
				countRecord.setFeiShuOpenId("");
			}
			//公众号
			if(loginType.getValue().equals(ThirdPartyLoginType.publicAccount.getValue())){
				countRecord.setPublicAccountOpenid("");
			}
			//小程序
			if(loginType.getValue().equals(ThirdPartyLoginType.applet.getValue())){
				countRecord.setMicroAppOpenId("");
				User haveUser = userService.getById(userId);
				if(haveUser != null){
					haveUser.setOpenId("");
					userService.updateById(haveUser);
				}
			}
			return R.data(thirdBindCountRecordService.updateById(countRecord),"解绑成功");
		}
		return R.fail("绑定信息不存在");
	}

}
