package com.bjtdba.userCenter.controller;

import cn.hutool.json.JSONObject;
import com.bjtdba.userCenter.service.WechatLogOnService;
import com.bjtdba.userCenter.util.AES;
import com.bjtdba.utils.ResponseUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("userCenter_service/userWechatLogOn")
public class WechatLogOnController {

    @Autowired
    private WechatLogOnService wechatLogOnService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//只支持redis五大类型中的字符串类型

    /**
     *   获取到用户的openid
     *   那openid查询自己数据库资料
     * @return
     */
    @GetMapping("/wechat")
    public Object wechatBindPhone(String code){
        return wechatLogOnService.wechatBindPhone(code);
    }
    /**
     * 新版小程序openid接口
     */
    @PostMapping("/")
    public Object wechatUserId(String code){
        return wechatLogOnService.wechatUserId(code);
    }
    /**
     * 获取用户手机号 前端传code  改方法同时获取所需要用到的token
     */
    @PostMapping("/wechatPhone")
    public Object wechatPhone(@RequestBody Map<String,String> map){
        return wechatLogOnService.wechatPhone(map.get("code"));
    }

    /**
     * 微信小程序登录
     * @param
     * @return
     */
    @PostMapping("/miniLogin")
    public Object miniLogin(@RequestBody Map<String,String> map){
        Map<String, Object>  data = new HashMap();
        // 1.解析加密数据
        String phoneNumber = null;
        JSONObject userencryptedData = AES.wxDecrypt(map.get("encryptedData"),map.get("sessionKey"), map.get("iv"));
        if (StringUtils.isNotBlank((String) userencryptedData.get("phoneNumber"))){
            phoneNumber = (String) userencryptedData.get("phoneNumber");
        }
        // 2.自己的登录 逻辑
        JSONObject phoneJson = new JSONObject();
        phoneJson.put("phone", phoneNumber);
        phoneJson.put("mobile_code", "123456");
        phoneJson.put("createTime", System.currentTimeMillis());
        stringRedisTemplate.boundValueOps(phoneNumber+"phoneJson").set(phoneJson.toString());
        data.put("phoneNumber",phoneNumber);
        return ResponseUtil.ok(data);
    }

}
