package com.bohuikeji.delivery.backstage.service.third;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.entity.TConfig;
import com.bohuikeji.delivery.backstage.entity.TCourier;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.TOrderCircu;
import com.bohuikeji.delivery.backstage.entity.open.VoBase;
import com.bohuikeji.delivery.backstage.entity.open.vo.CourierVo;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.listener.order.OrderCheckPriceListener;
import com.bohuikeji.delivery.backstage.service.ITConfigService;
import com.bohuikeji.delivery.backstage.service.ITCourierService;
import com.bohuikeji.delivery.backstage.service.ITOrderService;
import com.bohuikeji.delivery.backstage.service.third.base.ThirdBase;
import com.bohuikeji.delivery.backstage.util.capacity.HllUtils;
import com.bohuikeji.delivery.backstage.util.capacity.KDHundredUtils;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.bohuikeji.frame.module.admin.utils.YiXunGmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.List;

@Slf4j
@Component
public class KDHundredServer extends ThirdBase {

    /**
     * 子类向父类注册自己
     ***
     */
    public KDHundredServer(ITOrderService orderService, RedisTemplate<String, Object> redisTemplate, MqTool mqTool, RedisUtil redisUtil, ISysConfigService sysConfigService, ITConfigService configService, ITCourierService courierService) {
        super(NAME, KDHundredServer.class, "101", "102", "0", "3", "9");
        this.orderService = orderService;
        this.redisTemplate=redisTemplate;
        this.mqTool = mqTool;
        this.redisUtil=redisUtil;
        this.sysConfigService = sysConfigService;
        this.configService = configService;
        this.courierService = courierService;
    }
    final ITOrderService orderService;
    final RedisTemplate<String, Object> redisTemplate;
    final MqTool mqTool;
    final RedisUtil redisUtil;
    final ISysConfigService sysConfigService;
    final ITConfigService configService;
    final ITCourierService courierService;

    /**
     * 服务名
     */
    public static final String NAME ="KD";

    @Override
    public APIEntity<OrderDetailDO> orderInquiryAndPlace(TOrder order) {
        log.error("##################################快递100下单业务#######################");
        if ("已取消".equals(order.getOrderStatus())){return APIEntity.fail("【推送取消】订单已被接取，或者订单已取消！"); }
        if (order.getVehicleName().contains("电动车")){
            return APIEntity.fail("【快递100推单取消】订单：{}，非快递类订单。",order.getOrderNum());
        }
        //下单
        JSONObject res= KDHundredUtils.kdOrderConvert(order);
        log.info("快递100推送返回数据：{}",res);
        if (!res.getString("returnCode").equals("200")){
            YiXunGmsUtils.sendTxt(order.getMailingPhone(),"您的订单："+order.getOrderNum()+"由于："+res.getString("message"));
            orderService.cancelAndRefund(order);
            return APIEntity.fail("【快递100下单失败】");
        }
        JSONObject jsonObject = new JSONObject();

        JSONObject date = res.getJSONObject("data");
        jsonObject.put("taskId",date.getString("taskId"));
        jsonObject.put("orderId",date.getString("orderId"));
        jsonObject.put("kuaidinum",date.getString("kuaidinum"));
        //将货拉拉订单号存入订单中
        OrderDetailDO detailDO=new OrderDetailDO();
        detailDO.setThirdName(NAME);
        detailDO.setThirdNum(date.getString("kuaidinum"));
        detailDO.setOrderNumber(order.getOrderNum());
        detailDO.setDistance(String.valueOf(order.getOrderDistance()));
        detailDO.setOrderPrice(order.getOrderExpectPrice());
        detailDO.setKdJson(jsonObject);
        order.setThirdName("KD");
        order.setThirdNum(detailDO.getThirdNum());
        order.setKdJson(jsonObject);
        orderService.updateById(order);
        return APIEntity.success(detailDO);
    }


    /**
     * 获取订单详情
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderDetail(String orderNum, String thirdNum) {
        log.error("第三方订单详情：订单号：{}，运单号：{}",orderNum,thirdNum);
        //先查询缓存订单
        String task;
        JSONObject kdDatail=null;
        OrderDetailDO detailDO= redisUtil.get(ThirdBase.getCacheKey(orderNum,NAME),OrderDetailDO.class);
        log.error("########################快递100的订单信息:{}",detailDO);
        if (detailDO==null){
            detailDO=new OrderDetailDO();
            detailDO.setThirdName(NAME);
            detailDO.setThirdNum(thirdNum);
            detailDO.setOrderNumber(orderNum);
            /*TOrder order=orderService.getOne(new QueryWrapper<TOrder>().eq("order_num",orderNum));
            log.error("##############################推送快递的订单信息：{}",order);
            task = order.getKdJson().getString("taskId");*/
        }else {
            task = detailDO.getKdJson().getString("taskId");
            kdDatail = KDHundredUtils.getOrderInfo(task);
        }
        //查询价格
        if (kdDatail==null){
            log.error("订单：{}，无法查询价格，返回空当前状态：{}",orderNum,detailDO.getStatus());
            return APIEntity.success(detailDO);
        }
        if(StringUtils.isBlank(kdDatail.getString("courierName"))){
            log.error("第三方订单详情111：订单号：{}，kdDatail：{}",orderNum,kdDatail);
            return APIEntity.success(detailDO);
        }else {
            log.error("第三方订单详情222：订单号：{}，kdDatail：{}",orderNum,kdDatail);
            detailDO.setCourierName(kdDatail.getString("courierName"));
            detailDO.setCourierPhone(kdDatail.getString("courierMobile"));
        }
        return  APIEntity.success(detailDO);
    }

    @Override
    public APIEntity<CourierVo> courierInfo(String orderNum, String thirdNum) {
        TOrder order = orderService.getByNum(orderNum);
        TCourier courier=courierService.getById(order.getCourierId());
        CourierVo courierVo= VoBase.copy(courier,CourierVo.class);
        log.error("快递100的骑手信息：{}",courierVo);
        return APIEntity.success(courierVo);
    }

    /**
     * 计算补充价格
     * @param orderNum 订单号
     * @return
     */
    public BigDecimal huoLaLaSupplyPay(String orderNum){
        TOrder order=orderService.getByNum(orderNum);
        JSONObject huolalaDetail = HllUtils.getEOrderDetail(orderService.getHuolalaToken(),order.getThirdNum());
        if (huolalaDetail==null){
            return null;
        }
        BigDecimal allPrice=BigDecimal.valueOf(huolalaDetail.getFloatValue("send_bill_price_fen")).divide(new BigDecimal("100"));
        //货拉拉比订单价格高，说明存在差价，发送短信
        if(allPrice.compareTo(order.getOrderFactPrice().add(order.getPrefAmount()))>0){
            log.error("订单差价计算{}货拉拉价格比订单价格高，说明存在差价，发送短信",order);
            return allPrice.subtract(order.getOrderFactPrice().add(order.getPrefAmount()));
        }
        //return allPrice.subtract(order.getThirdPrice().add(order.getPrefAmount()));
        return new BigDecimal("0");
    }


    /**
     * 取消订单
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<JSONObject> orderCancel(String orderNum, String thirdNum) {
        log.error("##################################快递100取消订单业务#######################");
        String task;
        String orderId;
        TOrder order = orderService.getByNum(orderNum);
        if(order == null){
            return APIEntity.success();
        }
        //不是快递100的订单直接返回
        if (StringUtils.isBlank(order.getThirdName()) || !order.getThirdName().equals(NAME)){
            return APIEntity.success();
        }
        OrderDetailDO detailDO= redisUtil.get(ThirdBase.getCacheKey(orderNum,NAME),OrderDetailDO.class);
        if(detailDO == null){
            task = order.getKdJson().getString("taskId");
            orderId = order.getKdJson().getString("orderId");
        }else {
            task = detailDO.getKdJson().getString("taskId");
            orderId = detailDO.getKdJson().getString("orderId");
        }
        //获取订单详情中状态
        log.error("快递100取消是的缓存数据1：task:{},orderId:{}",task,orderId);
        JSONObject deductStatus = KDHundredUtils.orderCancel(task,orderId,"暂时不寄件了");
        return APIEntity.success(deductStatus);
    }

    @Override
    public APIEntity<JSONObject> orderTip(String orderNum, String thirdNum, BigDecimal tipAmount) {
       /* String token = orderService.getHuolalaToken();
        JSONObject huolalaDetail = HllUtils.hllAddorderTip(token,thirdNum,tipAmount);
        log.info("货拉拉添加小费返回结果信息：{}",huolalaDetail);*/
        return APIEntity.success();
    }

    /**
     * 获取第三方的订单流转记录
     *
     * @param orderNum 订单号
     * @param thirdNum 三方单号
     * @return 第三方没有此类接口返回null或者size=0
     */
    @Override
    public List<TOrderCircu> orderRecord(String orderNum, String thirdNum) {
        return null;
    }

    /**
     * 使用状态码计算文本描述
     *
     * @param statusCode
     * @return
     */
    @Override
    public String queryStatusDesc(int statusCode) {
        return null;
    }

    /**
     * 订单复核，骑手取件成功后调用，向第三方平台复核订单信息是否有变化，可用于地址修改同步，价格差价补付等
     *
     * @param orderNum 订单号
     * @param thirdNum 第三方订单号
     */
    @Override
    public void orderReview(String orderNum, String thirdNum) {
        //延迟5分钟，复核货拉拉计费计费
        //mqTool.sendDelayMsg(orderNum, OrderCheckPriceListener.class, Duration.ofMinutes(8));
    }

}
