package org.jeecg.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.api.bean.LoginReq;
import org.jeecg.api.service.OfficialLoginService;
import org.jeecg.api.untils.HttpConf;
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.api.untils.ConvertUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class OfficialLoginServiceImpl implements OfficialLoginService {

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

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


    @Value("${wechat-dm.mpAppId}")
    private String mpAppId;
    @Value("${wechat-dm.mpAppSecret}")
    private String mpAppSecret;


    /**
     * 公众号授权登录注册
     * @param loginReq
     * @return
     */
    @Override
    @Transactional
    public Result<?> officialLogin(LoginReq loginReq){
        Map<Object, Object> loginMap = new HashMap<>();
        if (StringUtils.isBlank(loginReq.getCode())) {
            throw new JeecgBootException("code为空");
        }
        String loginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +mpAppId + "&secret=" + mpAppSecret + "&code=" + loginReq.getCode() + "&grant_type=authorization_code";
        //使用工具类
        JSONObject json_test = httpConf.getJSONObject(loginUrl);
        log.info("{} {} -- {}", mpAppId, mpAppSecret, json_test);
        String wxOpenid = json_test.getString("openid");
        String wxUnionId = json_test.getString("unionid");
        String access_token  = json_test.getString("access_token");
        if (StringUtils.isBlank(wxOpenid)) {
            throw new JeecgBootException("未获取到openid");
        }
        HanHaiMember member = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getOfficialOpenid,wxOpenid).one();
        if(member!=null){
//            if (StringUtils.isBlank(member.getVid())){
//                member.setVid(loginReq.getVid());
//                member.setVtime(new Date());
//                hanHaiMemberService.updateById(member);
//            }
            //开始获取用户信息
            String memberUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+wxOpenid+"&lang=zh_CN";
            //使用工具类
            JSONObject json_member = httpConf.getJSONObject(memberUrl);
            String nickname = json_member.getString("nickname");
            String headimgurl  = json_member.getString("headimgurl");
            try {
                nickname = new String(nickname.getBytes("ISO-8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            member.setNickName(nickname);
            member.setHeadImage(headimgurl);
            member.setWxUnionid(wxUnionId);
            String token = JwtUtil.sign(member.getAccount(), member.getAccount());
            member.setToken(token);
            member.setUpdateTime(new Date());
            hanHaiMemberService.updateById(member);


            // 生成token返回

            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            // 设置超时时间
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
            loginMap.put("token",token);
            loginMap.put("userInfo",member);

            return Result.OK("登录成功",loginMap);
        }
        //开始获取用户信息
        String memberUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+wxOpenid+"&lang=zh_CN";
        //使用工具类
        JSONObject json_member = httpConf.getJSONObject(memberUrl);
        String nickname = json_member.getString("nickname");
        String headimgurl  = json_member.getString("headimgurl");
        try {
            nickname = new String(nickname.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HanHaiMember save = new HanHaiMember();
        save.setAccount(wxOpenid);
        save.setVid(loginReq.getVid());
        save.setVtime(new Date());
        save.setNickName(nickname);
        save.setHeadImage(headimgurl);
        save.setWxUnionid(wxUnionId);

        //销售邀请者标识
        save.setShareId(loginReq.getShareId());

        save.setOfficialOpenid(wxOpenid);
        save.setCreateTime(new Date());
        //密码加密
        String salt = ConvertUtils.randomGen(8);
        String encrypt = PasswordUtil.encrypt(wxOpenid,"123456" , salt);
        save.setPassword(encrypt);
        save.setPasswordSalt(salt);
        save.setDeleteFlag("N");
        save.setRole(0);


        // 生成token返回
        String token = JwtUtil.sign(wxOpenid, wxOpenid);
        save.setToken(token);

        hanHaiMemberService.save(save);
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
        loginMap.put("token",token);
        loginMap.put("userInfo",save);
        return Result.OK("登录成功",loginMap);
    }
}
