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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.util.OrderUtils;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.utils.NumberUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import jodd.http.HttpRequest;
import jodd.net.MimeTypes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.checkerframework.checker.units.qual.K;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 快递100 API开放平台
 * @author Admin
 */
@Slf4j
public class KDHundredUtils {

    public static String KEY="DxkXkCJu7055";
    public static String SECRET="4b99fd00c4e64d0894184d01259c5664";//密钥
    private static String BASE_SHAXIANG="https://api.kuaidi100.com";//快递100沙箱  https://test.tcjskd.com/delivery/api/callback/kd/order/notice
    private static String BASE_ZHENGSHI="https://poll.kuaidi100.com";//快递100正式  https://test.tcjskd.com/delivery/api/callback/kd/order/notice

    /**
     * 计费查询
     */
    //private static final String ORDER_INQUIRY =BASE_ZHENGSHI+"/order/borderapi.do";
    /**
     * 下单
     * 沙箱
     */
    //private static final String ORDER_PLACE="https://api.kuaidi100.com/apiMock/border";
    /**
     * 下单
     * 正式
     */
    private static final String ORDER_PLACE="https://poll.kuaidi100.com/order/borderapi.do";
    /**
     * 商家订单详情接口
     */
    private static final String ORDER_INFO="https://order.kuaidi100.com/order/borderapi.do";


    /**
     * 订单询价
     * @param order
     * @return
     */
    public static JSONObject kdOrderInquiry(TOrder order){
        log.error("【同城急送订单号：】订单:{}",order.getOrderNum());
        JSONObject data=orderInquiry(order);
        log.error("【快递100订单参数：】订单:{}，参数：{}",order.getOrderNum(),data);
        return request(ORDER_PLACE,data,"price");
    }

    /**
     * 订单推送
     * @param order
     * @return
     */
    public static JSONObject kdOrderConvert(TOrder order){
        log.error("【同城急送订单号：】订单:{}",order.getOrderNum());
        JSONObject data=orderConvert(order);
        log.error("【快递100订单参数：】订单:{}，参数：{}",order.getOrderNum(),data);
        return request(ORDER_PLACE,data,"bOrder");
    }

    /**
     * 订单询价参数
     * @param order
     * @return
     */
    private static JSONObject orderInquiry(TOrder order){
        AddressVo mailingAddress=order.getMailingAddress().fillAddress();
        AddressVo receiptAddress=order.getReceiptAddress().fillAddress();
        JSONObject map=new JSONObject();
        map.put("kuaidicom",getType("圆通"));
        //寄件地址
        map.put("sendManPrintAddr",mailingAddress.getProvince()+mailingAddress.getCity());
        //收件地址
        map.put("recManPrintAddr",receiptAddress.getProvince()+receiptAddress.getCity());
        map.put("weight",order.getCargoWeight());
        map.put("serviceType",serviceType("圆通"));
        return map;
    }

    /**
     * 订单转快递100格式
     * @param order
     * @return
     */
    private static JSONObject orderConvert(TOrder order){
        AddressVo mailingAddress=order.getMailingAddress().fillAddress();
        AddressVo receiptAddress=order.getReceiptAddress().fillAddress();
        JSONObject orderJs=new JSONObject();
        orderJs.put("kuaidicom",getType("圆通"));
        //寄件地址
        orderJs.put("sendManName",order.getMailingName());
        orderJs.put("sendManMobile",order.getMailingPhone());
        orderJs.put("sendManPrintAddr",mailingAddress.getCity()+mailingAddress.getArea()+mailingAddress.getAddress()+mailingAddress.getDetail());
        //收件地址
        orderJs.put("recManName",order.getReceiptName());
        orderJs.put("recManMobile",order.getReceiptPhone());
        orderJs.put("recManPrintAddr",receiptAddress.getCity()+receiptAddress.getArea()+receiptAddress.getAddress()+receiptAddress.getDetail());
        //订单消息回调地址
        orderJs.put("callBackUrl","https://os.tcjskd.com//delivery/api/callback/kd/order/notice");
        orderJs.put("cargo",order.getCargoName());
        orderJs.put("weight",order.getCargoWeight().toString());
        orderJs.put("valinsPay",order.getWorthName());
        orderJs.put("remark",order.getOrderRemarks());
        String orderPickStr=order.getPickTime();
        if (orderPickStr.contains("今天")){
            orderJs.put("dayType","今天");
        }
        if (orderPickStr.contains("明天")){
            orderJs.put("dayType","明天");
        }
        if (orderPickStr.contains("后天")){
            orderJs.put("dayType","后天");
        }
        LocalDateTime[] times= OrderUtils.getOrSurplusTimeArea(order.getPickTime());
        log.error("!!!!!!!!!!!!!!!!!!开始时间：{},结束时间：{}",times[0].format(StringUtils.timeFormats),times[1].format(StringUtils.timeFormats));
        orderJs.put("pickupStartTime",times[0].format(StringUtils.timeFormats));
        orderJs.put("pickupEndTime",times[1].format(StringUtils.timeFormats));
        //快递消息回调地址
       /* orderJs.put("op","1");
        orderJs.put("pollCallBackUrl","https://os.tcjskd.com//delivery/api/callback/kd/info/notice");
        orderJs.put("resultv2","3");*/
        return orderJs;
    }

    /**
     * 商家寄件订单详情查询接口
     * @param taskId
     * @return
     */
    public static JSONObject getOrderInfo(String taskId){
        JSONObject dat=new JSONObject();
        dat.put("taskId",taskId);
        return request(ORDER_INFO,dat,"detail");
    }

    /**
     * 取消订单
     * @param taskId
     * @param orderId
     * @param cancelMsg
     * @return
     */
    public static JSONObject orderCancel(String taskId,String orderId,String cancelMsg){
        JSONObject dat=new JSONObject();
        dat.put("taskId",taskId);
        dat.put("orderId",orderId);
        dat.put("cancelMsg",cancelMsg);
        return request(ORDER_PLACE,dat,"cancel");
    }

    /**
     * 请求接口,自动签名
     * @param url 接口地址
     * @param data 业务参数
     * @return 返回接口DATA数据
     */
    private static JSONObject request(String url, JSONObject data,String method){
        String resStr= HttpRequest.post(url).query(getSignParams(data,method)).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE,"UTF-8").send().bodyText();
        log.error("##########%%%%%%%%%%%#############:{}",resStr);
        /*if (StringUtils.isBlank(resStr)){
            log.error("【快递100开放平台】接口：{},返回：{},数据信息:{}",url,resStr,data);
            throw new RuntimeException("快递100开放平台，接口未返回数据！");
        }
        JSONObject resJson=JSON.parseObject(resStr);
        if (resJson.getIntValue("returnCode")!=200){
            log.error("【快递100开放平台】接口：{},返回：{}",url,resStr);
            return resJson;
        }*/
        JSONObject resJson=JSON.parseObject(resStr);
            log.error("【快递100开放平台】接口：{},返回：{},数据信息:{}",url,resStr,data);
        return resJson;
    }

    /**
     * 快递公司编码
     * @return
     */
    public static String getType(String type) {
        String kdCompanyNum;
        switch (type){
            case "京东":
                kdCompanyNum="jd";break;
            case "德邦":
                kdCompanyNum="debangkuaidi";break;
            case "顺丰":
                kdCompanyNum="shunfeng";break;
            case "极兔":
                kdCompanyNum="jtexpress";break;
            case "圆通":
                kdCompanyNum="yuantong";break;
            case "申通":
                kdCompanyNum="shentong";break;
            case "中通":
                kdCompanyNum="zhongtong";break;
            case "韵达":
                kdCompanyNum="yunda";break;
            default:
                return null;
        }
        return kdCompanyNum;
    }

    /**
     * 业务类型参数表
     * @return
     */
    public static String serviceType(String type) {
        String serviceType;
        switch (type){
            case "京东":
                serviceType="特惠送";break;
            case "德邦":
                serviceType="标准快递";break;
            case "顺丰":
                serviceType="顺丰标快";break;
            case "极兔":
                serviceType="标准快递";break;
            case "圆通":
                serviceType="标准快递";break;
            case "申通":
                serviceType="标准快递";break;
            case "中通":
                serviceType="标准快递";break;
            case "韵达":
                serviceType="标准快递";break;
            default:
                return null;
        }
        return serviceType;
    }

    /**
     * 闪送公共参数
     * @param data
     * @param method
     * @return
     */
    private static Map<String,String> getSignParams(JSONObject data,String method){
        String t = String.valueOf(System.currentTimeMillis());
        Map<String,String> params=new TreeMap<>();
        params.put("key",KEY);
        params.put("sign",getSign(data,t));
        params.put("t",t);
        params.put("param",data.toJSONString());
        params.put("method",method);
        return  params;
    }
    /**
     * 生成签名
     * @param data
     * @param t
     * @return
     */
    public static String getSign(JSONObject data,String t) {
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append(data);
        stringBuilder.append(t);
        stringBuilder.append(KEY);
        stringBuilder.append(SECRET);;
        String sign = DigestUtils.md5DigestAsHex(stringBuilder.toString().getBytes(StandardCharsets.UTF_8)).toUpperCase(Locale.ROOT);
        return sign;
    }
}
