package com.izouma.weixin.util;

import com.izouma.weixin.dto.WxPaySendData;
import com.izouma.weixin.wxpay.MyConfig;
import com.izouma.weixin.wxpay.WXPay;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;


/**
 * 微信工具类
 *
 * @author
 */
@Service
public class WeixinUtil {


    private static Logger logger = Logger.getLogger(WeixinUtil.class);


    /**
     * 统一下单
     *
     * @param data
     * @return
     */
    public static Map<String, String> unifiedOrder(WxPaySendData data) {

        Map<String, String> map = new HashMap<String, String>();
        try {
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("device_info", data.getDevice_info());
            parameters.put("body", data.getBody());
            parameters.put("out_trade_no", data.getOut_trade_no());
            parameters.put("notify_url", data.getNotify_url());
            parameters.put("total_fee", String.valueOf(data.getTotal_fee()));
            parameters.put("trade_type", data.getTrade_type());
            parameters.put("spbill_create_ip", data.getSpbill_create_ip());
            if (data.getOpenid() != null) {

                parameters.put("openid", data.getOpenid());
            }
            parameters.put("attach", data.getAttach());


            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);

            map = wxpay.unifiedOrder(parameters);
            //System.out.println(map);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信统一下单异常：", e);
        }

        return map;
    }

    public static Map<String, String> orderQuery(String outTradeNo) {

        Map<String, String> map = new HashMap<String, String>();


        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", outTradeNo);

        try {
            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);

            map = wxpay.orderQuery(data);
            //System.out.println(map);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信查询订单异常：", e);
        }

        return map;
    }


    public static String create_timestamp() {

        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static String create_nonce_str() {

        return UUID.randomUUID().toString().replace("-", "");
    }


    public static JSONObject loadJSON(String url) {

        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return new JSONObject(json.toString());
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {

        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        System.out.println(string1);

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    /**
     * 生成订单号
     *
     * @return
     */
    public static String create_out_trade_no() {

        return Long.toString(System.currentTimeMillis() / 1000) + getRandomNum(10);

    }

    /**
     * 生成特定位数的随机数字
     *
     * @param length
     * @return
     */
    public static String getRandomNum(int length) {

        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }


    public static String byteToHex(final byte[] hash) {

        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }


    /**
     * <p>获取ip地址。</p>
     *
     * @return
     */
    public static String getHostAdderss() {

        InetAddress ia = null;
        try {
            ia = ia.getLocalHost();

            String localname = ia.getHostName();
            String localip = ia.getHostAddress();
            System.out.println("本机名称是：" + localname);
            System.out.println("本机的ip是 ：" + localip);
            return localip;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String getIpAdderss(HttpServletRequest request) {

        InetAddress ia = null;
        try {
            // 获取客户端IP地址，考虑反向代理的问题
            String ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                        ip = inet.getHostAddress();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (!StringUtils.isEmpty(ip) && ip.length() > 15) {
                ip = ip.substring(0, ip.indexOf(","));
            }
            return ip;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


}
