package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.HttpGetUtil;
import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Tag(name = "真·用户接口",description = "用户登录，")
@RestController
public class Demmo {
    @RequestMapping("/index")
    public String first(){
        return "index";
    }
    @Autowired
    private UserMapper userMapper;
    @GetMapping("atlogin")
    @Operation(summary = "真·微信登录接口")

    public Map getOpenId( HttpServletRequest request,
                          HttpServletResponse response,
                          @RequestParam(value = "code", required = false) String code) throws UnsupportedEncodingException {
        response.setContentType("text/html");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map params = new HashMap();
        params.put("appid", "wx954296403ec15396");
        params.put("secret", "3317b29d14270cebb8f4e3521506f285");
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        System.out.println(params);
        String result = HttpGetUtil.httpRequestToString(
                "https://api.weixin.qq.com/sns/jscode2session", params);
        JSONObject jsonObject = JSONObject.parseObject(result);

        String openid = jsonObject.get("openid").toString();
        System.out.println("得到的openid为:"+openid);
        String sessionKey=jsonObject.get("session_key").toString();
        User user = this.userMapper.selectById(openid);
        // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
        String skey = UUID.randomUUID().toString();
        if (user == null) {
            // 用户信息入库
//            String nickName = rawDataJson.getString("nickName");
//            String avatarUrl = rawDataJson.getString("avatarUrl");
//            String gender = rawDataJson.getString("gender");
//            String city = rawDataJson.getString("city");
//            String country = rawDataJson.getString("country");
//            String province = rawDataJson.getString("province");

            user = new User();
            user.setOpenId(openid);
            user.setSkey(skey);
            user.setCreateTime(new Date());
            user.setLastVisitTime(new Date());
            user.setSessionKey(sessionKey);
//            user.setCity(city);
//            user.setProvince(province);
//            user.setCountry(country);
//            user.setAvatarUrl(avatarUrl);
//            user.setGender(Integer.parseInt(gender));
//            user.setNickName(nickName);

            this.userMapper.insert(user);
        } else {
            // 已存在，更新用户登录时间
            user.setLastVisitTime(new Date());
            // 重新设置会话skey
            user.setSkey(skey);
            this.userMapper.updateById(user);
        }
        Map<String, Object> skeymap = new HashMap<String, Object>();
        skeymap.put("skey",skey);

        return  skeymap;
    }
    @RequestMapping("/atbind")
    @Operation(summary = "用户绑定接口")
    public void atbind(@RequestParam(value = "studentnumber",required = true) String studentnumber,
                       @RequestParam(value = "name",required = true) String name,
                       @RequestParam(value = "skey",required = true) String skey)
    {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("skey", skey);
        User user = this.userMapper.selectOne(queryWrapper);
        user.setStudentNumber(studentnumber);
        user.setName(name);
        this.userMapper.updateById(user);
        System.out.println(user);

    }

}
