package com.bohuikeji.delivery.backstage.util.capacity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import jodd.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

/**
 *
 * @author Admin
 */
@Slf4j
public class UUPaotuiUtils {


    /**
     * 生产环境
     */
    private static final String APPID="296b9ab0d286439ca87304877b7e24df";
    private static final String APPKEY="324af2a8911f45f58fbb5e9b1b24d35d";
    private static final String ACCOUNT="15391160134 ";
    private static final String OPENID="7ae82c33ab214e1a86c082d18f35f871";
    private static final String BASE_URL="https://openapi.uupt.com/v2_0/";
    public static final String NOTICE_URL="https://os.tcjskd.com/delivery/api/callback/uu/order/notice";

    /**
     * 测试环境
     */
    /*private static final String APPID="ccba8bd4a2d54a2fb6df97e87979f303";
    private static final String APPKEY="2815a7a1f8e3405d81fd6263683ec4e7";
    private static final String OPENID="910a0dfd12bb4bc0acec147bcb1ae246";
    private static final String BASE_URL="http://openapi.test.uupt.com/v2_0/";
    public static final String NOTICE_URL="http://sjh.tcjs.frp.bhynm.net/delivery/api/callback/uu/order/notice";*/

    /**
     * 订单询价
     */
    private static final String API_ORDER_TEST="getorderprice.ashx";
    /**
     * 发布订单
     */
    private static final String API_ORDER_PLACE="addorder.ashx";

    /**
     * 订单增加小费
     */
    private static final String API_ORDER_TIP="payonlinefee.ashx";

    /**
     * 取消订单
     */
    private static final String API_ORDER_CANCEL="cancelorder.ashx";

    /**
     * 查询订单详情
     */
    private static final String API_ORDER_DETAIL="getorderdetail.ashx";

    /**
     * 查询账户余额详情
     */
    private static final String API_ACCOUNT_DETAIL="getbalancedetail.ashx";

    /**
     * 获取已开通的城市列表
     */
    private static final String API_CITY_LIST="getcitylist.ashx";

    /**
     * 查询某城市的计费规则
     */
    private static final String API_CITY_DETAIL="getgoodsweigthlist.ashx";

    /**
     * 获取账户余额充值连接
     */
    private static final String API_ACCOUNT_RECHARGE="getrecharge.ashx";

    /**
     * 单元测试方法
     */
    @Test
    public void test(){
        log.info("UU跑腿开放城市列表：{}",cityList());
        ShanSongUtils.QueryCity();


    }

    /**
     * 订单询价
     * @param params 询价参数，详见UU接口文档：http://open.uupt.com/Doc/wordshow.html?code=getorderprice
     * @return
     */
    public static APIEntity<JSONObject> orderTest(TreeMap<String,String> params){
        return request(API_ORDER_TEST,params);
    }

    /**
     * 下单
     * @param params 订单参数，详见UU接口文档：http://open.uupt.com/Doc/wordshow.html?code=addorder
     * @return
     */
    public static APIEntity<JSONObject> orderPlace(TreeMap<String,String> params){
        return request(API_ORDER_PLACE,params);
    }

    /**
     * 取消订单
     * @param orderNum 订单号
     * @param reason 取消原因
     * @return
     */
    public static APIEntity<JSONObject> orderCancel(String orderNum,String thirdNum,String reason){
        TreeMap<String,String> params=new TreeMap<>();
        params.put("origin_id",orderNum);
        params.put("order_code",thirdNum);
        if (StringUtils.isEmpty(reason)){
            reason="其他";
        }
        params.put("reason",reason);
        return request(API_ORDER_CANCEL,params);
    }

    /**
     * 查询订单详情
     * @param orderNum 系统订单号
     * @param thirdNum UU订单号
     * @return
     */
    public static APIEntity<JSONObject> orderDetail(String orderNum,String thirdNum){
        TreeMap<String,String> params=new TreeMap<>();
        params.put("origin_id",orderNum);
        params.put("order_code",thirdNum);
        return request(API_ORDER_DETAIL,params);
    }

    /**
     * UU订单增加小费
     * @param orderNum
     * @param thirdNum
     * @return
     */
    public static APIEntity<JSONObject> uuAddorderTip(String orderNum, String thirdNum, BigDecimal onlinefee){
        TreeMap<String,String> params=new TreeMap<>();
        params.put("origin_id",orderNum);
        params.put("order_code",thirdNum);
        params.put("onlinefee", String.valueOf(onlinefee));
        return request(API_ORDER_TIP,params);
    }

    /**
     * 查询UU跑腿已开通的城市列表
     * @return
     */
    public static APIEntity<JSONObject> cityList(){
        return request(API_CITY_LIST);
    }


    /**
     * 查询UU跑腿某个城市的计费规则
     * @param cityName 城市名称，例如：西安市
     * @return
     */
    public static APIEntity<JSONObject> cityDetail(String cityName){
        TreeMap<String,String> params=new TreeMap<String,String>();
        params.put("city_name",cityName);
        return request(API_CITY_DETAIL,params);
    }

    /**
     * 查询账户内余额
     * @return
     */
    public static APIEntity<JSONObject> accountDetail(){
        return request(API_ACCOUNT_DETAIL);
    }

    /**
     * 获取账户充值连接
     * @return
     */
    public static APIEntity<JSONObject> accountPayUrl(){return request(API_ACCOUNT_RECHARGE);}




    /**
     * 调用接口，无业务参数
     * @param url 接口地址
     * @return
     */
    private static APIEntity<JSONObject> request(String url){
        return request(url,null);
    }

    /**
     * 请求接口,自动签名
     * @param url 接口地址
     * @param params 业务参数
     * @return 返回接口DATA数据
     */
    private static APIEntity<JSONObject> request(String url, TreeMap<String,String> params){
        String resStr= HttpRequest.post(BASE_URL+url).query(signParams(params)).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE,"UTF-8").send().bodyText();
        if (StringUtils.isBlank(resStr)){
            log.error("【UU跑腿开放平台】接口：{},返回：{}",url,resStr);
            throw new RuntimeException("闪送开放平台，接口未返回数据！");
        }
        JSONObject resJson= JSON.parseObject(resStr);
        if (!"ok".equals(resJson.getString("return_code"))){
            log.error("【UU跑腿开放平台请求失败】接口：{},返回：{}",url,resStr);
            return APIEntity.fail(resStr);
        }
        log.error(resStr);
        return APIEntity.success(resJson);
    }

    /**
     * 对参数进行签名
     * @param params
     * @return
     */
    private static TreeMap<String,String> signParams(TreeMap<String,String> params){
        if (params==null){
            params=new TreeMap<>();
        }
        params.put("nonce_str", RandomStringUtils.randomAlphanumeric( 24 ));
        params.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        params.put("openid",OPENID);
        params.put("appid",APPID);
        StringBuilder builder=new StringBuilder();
        params.forEach((k,v)->{
            if (StringUtils.isNotBlank(v)){
                builder.append(k);
                builder.append("=");
                builder.append(v);
                builder.append("&");
            }
            else {
                log.error("参数：{}={}",k,v);
            }
        });
        builder.append("key=");
        builder.append(APPKEY);
        String paramStr=builder.toString().toUpperCase(Locale.ROOT);
        String sign=DigestUtils.md5DigestAsHex(paramStr.getBytes(StandardCharsets.UTF_8)).toUpperCase(Locale.ROOT);
        log.info("签名：{}",sign);
        params.put("sign",sign);
        log.error("#################################UU跑腿请求参数开始##############################");
        params.forEach((k,v)->{
            log.error("{}={}",k,v);
        });
        log.error("#################################UU跑腿请求参数结束##############################");
        return params;
    }
}
