package org.jeecg.modules.xcx.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.bean.HttpConf;
import org.jeecg.modules.bean.LoginReq;
import org.jeecg.modules.clockinauth.entity.ClockinAuth;
import org.jeecg.modules.clockinauth.service.IClockinAuthService;
import org.jeecg.modules.clockinteam.entity.ClockinTeam;
import org.jeecg.modules.clockinteam.service.IClockinTeamService;
import org.jeecg.modules.clockinteamlog.entity.ClockinTeamLog;
import org.jeecg.modules.clockinteamlog.service.IClockinTeamLogService;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.xcx.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    //公共用户表
    @Resource
    private IHanHaiMemberService hanHaiMemberService;

    //公共缓存类
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private HttpConf httpConf;



    /**
     * 微信公众号-appid
     */
    @Value("${weixin.mpAppId}")
    private String mpAppId;

    /**
     * 微信公众号-appSecret
     */
    @Value("${weixin.mpAppSecret}")
    private String mpAppSecret;
    @Resource
    private IHanHaiMemberService memberService;
    @Resource
    private IClockinTeamLogService clockinTeamLogService;
    @Resource
    private IClockinTeamService clockinTeamService;
    @Resource
    private IClockinAuthService clockinAuthService;


    /**
     * 公众号授权登录注册
     * @param loginReq
     * @return
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public Result<?> officialLogin(LoginReq loginReq){
        Result<Object> result = new Result<>();
        Map<String, Object> map = new HashMap<>();
            if (StringUtils.isBlank(loginReq.getCode())) {
                throw new JeecgBootException("小程序code为空");
            }
            String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + mpAppId + "&secret=" + mpAppSecret+ "&js_code=" + loginReq.getCode() + "&grant_type=authorization_code";
            //使用工具类
            JSONObject json_test = httpConf.getJSONObject(loginUrl);
            String wxOpenid = json_test.getString("openid");
            String sessionKey = json_test.getString("session_key");
            if (StringUtils.isBlank(wxOpenid)) {
                throw new JeecgBootException("未获取到openid");
            }

            HanHaiMember member = memberService.lambdaQuery().eq(HanHaiMember::getAppletOpenid,wxOpenid).one();
            if (member == null) {
                //如果user等于null说明该用户第一次登录，数据库没有该用户信息。
                loginReq.setOpenid(wxOpenid);
                loginReq.setSession_key(sessionKey);
                member = new HanHaiMember();
//            member.setSesssionKey(sessionKey);
                member.setAppletOpenid(wxOpenid);
                member.setNickName(loginReq.getNickName());
                member.setHeadImage(loginReq.getHeadimgurl());
                // 生成token返回给小程序端
                String token = JwtUtil.sign(member.getAppletOpenid(), wxOpenid);
                memberService.save(member);
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
                // 设置超时时间
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
                map.put("userInfo", member);
                map.put("token", token);

                result.setCode(200);
                result.setResult(map);
                return result;
            } else {
                ClockinTeamLog clockinTeamLog = clockinTeamLogService.lambdaQuery()
                        .eq(ClockinTeamLog::getDelFlag, 0)
                        .eq(ClockinTeamLog::getUserId, member.getId())
                        .one();
                if(clockinTeamLog != null){
                    ClockinTeam clockinTeam = clockinTeamService.lambdaQuery()
                            .eq(ClockinTeam::getDelFlag, 0)
                            .eq(ClockinTeam::getId, clockinTeamLog.getTeamId())
                            .one();
                    member.setTeam(clockinTeam);
                }
                ClockinAuth clockinAuth = clockinAuthService.lambdaQuery()
                        .eq(ClockinAuth::getDelFlag, 0)
                        .eq(ClockinAuth::getUserId, member.getId())
                        .one();
                member.setAuth(clockinAuth);
//            member.setHeadImage(loginReq.getHeadimgurl());
//            member.setSessionKey(sessionKey);
//            memberService.saveOrUpdate(member);
                // 生成token返回给小程序端
                String token = JwtUtil.sign(member.getAppletOpenid(), wxOpenid);
                redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
                // 设置超时时间
                redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
                map.put("userInfo", member);
                map.put("token", token);
                //用户id做im账号
                result.setResult(map);
                result.setCode(200);
//            result.setMessage(member.getNickName()+"已于"+member.getCreateTime()+"注册成功！请勿重复注册！");
//            // 未绑定手机号，跳转授权绑定手机号
//            if (StringUtils.isBlank(member.getPhone())) {
//                result.setMessage("该微信用户尚未绑定手机号，请授权手机进行绑定");
//                result.setCode(905);
//                result.setResult(map);
//                return result;
//            }
            }


        return result;
    }
}
