package com.nbclass.activity.controller.casesfirst;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nbclass.activity.model.WeiXiUser;
import com.nbclass.activity.service.WxService;
import com.nbclass.exception.ParameterException;

import com.nbclass.util.HttpUtils;
import com.nbclass.util.JWTUtils;
import com.nbclass.vo.base.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 微信接口
 * @author gao
 * @datetime 2021年10月14日
 */
@Controller
@RequestMapping("/wx")
public class WxController {

    /**
     * wx的AppID
     */
    private static final String appId = "wx013ea7738ce6991f";

    /**
     * wx的AppSecret
     */
    private static final String AppSecret = "03255f509c6b53cb2b94c9bd21b8aaa8";

    /**
     * 企业微信corpid
     */
    private static final String corpid = "wwc0b239a20872ff25";

    /**
     * 企业微信corpsecret(客户的secret)
     */
    private static final String corpsecret = "VuJ-Sd2X-oUwFUCzzdQfDZDe0Ryb3IbvkczFu8KUP0o";

    @Autowired
    private WxService wxService;

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "loginPage";
    }

    @RequestMapping("/weixinLogin")
    public String weixinLogin(){
        return "weixinLogin";
    }

    @RequestMapping("/demo")
    public String demo(){
        return "demo";
    }

    /**
     * 获取微信用户信息
     * @param request
     * @return
     */
    @GetMapping("/getWxUser")
    @ResponseBody
    public Result getWxUser(HttpServletRequest request){
        if(request.getParameter("code")==null){
            throw new ParameterException("code参数异常!");
        }

        //获取code
        String code = request.getParameter("code");

        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url,appId,AppSecret,code);
        JSONObject jsonObject = HttpUtils.httpGet(url);

        if(jsonObject.getString("access_token")==null){
            throw new ParameterException("access_token参数异常!");
        }

        if(jsonObject.getString("openid")==null){
            throw new ParameterException("openid参数异常!");
        }

        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        //String wxUnionId = jsonObject.getString("unionid");

        //数据库查询是否有该openid，如果有直接从数据库获取用户信息
        int result = wxService.getOpenId(openid);
        if(result == 0){
            //获取用户信息
            String url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
            url2 = String.format(url2,accessToken,openid);
            JSONObject jsonUser = HttpUtils.httpGet(url2);
            WeiXiUser weiXiUser = jsonUser.toJavaObject(WeiXiUser.class);
            //添加用户信息到数据库
            wxService.saveWxUser(weiXiUser);
        }
        //数据库获取用户信息
        WeiXiUser weiXiUser = wxService.getWxUser(openid);
        WeiXiUser user = new WeiXiUser();
        user.setId(weiXiUser.getId());
        user.setOpenid(weiXiUser.getOpenid());

        String token = "";

        //生成token
        String subject = JSON.toJSONString(user);
        try {
            token = JWTUtils.createJWT(UUID.randomUUID().toString(), "admin", subject, 7200 * 1000, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("nickname",weiXiUser.getNickname());
        map.put("headimgurl",weiXiUser.getHeadimgurl());


        //获取企业微信的access_token
       /* String qyWxUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
        qyWxUrl = String.format(qyWxUrl,corpid,corpsecret);
        JSONObject qyWxJson = HttpUtils.httpGet(qyWxUrl);
        if(qyWxJson.getString("access_token")==null){
            throw new ParameterException("企业微信的access_token参数异常!");
        }
        String qyWxAccessToken = qyWxJson.getString("access_token");

        //获取客户群列表
        String qyWxListUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token=%s";
        qyWxListUrl = String.format(qyWxListUrl,qyWxAccessToken);
        String limit = "{\"limit\": 1000}";
        String s1 = HttpUtil.doPostJson(qyWxListUrl, limit);
        JSONObject jsonObject = JSON.parseObject(s1);

        if(jsonObject.getString("group_chat_list")==null){
            throw new ParameterException("企业微信的chatId参数异常!");
        }

        String s = jsonObject.toJSONString();
        System.out.println(s);
        Map groupChats = JSONObject.parseObject(s,Map.class);
        JSONArray jsonArray = JSONArray.parseArray(groupChats.get("group_chat_list").toString());
        //获取chatId
        String chatId = jsonArray.getJSONObject(0).getString("chat_id");

        //获取客户群详情
        String khUrl = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=%s";
        khUrl = String.format(khUrl,qyWxAccessToken);
        String chat_id = "{\"chat_id\": \""+chatId+"\"}";
        String s2 = HttpUtil.doPostJson(khUrl, chat_id);
        System.out.println(s2);
        String group_chat = JSON.parseObject(s2).get("group_chat").toString();
        GroupChat groupChat = JSONObject.parseObject(group_chat, GroupChat.class);
        System.out.println(groupChat);
        List<MemberList> memberLists = groupChat.getMember_list();
        List<String> list = new ArrayList<>();
        for (MemberList memberList : memberLists) {
           *//* if(wxUnionId.equals(memberList.getUnionid())){

            }*//*

            System.out.println(memberList.getUnionid());
        }*/


        return Result.success(map);
    }

    /**
     * 查看用户基础信息
     * @return
     */
    @GetMapping("/getUserBasicData")
    @ResponseBody
    public Result getUserBasicData(HttpServletRequest request){
        String token = request.getHeader("token");
        String userId = JWTUtils.getUserId(token);
        WeiXiUser weiXiUser = wxService.getUserBasicData(Long.parseLong(userId));
        return Result.success(weiXiUser);
    }

    /**
     * 更新用户基础信息
     * @param weiXiUser
     * @return
     */
    @PostMapping("/updateBasicData")
    @ResponseBody
    public Result updateBasicData(WeiXiUser weiXiUser, HttpServletRequest request){
        String token = request.getHeader("token");
        String userId = JWTUtils.getUserId(token);
        weiXiUser.setId(Long.parseLong(userId));
        weiXiUser.setUpdateTime(new Date());
        wxService.updateBasicData(weiXiUser);
        return Result.success();
    }


}
