package com.ruoyi.biz.controller;

import com.ruoyi.biz.domain.vo.ArUserVo;
import com.ruoyi.biz.service.IArUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * app项目
 *
 * @author gwd
 * @date 2023-06-26
 */

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/project")
@Component
@ConfigurationProperties(prefix = "app")
@PropertySource(value = {"classpath:app.yml"})
public class ProjectController extends BaseController {

    private final IArUserService arUserService;

    @Value("${appId}")
    private String appId;

    @Value("${appSecret}")
    private String appSecret;

    /**
     * 获取项目AppId，AppSecret
     */
    @GetMapping("/getAppInfo")
    public R<Map<String,Object>> getAppInfo() {
        Map<String,Object> map = new HashMap<>();
        map.put("appid",appId);
        map.put("appsecret",appSecret);
        return R.ok(map);
    }

    /**
     * 获取openid
     */
    @GetMapping("/getOpenId")
    @ResponseBody
    public R<Map<String,Object>> getOpenId(String code) {
        String json = httpGetSend("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret +"&js_code=" +code +"&grant_type=authorization_code","UTF-8");
        Map<String, Object> map = (Map<String, Object>) JSON.parse(json);
        return R.ok(map);
    }

    public static String httpGetSend(String snedUrl,String encoded) {
        String urlPath = snedUrl;
        StringBuffer sbf = new StringBuffer("");
        BufferedReader reader = null;
        HttpURLConnection uc = null;
        try {
            URL url = new URL(urlPath);
            uc = (HttpURLConnection) url.openConnection();
            uc.setConnectTimeout(30000);
            uc.setReadTimeout(30000);
            uc.setRequestMethod("GET");
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.connect();
            reader = new BufferedReader(new InputStreamReader(uc.getInputStream())); // 读取服务器响应信息
            String line;
            while ((line = reader.readLine()) != null) {
                sbf.append(line);
            }
            reader.close();
            uc.disconnect();
            return sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取User
     */
    @GetMapping("/wxLogin")
    @ResponseBody
    public R<Map<String,Object>> wxLogin(String name, String image, String openId) {
        return R.ok(arUserService.findUser(name, image, openId));
    }

    /**
     * 获取User通过userId
     */
    @GetMapping("/getUser")
    public R<ArUserVo> getUser(Long userId) {
        return R.ok(arUserService.queryById(userId));
    }
}
