package com.yihu.wlyy.web.wx;

import com.yihu.wlyy.service.weixin.WeiXinCoreService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by lyr on 2016/08/11.
 */
@Controller
@RequestMapping(value = "/weixin")
@Api(description = "微信")
public class WechatCoreController extends WeixinBaseController {

    @Autowired
    private WeiXinCoreService weiXinCoreService;

    /**
     * 微信接口验证
     *
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public void checkSignature(HttpServletRequest request, HttpServletResponse response) {
        try {
            String signature = request.getParameter("signature").toString();
            String timestamp = request.getParameter("timestamp").toString();
            String nonce = request.getParameter("nonce").toString();
            String echostr = request.getParameter("echostr").toString();

            if(validate(signature,timestamp,nonce)){
                // 验证成功，返回验证码
                response.getWriter().print(echostr);
            }else{
                // 验证失败
                response.setStatus(401);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 服务器错误
            response.setStatus(500);
        }
    }

    /**
     * 接收微信推送消息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public void receiveMessages(HttpServletRequest request, HttpServletResponse response){
        try{
            String signature = request.getParameter("signature").toString();
            String timestamp = request.getParameter("timestamp").toString();
            String nonce = request.getParameter("nonce").toString();

            if(validate(signature,timestamp,nonce)){
                String xmlStr =  weiXinCoreService.messageProcess(request,getAccessToken());

                if(xmlStr == "error"){
                    // 服务器错误
                    response.setStatus(500);
                }else{
                    // 返回消息
                    response.getWriter().print(xmlStr);
                }
            }else{
                // 验证失败
                response.setStatus(401);
            }
        }catch (Exception e){
            e.printStackTrace();
            // 服务器错误
            response.setStatus(500);
        }
    }

    /**
     * 微信推送消息验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static boolean validate(String signature,String timestamp,String nonce) throws NoSuchAlgorithmException {
        String token = SystemConf.getInstance().getSystemProperties().getProperty("wechat_token");
        // 字典序排序
        String[] array = new String[]{token, timestamp, nonce};
        Arrays.sort(array);

        //连接字典序排序后字符串
        String content = "";
        for (String str : array) {
            content += str;
        }

        // 解析
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        String decodeStr = "";
        byte[] bytes = md.digest(content.getBytes());
        decodeStr = byteToStr(bytes);

        if(StringUtils.isNotEmpty(decodeStr) && decodeStr.equals(signature.toUpperCase())){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 将字节数组转换为字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 微信菜单创建
     *
     * @return
     */
    @RequestMapping(value = "/menu/create")
    @ResponseBody
    public String createMenuTest(){
        try{
            String filePath = WechatCoreController.class.getResource("/").getPath() +
                    File.separator + "weixin_menu.txt";
            String url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + getAccessToken();
            // 读取微信菜单配置文件
            InputStreamReader reader = new InputStreamReader(new FileInputStream(filePath),"utf-8");
            BufferedReader bufferedReader = new BufferedReader(reader);
            String params = "";
            String readTxt = "";
            // 读取微信菜单
            while((readTxt = bufferedReader.readLine()) != null){
                System.out.println(readTxt);
                params += readTxt;
            }

            bufferedReader.close();
            reader.close();
            // 替换服务器地址、APPID
            params = params.replaceAll("server_url",SystemConf.getInstance().getSystemProperties().getProperty("wechat_base_url"));
            params = params.replaceAll("appId",SystemConf.getInstance().getSystemProperties().getProperty("appId"));
            // 请求微信接口创建菜单
            String jsonStr = HttpUtil.sendPost(url, params);
            JSONObject result = new JSONObject(jsonStr);
            if(result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")){
                return write(200,"创建成功!","data",jsonStr);
            }else{
                return write(-1,"创建失败!","data",jsonStr);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"创建失败");
        }
    }

    /**
     * 将字节转换为字符
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
}
