package com.ff.weijinxiao.controller;

import com.ff.weijinxiao.util.MD5;
import com.ff.weijinxiao.util.WXUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.util.*;

@RestController
@RequestMapping(value = "api/wxapp")
public class WechatControoler {
    public static String appid = "wx3d48d376faa3e9fb";
    public static String appsecret = "97193e51eb0b8474f5259bc5be874e30";

    /**
     * code转openid
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/openid")
    @ResponseBody
    public Map<String, String> getOpenid(String code) {
        Map<String, String> result = new HashMap<String, String>();
        Map<String, Object> data = getSessionKey(code);
        if (data != null && data.containsKey("openid")) {
            result.put("result", "1");
            result.put("openid", data.get("openid").toString());
            if (data.containsKey("unionid")) {
                result.put("unionid", data.get("unionid").toString());
            }
        } else {
            result.put("result", "0");
        }
        return result;
    }


    public static String getsign(Map<String, Object> map, String apikey) {

        Collection<String> keyset = map.keySet();
        List<String> list = new ArrayList<String>(keyset);

        // 对key键值按字典升序排序
        Collections.sort(list);
        String result = "";
        for (String s : list) {
            if (map.get(s) != null) {
                result += s + "=" + map.get(s) + "&";
            }
        }
        result += "key=" + apikey;
        // if (result.endsWith("&")) {
        // result = result.substring(0, result.length() - 1);
        // }
        result = MD5.GetMD5Code(result).toUpperCase();
        return result;
    }

    public static Map<String, Object> getSessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
                + "&js_code=" + code + "&grant_type=authorization_code";
        return WXUtil.parseJSON2Map(WXUtil.sendGet(url, null));
    }

    public static String getRandomString(int length) {
        String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(randString.charAt((int) (Math.random() * 35 + 1)));
        }
        return sb.toString();
    }


    public static Map<String, String> payRefund(String appid, String mchid, String apikey, String wxcode, String mycode, int totalprice,
                                                int refundprice) throws FileNotFoundException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appid", appid);
        map.put("mch_id", mchid);
        map.put("nonce_str", getRandomString(10));
        if (wxcode != null) {
            map.put("transaction_id", wxcode);
        }
        if (mycode != null) {
            map.put("out_trade_no", mycode);
        }
        String tkcode = "tk" + (System.currentTimeMillis() + "").substring(0, 10) + getRandomString(4);
        map.put("out_refund_no", tkcode);
        map.put("total_fee", totalprice);
        map.put("refund_fee", refundprice);
        //map.put("op_user_id", wca.getMcid());
        map.put("refund_fee_type", "CNY");
        String sign = WXUtil.getsign(map, apikey);
        map.put("sign", sign);
        String dada = WXUtil.getSendText(map);
        System.out.println("========" + dada);
        System.out.println(dada);
        Map<String, String> result = WXUtil.sendPostWithCA("https://api.mch.weixin.qq.com/secapi/pay/refund", dada,
                mchid,
                geCaFilePath());
        // Util.getRootPath() + File.separator +
        // wca.getCafilepath().replaceAll("/", "\\" + File.separator);
        Map<String, String> data = new HashMap<String, String>();
        if (result != null && result.containsKey("return_code") && result.get("return_code").equals("SUCCESS")
                && result.containsKey("result_code") && result.get("result_code").equals("SUCCESS")) {
            data.put("result", "1");
            data.put("tkcode", tkcode);
            data.put("prepayid", result.get("refund_id"));
            data.put("codeurl", result.get("code_url"));
        } else {
            System.out.println("======退款失败=====");

            if (result != null && result.containsKey("result_code") && result.get("result_code").equals("FAIL")
                    && result.containsKey("err_code") && result.get("err_code").equals("NOTENOUGH")) {
                //未结算金额不足导致退款失败，尝试其他账号退款
                map.put("refund_account", "REFUND_SOURCE_RECHARGE_FUNDS");//改用可用余额退款
                dada = WXUtil.getSendText(map);
                System.out.println("====again====" + dada);
                System.out.println(dada);
                result = WXUtil.sendPostWithCA("https://api.mch.weixin.qq.com/secapi/pay/refund", dada,
                        mchid, geCaFilePath());
                if (result != null && result.containsKey("return_code") && result.get("return_code").equals("SUCCESS")
                        && result.containsKey("result_code") && result.get("result_code").equals("SUCCESS")) {
                    data.put("result", "1");
                    data.put("tkcode", tkcode);
                    data.put("prepayid", result.get("refund_id"));
                    data.put("codeurl", result.get("code_url"));
                } else {
                    System.out.println("===again===退款失败=====");
                    data.put("result", "0");
                }
            }else {
                data.put("result", "0");//其他错误，非余额不足退款错误
            }

        }
        return data;
    }

    public static String geCaFilePath() throws FileNotFoundException {
        return "/opt/p12/1516214821_20181111_cert.p12";


    }


}
