package org.jeecg.modules.api.service.Impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.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.RedisUtil;
import org.jeecg.modules.api.service.LoginApiService;
import org.jeecg.modules.bean.HttpConf;
import org.jeecg.modules.bean.LoginReq;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LoginApiServiceImpl implements LoginApiService {

    /******************************************************************************************************************/
    //微信小程序appid(鸿宇研学生)
    private static final String mpAppId = "wxee64675d48680dd4";
    //微信小程序appSecret(鸿宇研学生)
    private static final String mpAppSecret = "d7e3f49858350cf40b1aeeb8fa1c61eb";

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private IHanHaiMemberService hanHaiMemberService;

    @Resource
    private HttpConf httpConf;
    /******************************************************************************************************************/

    @Override
    public Result<?> login(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 = hanHaiMemberService.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);
            hanHaiMemberService.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 {
//            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;
    }

    @Override
    public Result<Object> bindPhone(String phoneCode) {
        try {
            String phoneNumber = this.getPhoneNumber(phoneCode);
            return Result.OK(phoneNumber);
        }catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    private static final String API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
    public String getPhoneNumber(String code) throws Exception {
        URL url = new URL(API_URL + "?access_token=" + this.getAccessToken());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; utf-8");
        conn.setRequestProperty("Accept", "application/json");
        conn.setDoOutput(true);

        JSONObject jsonInput = new JSONObject();
        jsonInput.put("code", code);

        try (DataOutputStream os = new DataOutputStream(conn.getOutputStream())) {
            byte[] input = jsonInput.toString().getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            //获取手机号码
            return response.toString();
        }
    }

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    public  String getAccessToken() throws Exception {
        String requestUrl = String.format(TOKEN_URL, mpAppId, mpAppSecret);
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }

            org.json.JSONObject jsonResponse = new org.json.JSONObject(response.toString());
            return jsonResponse.getString("access_token");
        }
    }


}
