package com.chuanghai.h3c_reporting.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chuanghai.h3c_reporting.common.exception.BizCodeEnume;
import com.chuanghai.h3c_reporting.common.exception.RRException;
import com.chuanghai.h3c_reporting.common.utils.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取微信绑定手机号
 *
 * @Author 浮生
 * @Date 2023/3/12 14:46
 * @PackageName:com.chuanghai.h3c_reporting.controller
 * @ClassName: WxController
 * @Description: TODO
 * @Version 1.0
 */
@Controller
@RequestMapping("/wx")
public class WxController {

    @Value("${wx.app_id}")
    private String appID;

    @Value("${wx.secret}")
    private String secret;

    private String access_token = "";

    /**
     * 通过code换取用户手机号
     */
    @GetMapping("/getPhone")
    @ResponseBody
    public CommonResult<String> getPhone(String code, String state) {
        if (access_token.equals("")) {
            getAccessToken();
        }
//        System.out.println("access_token  ======>>>" + access_token);
        try {
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            Map<String, String> paramCardNumber = new HashMap<>();
//            paramCardNumber.put("access_token", access_token);
            paramCardNumber.put("code", code);
            HttpEntity<Map<String, String>> requestM = new HttpEntity<>(paramCardNumber, headers);
            String userInfoUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
            ResponseEntity<String> responsem = restTemplate.postForEntity(userInfoUrl, requestM, String.class);

            JSONObject resPhoneInfo = JSON.parseObject(responsem.getBody());

            System.out.println(resPhoneInfo);

            JSONObject phoneInfo = resPhoneInfo.getJSONObject("phone_info");
            String phoneNumber = phoneInfo.get("phoneNumber").toString();

            return CommonResult.ok().setResult(phoneNumber);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(BizCodeEnume.WX_EXCEPTION, "获取用户绑定的手机号失败");
        }
    }

    // 获取access_token
    @Scheduled(cron = "0 59 0/1 * * ?")   // 每1小时59分,执行一次刷新access_token
    public void getAccessToken() {
//        Map<String, String> token = new HashMap<>();
//        token.put("appid", appID);
//        token.put("secret", secret);
//        token.put("grant_type", "client_credential");
        String url = "https://api.weixin.qq.com/cgi-bin/token?" +
                "grant_type=client_credential" +
                "&appid=" + appID +
                "&secret=" + secret;

        RestTemplate restTemplate = new RestTemplate();
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        HttpEntity<Map<String, String>> request = new HttpEntity<>(token, headers);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        JSONObject objParam = JSON.parseObject(responseEntity.getBody());

        for (Map.Entry<String, Object> entry : objParam.entrySet()) {
            Object o = entry.getValue();
            if (o instanceof String) {
                if (entry.getKey().equals("access_token")) {
                    access_token = (String) entry.getValue();
                }
            }
        }
//        System.out.println(access_token);
//        return access_token;
    }

}
