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


import com.alibaba.fastjson.JSONObject;
import com.bohuikeji.delivery.backstage.entity.TMaltField;
import com.bohuikeji.delivery.backstage.entity.TOrder;
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 com.bohuikeji.frame.module.admin.utils.maiyatian.maiyatianSignUtils;
import jodd.http.HttpRequest;
import jodd.net.MimeTypes;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.UUID;


/**
 * 麦芽田工具类
 * @author Admin
 */
@Slf4j
public class maltUtils {


    //
    public static String app_key="uupUexMG";//开发者id
    public static String app_secret="b6b690a49afff949274cd2ecd8ea248a";//企业id
    public static String tag="JISONG";//密钥
    //public static String PORDURL="https://open-api-test.maiyatian.com/v1/delivery";//测试环境
    public static String PORDURL="https://open-api.maiyatian.com/v1/delivery";//正式环境


    /**
     * 公共请求参数
     * @param method
     * @param token
     * @return
     */
    public static JSONObject getMap(JSONObject data,String command,String token) throws Exception {
        JSONObject map = new JSONObject();
        map.put("app_key",app_key);
        map.put("data",data.toJSONString());
        map.put("request_id",UUID.randomUUID().toString());
        map.put("token",token);
        map.put("timestamp",LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));//System.currentTimeMillis()/1000L
        map.put("signature",maiyatianSignUtils.getSignature(map,command));
        return map;
    }

    /**
     * 150104
     * 获取、刷新Token
     */
    public static JSONObject getAccessToken(String code,String customerPhone,String shopNum,AddressVo adrass) throws Exception {
        JSONObject data = new JSONObject();
        data.put("grant_type","1");
        data.put("code",code);
        data.put("mobile",customerPhone);
        data.put("store_id",shopNum);
        data.put("city",adrass.getCity());
        data.put("city_code",adrass.getAdcode());
        JSONObject map=getMap(data,"access_token","");
        log.info("获取token时请求参数:{}",map);
        String resultJson = HttpRequest.post(PORDURL+"/access_token").bodyText(map.toJSONString(), MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        return res;
    }

    /**
     * 用授权码code换取长时令牌refreshToken以及访问令牌accessToken
     */
    public static JSONObject getRefreshToken(String token,String refreshToken) throws Exception {
        JSONObject data = new JSONObject();
        data.put("token", token);
        data.put("refresh_token", refreshToken);
        JSONObject map=getMap(data,"refresh_token","");
        String resultJson = HttpRequest.post(PORDURL+"/refresh_token").bodyText(map.toJSONString(), MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        log.info("########################刷新token:{}",resultJson);
        JSONObject res= JSONObject.parseObject(resultJson);
        return res;
    }

    /**
     *授权解绑
     */
    /*public static JSONObject gettokenUnbind(String token) throws Exception {
        JSONObject data = new JSONObject();
        data.put("shop_id", "1539367");
        data.put("token",token);
        Map<String,Object> map=getMap(data,"token_unbind","");
        String req = JSONObject.toJSONString(map);
        String resultJson = HttpRequest.post(PORDURL+"/token_unbind").bodyText(req, MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        return res;
    }*/

    /**
     * 获取、刷新Token
     */
    public static JSONObject getDeliveryChange(TOrder order, String courierName,TMaltField maltField, AddressVo address,String reason,Integer cancelType){
        JSONObject data = new JSONObject();
        data.put("order_no",order.getOrderNum());
        data.put("source_order_no",order.getMaltFieldNum());
        data.put("shop_id",maltField.getShopId().toString());
        data.put("status",getOrderStatus(order.getOrderStatus()));
        if(StringUtils.isNotBlank(courierName)){
            data.put("rider_name",courierName);
            data.put("rider_phone",order.getCourierPhone());
            if(address == null){
                data.put("longitude","");
                data.put("latitude","");
            }else {
                data.put("longitude",address.getLng());
                data.put("latitude",address.getLat());
            }
            data.put("cancel_type",cancelType);
            data.put("cancel_reason",reason);
        }else {
            data.put("rider_name","");
            data.put("rider_phone","");
            data.put("longitude","");
            data.put("latitude","");
            data.put("cancel_type",cancelType);
            data.put("cancel_reason",reason);
        }
        data.put("pickup_code","");
        data.put("at_time",System.currentTimeMillis()/1000L);
        JSONObject map= null;
        try {
            map = getMap(data,"delivery_change",maltField.getAccessToken());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String req = JSONObject.toJSONString(map);
        String resultJson = HttpRequest.post(PORDURL+"/delivery_change").bodyText(map.toJSONString(), MimeTypes.MIME_APPLICATION_JSON,"UTF-8").send()
                .contentType("application/json","utf-8").bodyText();
        JSONObject res= JSONObject.parseObject(resultJson);
        log.error("麦芽田订单状态流转：{}",res);
        return res;
    }

    /**
     * CANCEL 配送取消
     * RIDER_CANCEL 骑手取消
     * @param orderStatus
     * @return
     */
    public static String getOrderStatus(String orderStatus) {
        String status=null;
        switch (orderStatus){
            case "待接单":
                status = "PENDING";break;//未分配骑手
            case "待取件":
            case "取件中":
                status = "GRABBED";break;//已分配骑手
            case "待派送":
                status = "PICKUP";break;//已到店
            case "派送中":
                status = "DELIVERING";break;//配送中
            case "已完成":
                status = "DONE";break;//已完单
            case "已取消":
                status = "CANCEL";break;//取消
            default:
                return null;
        }
        return status;
    }

}
