package com.tangguo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tangguo.common.domain.QwmhUserInfo;
import com.tangguo.common.exception.ServiceException;
import com.tangguo.common.mauth.MobileTokenHelper;
import com.tangguo.domain.bo.CodeLoginBO;
import com.tangguo.mapper.BbsUserMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 动态用户业务类
 *
 * @author 谈笑
 * @createTime 2025-09-02 14:55:04 星期二
 */
@Slf4j
@Service
public class BbsUserService {

	@Resource
	private WxCpService wxCpService;

	@Resource
	private BbsUserMapper bbsUserMapper;


	/**
	 * 企微用户Code登录
	 *
	 * @param bo 登录参数
	 * @return 登录结果
	 */
	public Map<String, Object> codeLogin(CodeLoginBO bo) {
		String userName;
		try {
			log.info("=> 移动端用户登录：{}", bo);
			WxCpOauth2UserInfo authUserInfo = this.wxCpService.getOauth2Service().getAuthUserInfo(bo.getCode());
			userName = authUserInfo.getUserId();
		} catch (WxErrorException e) {
			log.error("=> 移动端用户登录失败，查询企微用户信息失败：", e);
			throw new ServiceException("登录失败，查询企微用户信息失败。");
		}

		try {
			QwmhUserInfo dbUser = this.bbsUserMapper.selectQwmhUserInfo(userName);
			if (Objects.nonNull(dbUser)) {
				Map<String, Object> payloads = new LinkedHashMap<>(1);
				payloads.put("userName", dbUser.getUserName());
				return MobileTokenHelper.createDetailToken(payloads);
			} else {
				throw new ServiceException("登录失败，未查询到当前登录用户数据。");
			}
		} catch (ServiceException e) {
			log.error("=> 移动端用户登录失败：", e);
			throw e;
		} catch (Exception e) {
			log.error("=> 移动端用户登录失败：", e);
			throw new ServiceException("登录失败：" + e.getMessage());
		}
	}


	/**
	 * 查询用户信息
	 *
	 * @return 用户信息
	 */
	public Map<String, Object> getUserProfile() {
		String username = MobileTokenHelper.getUsername();
		QwmhUserInfo dbUser = this.bbsUserMapper.selectQwmhUserInfo(username);
		if (Objects.nonNull(dbUser)) {
			return BeanUtil.beanToMap(dbUser, false, false);
		} else {
			throw new ServiceException("操作失败，未查询到当前用户信息。");
		}
	}

}
