package com.yami.shop.delivery.comment.api.paotui;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.delivery.comment.api.paotui.model.Base;
import com.yami.shop.delivery.comment.api.paotui.model.request.*;
import com.yami.shop.delivery.comment.api.paotui.model.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Component
@Slf4j
public class PaoTuiApi {

    private static String host = "http://open.maiyatian.com/";
    private static String appSecret = "b2c8e23bd205857b79f92d57f7c73c7e";
    private static String appKey = "551081";
    @Autowired
    private ShopConfig shopConfig;

    // 添加店铺
    public String shopAdd(StoreAddRequest storeInfoModel) {

        JSONObject data = JSONUtil.parseObj(httpPost(storeInfoModel, "shop/add/"));
        Object shopId = data.get("shop_id");
        return String.valueOf(shopId);
    }

    // 更新店铺
    public String shopUpdate(UpdateShopRequest updateShopModel) {
        JSONObject entries = JSONUtil.parseObj(httpPost(updateShopModel, "shop/update/"));
        return String.valueOf(entries);
    }

    public List<StoreQueryResponse> shopQuery(ShopQueryRequest shopQueryRequest) {
        String string = httpPost(shopQueryRequest, "shop/query/");
        return null;
    }
    public List<StoreQueryResponse> balance() {
        String string = httpPost(null, "/merchant/balance/");
        return null;
    }
//
//    public List<StoreQueryResponse> shopDetail(ShopQueryRequest shopQueryRequest) {
//        String s = httpPost(shopQueryRequest, "shop/detail/");
//        return JSONUtil.toList(s, StoreQueryResponse.class);
//    }

    // 说明：传入订单相关参数进行订单配送下单
    public OrderResponse addOrder(AddOrderRequest orderRequestModel) {
        orderRequestModel.setCallback_url(shopConfig.getDomain().getApiDomainName() + orderRequestModel.getCallback_url());
//        orderRequestModel.setCallback_url("www.baidu.com");
        OrderResponse orderResponseModel = new OrderResponse();
        JSONObject entries = JSONUtil.parseObj(httpPost(orderRequestModel, "order/add/"));
        orderResponseModel = JSONUtil.toBean(entries, OrderResponse.class);
        log.error("paotuiPAI配送结果：{}", orderResponseModel);
        if (!String.valueOf(entries.get("code")).equals("1")) {
            orderResponseModel.setOrigin_id(null);
            return orderResponseModel;
        }
        return orderResponseModel;
    }

    // 说明：查询当前门店该时间段配送到收货地址所需要的预估费用（⚠️注意：先同步创建门店）
    public DeliveryPriceResponse deliveryPrice(DeliveryPriceRequest deliveryPriceRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(deliveryPriceRequest, "order/price/"));
        DeliveryPriceResponse orderResponseModel = JSONUtil.toBean(entries, DeliveryPriceResponse.class);
        return orderResponseModel;
    }

    // 可调用此接口对订单调度，即添加小费功能，用于加快订单接单，提升接单率。
    //⚠️注意：小费添加是以最新请求金额为最终小费的金额，不是累加
    public OrderTipResponse orderTip(OrderTipRequest orderTipRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(orderTipRequest, "order/tip/"));
        OrderTipResponse orderResponseModel = JSONUtil.toBean(entries, OrderTipResponse.class);
        return orderResponseModel;
    }

    // 可调用此接口查询不同状态下的订单列表
    public OrderQueryResponse orderQuery(OrderQueryRequest orderQueryRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(orderQueryRequest, "order/query/"));
        OrderQueryResponse orderResponseModel = JSONUtil.toBean(entries, OrderQueryResponse.class);
        return orderResponseModel;
    }

    // 可调用此接口查询订单以及骑手的相关信息
    public OrderDetailResponse orderDetail(OrderDetailRequest orderDetailRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(orderDetailRequest, "order/detail/"));
        OrderDetailResponse orderResponseModel = JSONUtil.toBean(entries, OrderDetailResponse.class);
        return orderResponseModel;
    }

    // 可调用此接口对订单进行取消操作，如果在骑手接单后取消可能会收取违约金，麦芽田收取违约金是和配送方收取的违约金是等额的
    public CancelOrderRequest orderCancel(CancelOrderRequest cancelOrderRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(cancelOrderRequest, "order/cancel/"));
        CancelOrderRequest orderResponseModel = JSONUtil.toBean(entries, CancelOrderRequest.class);
        return orderResponseModel;
    }

    // 此接口可获取到指定订单的状态信息，用来进行订单状态的查询。
    public OrderStatusResponse deliveryRoute(OrderDetailRequest orderDetailRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(orderDetailRequest, "delivery/route/"));
        OrderStatusResponse orderResponseModel = JSONUtil.toBean(entries, OrderStatusResponse.class);
        return orderResponseModel;
    }

    // 此接口可获取到指定订单的状态信息，用来进行订单状态的查询。
    public DeliveryLocationResponse deliveryLocation(OrderDetailRequest orderDetailRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(orderDetailRequest, "delivery/location/"));
        DeliveryLocationResponse orderResponseModel = JSONUtil.toBean(entries, DeliveryLocationResponse.class);
        return orderResponseModel;
    }

    // 说明：查询当前门店该时间段配送到收货地址所需要的预估费用（⚠️注意：这个场景适用于无门店的概念的用户呼叫跑腿进行取货配送的）
    public DeliveryPriceResponse ordercPrice(DeliveryCpriceRequest deliveryCpriceRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(deliveryCpriceRequest, "order/cPrice/"));
        DeliveryPriceResponse orderResponseModel = JSONUtil.toBean(entries, DeliveryPriceResponse.class);
        return orderResponseModel;
    }

    // 用于c端下单呼叫
    public OrderResponse orderaddWithoutShop(AddWithoutShopRequest addWithoutShopRequest) {
        addWithoutShopRequest.setCallback_url(shopConfig.getDomain().getApiDomainName() + addWithoutShopRequest.getCallback_url());
        JSONObject entries = JSONUtil.parseObj(httpPost(addWithoutShopRequest, "order/addWithoutShop/"));
        OrderResponse orderResponseModel = JSONUtil.toBean(entries, OrderResponse.class);
        return orderResponseModel;
    }

    /**
     * 绑定配送方-顺丰
     *
     * */
    public BindResponse bindTheShipper(BindRequest bindRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(bindRequest, "shop/bindAccount/"));
        BindResponse bindResponse = JSONUtil.toBean(entries, BindResponse.class);
        return bindResponse;
    }
    /**
     * 绑定配送方-顺丰
     *
     * */
    public BindResponse getAuthUrl(BindRequest bindRequest) {
        JSONObject entries = JSONUtil.parseObj(httpPost(bindRequest, "logistic/getAuthUrl/"));
        BindResponse bindResponse = JSONUtil.toBean(entries, BindResponse.class);
        return bindResponse;
    }

    public static void main(String[] args) {
        PaoTuiApi paoTuiApi = new PaoTuiApi();
//        BindRequest bindRequest = new BindRequest()
//                .setOrigin_id("109")
//                .setLogistic("shunfeng");
//        List<Account> account = new ArrayList<>();
//        Account account1 = new Account()
//                .setShunfeng_id("74863879105");
//        account.add(account1);
//        BindResponse bindResponse = paoTuiApi.getAuthUrl(bindRequest);
//        BindResponse bindResponse = paoTuiApi.bindTheShipper(bindRequest);
//        ShopQueryRequest shopQueryRequest = new ShopQueryRequest();
//        shopQueryRequest.setOffset(0);
//        shopQueryRequest.setCount(50);
//        paoTuiApi.shopQuery(shopQueryRequest);

        //订单查询
//        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
//        orderDetailRequest.setOrder_id("2356157330862639039");
//        paoTuiApi.orderDetail(orderDetailRequest);
//
//
//        OrderQueryRequest orderQueryRequest = new OrderQueryRequest();
//        orderQueryRequest.setShopId(6249960);
//        paoTuiApi.orderQuery(orderQueryRequest);
//        ShopQueryRequest shopQueryRequest = new ShopQueryRequest();
//        shopQueryRequest.setOffset(0);
//        shopQueryRequest.setCount(50);
//        paoTuiApi.shopQuery(shopQueryRequest);

        //下单
//            AddOrderRequest addOrderRequest = new AddOrderRequest();
//            addOrderRequest.setShop_id(String.valueOf(109));
//            addOrderRequest.setOrigin_id("1938133514725756928");
//            addOrderRequest.setSubscribe_time(Instant.now().getEpochSecond() + 60 * 60);
//            addOrderRequest.setReceiver_longitude(String.valueOf(106.61854273868924));
//            addOrderRequest.setReceiver_latitude(String.valueOf(26.65018431737428));
//            addOrderRequest.setReceiver_address("贵州省贵阳市观山湖区碧海第一街");
//            addOrderRequest.setReceiver_address_detail("3401");
//            addOrderRequest.setReceiver_name("王一");
//            addOrderRequest.setReceiver_phone("15165016065");
//            addOrderRequest.setGoods_value(new BigDecimal("15.90").intValue() * 100);
//          paoTuiApi.addOrder(addOrderRequest);

          paoTuiApi.balance();

    }

    public List<City> configCity() {
        String s = httpPost(new Base(), "config/city/");

        Gson gson = new Gson();
        Type listType = new TypeToken<List<City>>() {
        }.getType();
        List list = gson.fromJson(s, listType);
        return list;
    }

    public List<District> configDistrict() {
        String s = httpPost(new Base(), "config/district/");
        Gson gson = new Gson();
        Type listType = new TypeToken<List<District>>() {
        }.getType();
        List list = gson.fromJson(s, listType);
        return list;
    }


    private static String httpPost(Base base, String url) {

        Map<String, String> entries = new TreeMap<>();
        entries.put("app_key", appKey);
        entries.put("version", "1");
        entries.put("timestamp", String.valueOf(Instant.now().getEpochSecond()));
        entries.put("params", JSONUtil.toJsonStr(base));
        String sin = generateSign(entries, appSecret);
        entries.put("sign", sin);
        String post = HttpUtil.post(host + url, JSONUtil.toJsonStr(entries));

        JSONObject jsonObject = JSONUtil.parseObj(post);
        if (!String.valueOf(jsonObject.get("code")).equals("1")) {
            return JSONUtil.toJsonStr(jsonObject);
        }
        return JSONUtil.toJsonStr(jsonObject.get("data"));
    }

    public static String generateSign(Map<String, String> params, String appSecret) {
        // 第一步：字典排序已经由 TreeMap 自动完成
        StringBuilder stringBuilder = new StringBuilder();

        // 第二步：拼接键值对
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }
        // 第三步：首尾加上 app_secret
        String signString = appSecret + stringBuilder.toString() + appSecret;

        // 第四步：MD5 加密
        String md5Hash = DigestUtil.md5Hex(signString);

        // 第五步：转换为大写
        return md5Hash != null ? md5Hash.toUpperCase() : null;
    }
}
