package com.supplier.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.supplier.jwt.JWTUtil;
import com.supplier.model.Supplier;
import com.supplier.model.User;
import com.supplier.service.PersonalServce;
import com.supplier.util.ParsingToken;
import com.supplier.vx.WxLogin;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * wx登录
 */
@Slf4j
@Controller
@RequestMapping("/wx/login")
public class WXLoginController {

    @Autowired
    private WxLogin wxLogin;

    @Autowired
    private PersonalServce personalServce;

    /**
     * 普通用户微信登录
     * @param code 参数
     */
    @RequestMapping("/notify/code")
    @ResponseBody
    public Map<String, Object> notifyCode(String code, String type) {
        System.out.println(code);
        //获取回调地址中的code
        Map<String, Object> map = new HashMap<>();
        try{
            Map<String, Object> wxMap = wxLogin(code, type); //微信回调数据
            //调用成功
            if(wxMap.get("msg") == "200"){
                JSONObject jsonObject1 = (JSONObject) wxMap.get("data");
                int sex = Integer.parseInt(jsonObject1.get("sex").toString()) == 0 ? 1 : 2;
                User user = new User()
                        .setSex(sex + "")
                        .setWxid(jsonObject1.getString("unionid"))
                        .setCity(jsonObject1.getString("city"))
                        .setHeadpir(jsonObject1.getString("headimgurl"))
                        .setName(jsonObject1.getString("nickname"))
                        .setWxtoken((String) wxMap.get("accesstoken"))
                        .setWxRefreshToken((String) wxMap.get("refreshtoken"))
                        .setWxOpenid((String) wxMap.get("openId"))
                        .setPhone("");
                //查询指定微信用户是否存在
                List<User> list = personalServce.seleceWxUserCount(user);
                if(list.size() == 0){
//                    personalServce.addWXUser(user);
//                    int wxID = personalServce.geThisUserID(user.getWxid());
//                    user.setCode(SerialNumber("CUS", wxID + "")).setId(wxID + "");
//                    personalServce.updateUserWx(user);
                } else {
                    user.setCode(list.get(0).getCode()).setId(list.get(0).getId());
                    personalServce.updateUserWx(user);
                    user = personalServce.seleceWxUserCount(user).get(0);
                    //生成token传参
                    Map<String, String> payload = new HashMap<>();
                    payload.put("code", user.getCode());
                    // 生成jwt的令牌
                    String token = JWTUtil.getToken(payload);
                    user.setToken(token);
                }
                map.put("data", user);
                map.put("msg", "200");
            } else { //失败
                return wxMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "微信登录异常");
        }
        return map;
    }

    /**
     * 供应商绑定微信
     * @param code  参数
     * @param request 参数
     * @return 返回结果
     */
    @RequestMapping("/notify/codeSupplier")
    @ResponseBody
    public Map<String, Object> codeSupplier(String code, String type, HttpServletRequest request) {
        //获取回调地址中的code
        Map<String, Object> map = new HashMap<>();
        try{
            Map<String, Object> wxMap = wxLogin(code, type); //微信回调数据
            //调用成功
            if(wxMap.get("msg") == "200"){
                JSONObject jsonObject1 = (JSONObject) wxMap.get("data");
                //获取token
                Map<String, Object> userMap = ParsingToken.tokenParsing(request);
                Supplier supplier = new Supplier()
                        .setWxid(jsonObject1.getString("unionid"))
                        .setWxtoken((String) wxMap.get("accesstoken"))
                        .setWxRefreshToken((String) wxMap.get("refreshtoken"))
                        .setWxOpenid((String) wxMap.get("openId"))
                        .setCode((String) userMap.get("code"));
                personalServce.updatePhone(supplier);//给指定供应商添加微信标识
                map.put("msg", "200");
            } else { //失败
                return wxMap;
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "500");
            map.put("errMsg", "微信登录异常");
        }
        return map;
    }

    /**
     * 用户编号
     * @param id
     * @return
     */
    public static String SerialNumber(String letter, String id){
        for(int i = 0; i < 8 - id.length(); i++){
            letter = letter + "0";
        }
        return letter + id;
    }

    /**
     * 获取微信信息
     * @param code 参数
     */
    public Map<String, Object> wxLogin(String code, String type) throws IOException {
        Map<String, Object> map = new HashMap<>();
        CloseableHttpClient client = HttpClients.createDefault();
        String appId = "";
        String appSecret = "";
        if(type.equals("app")){
            appId = wxLogin.getAppIdMobile();
            appSecret = wxLogin.getAppSecretMobile();
        } else {
            appId = wxLogin.getAppId();
            appSecret = wxLogin.getAppSecret();
        }
        // 定义地址
        String token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ appId +"&secret="+ appSecret +"&code="+ code +"&grant_type=authorization_code";
        HttpGet httpGet = new HttpGet(token_url);
        CloseableHttpResponse closeableHttpResponse = client.execute(httpGet);
        if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String strResult = EntityUtils.toString(closeableHttpResponse.getEntity(),"UTF-8"); //此处设定编码格式
            JSONObject jsonObject = JSON.parseObject(strResult);
            //获取token
            String accesstoken = jsonObject.getString("access_token"); // 获取微信开放平台票据号
            String refreshtoken = jsonObject.getString("refresh_token");//获取微信开放平台的刷新token
            String openId = jsonObject.getString("openid");  //获取登录微信的唯一凭证号
            map.put("accesstoken", accesstoken);
            map.put("refreshtoken", refreshtoken);
            map.put("openId", openId);
            //获取用户信息
            String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ accesstoken +"&openid="+ openId;  // 该url用于从微信那里获取用户数据
            HttpGet httpGet1 = new HttpGet(url);
            CloseableHttpResponse closeableHttpResponse1 = client.execute(httpGet1);
            if (closeableHttpResponse1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult1 = EntityUtils.toString(closeableHttpResponse1.getEntity(),"UTF-8"); //此处设定编码格式
                JSONObject jsonObject1 = JSON.parseObject(strResult1);
                map.put("msg", "200");
                map.put("data", jsonObject1);
            } else {
                map.put("msg", "500");
                map.put("errMsg", "请求出错");
            }
        } else {
            map.put("msg", "500");
            map.put("errMsg", "请求出错");
        }
        return map;
    }
}
