package com.mvc.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.mvc.model.weixin.WxUser;
import com.mvc.utils.WeChatUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;


//@RequestMapping("/WxUserAction")
//@Controller
public class WxUserAction {

    @Value("${wxMini.appId}")
    public String appId;
    @Value("${wxMini.secret}")
    public String secret;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject login(@RequestBody WxUser user){
        String code = user.getCode();
        JSONObject object=new JSONObject();
        if(code == "" || "".equals(code)){
            object.put("code",300);
            object.put("msg","code不能为空!");
            return object;
        }
        else {
            //微信接口服务,通过调用微信接口服务中jscode2session接口获取到openid和session_key
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            String str = WeChatUtil.httpRequest(url, "GET", null); //调用工具类解密
            JSONObject jsonObject=JSONObject.parseObject(str);
            String openid = (String) jsonObject.get("openid");
            if(openid != null && !"".equals(openid)){
                //登录成功
                WxUser userVo=new WxUser();
                userVo.setNickName(user.getNickName());
                userVo.setAvatarUrl(user.getAvatarUrl());
                userVo.setOpenId(openid);
                userVo.setGender(user.getGender());
                userVo.setFirstLoginTime(new Date(System.currentTimeMillis()));
                userVo.setLastLoginTime(new Date(System.currentTimeMillis()));
              //  User us = userService.queryById(openid);
                if(userVo != null) {
                    //不是首次登录，更新用户信息
                    //userVo.setId(us.getId());
                    //userService.updateUser(userVo);
                }
                else {
                    //首次登录，存储用户信息
                    //serService.insertUser(userVo);
                }
                object.put("code",200);
                object.put("msg","登录成功!");
                object.put("userInfo",userVo);
                return object;
            }else {
                object.put("code",400);
                object.put("msg","未知错误，请重试!");
                return object;
            }
        }
    }


}


