package com.ruoyi.model.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.applet.pojo.dto.ApiAppletLoginDTO;
import com.ruoyi.applet.utils.wechat.WechatHttpConf;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginApplet;
import com.ruoyi.common.core.domain.model.LoginMember;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.service.IAApiAppletLoginService;
import com.ruoyi.model.service.IAppUsersService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;



@Slf4j
@Service
public class AApiAppletLoginServiceImpl implements IAApiAppletLoginService {


    @Value("${wechat-admin.appId}")
    private String appId;
    @Value("${wechat-admin.secret}")
    private String secret;
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private static final String API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
    @Resource
    private WechatHttpConf wechatHttpConf;
    @Resource
    private IAppUsersService appUsersService;
    @Resource
    private TokenService tokenService;





    //伴宠师-微信授权登录
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public AjaxResult wechatLogin(ApiAppletLoginDTO params){
        if(StringUtils.isEmpty(params.getCode())){
            throw new RuntimeException("参数错误");
        }
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + appId + "&secret="
                + secret+ "&js_code="
                + params.getCode()
                + "&grant_type=authorization_code";
        JSONObject wx_json = wechatHttpConf.getJSONObject(loginUrl);
        String wxOpenid = wx_json.getString("openid");
        if (StringUtils.isBlank(wxOpenid)) {
            throw new RuntimeException("服务繁忙，稍后再试");
        }
        AppUsers appUsers = appUsersService.selectAppUsersByOpenId(wxOpenid);
        if (appUsers == null) {
            //用户信息为空的情况下说明是新的用户
            appUsers = new AppUsers();
            long appletId = System.currentTimeMillis();
            appUsers.setUserId(appletId);
            appUsers.setOpenid(wxOpenid);
            appUsers.setUserName(null);//lzx需要修改到conf中的配置获取
            appUsers.setUserImage("https://image.hhlm1688.com/img/work/log/headImage.png"); //lzx需要修改到conf中的配置获取
            appUsers.setCreateTime(LocalDateTime.now());
            appUsers.setPrice(new BigDecimal(0));
            appUsers.setBaoPrice(new BigDecimal(0));
            appUsers.setUserBcsRole(0); //初始化伴宠师角色
            appUsers.setUserHhRole(0); //初始化合伙人角色
            //初始化合伙人佣金
            appUsers.setMoney(new BigDecimal(0));
//            appUsers.setInvitationCode(String.valueOf(appletId));
            appUsersService.insertAppUsers(appUsers);
            appUsersService.getUserCode(appletId);
            LoginApplet loginApplet = new LoginApplet();
            loginApplet.setAppletId(appletId);
            String appletToken = tokenService.createAppletToken(loginApplet);
            Map<String,Object> map = new HashMap();
            map.put("token",appletToken);
            map.put("userInfo",appUsers);
            return AjaxResult.success("登录成功",map);
        }else{
            LoginApplet loginApplet = new LoginApplet();
            loginApplet.setAppletId(appUsers.getUserId());
            String appletToken = tokenService.createAppletToken(loginApplet);
            Map<String,Object> map = new HashMap();
            map.put("token",appletToken);
            map.put("userInfo",appUsers);
            return AjaxResult.success("登录成功",map);
        }
    }



    //伴宠师-获取手机号码
    @Override
    public AjaxResult bindPhone(ApiAppletLoginDTO params){
        try {
            String phoneNumber = this.getPhoneNumber(params.getCode());
            AppUsers appUsers = appUsersService.selectAppUsersByOpenId(params.getOpenid());
            //如果对象存在
            if (appUsers!=null){
                appUsers.setUserTelephone(phoneNumber);
                appUsersService.updateAppUsers(appUsers);
            }
            return AjaxResult.success(phoneNumber);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }



    //伴宠师-登录页基础信息
    @Override
    public AjaxResult loginConf(){
        Map map = new HashMap();
        map.put("appletName","伴宠师");
        map.put("appletLogoImg","https://image.hhlm1688.com/img/Group%20213084%402x.png");
        map.put("user_xy","用户协议富文本");
        map.put("user_zc","隐私政策富文本");
        return AjaxResult.success("查询成功",map);
    }



    //伴宠师-获取用户基本能信息
    @Override
    public AjaxResult getAppletUserInfo(Long appUserId){
        AppUsers appUsers = appUsersService.selectAppUsersByUserId(appUserId);
        return AjaxResult.success("用户信息",appUsers);
    }




    public  String getAccessToken() throws Exception {
        String requestUrl = String.format(TOKEN_URL, appId, secret);
        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");
        }
    }



    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();
        }
    }







}
