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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.JdUtils;
import com.bohuikeji.delivery.backstage.util.capacity.UUPaotuiUtils;
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.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.exception.WebVerifiedException;
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.math.RoundingMode;
import java.time.Duration;
import java.util.List;

@Slf4j
@Component
public class HuolalaServer extends ThirdBase {

    /**
     * 子类向父类注册自己
     ***
     */
    public HuolalaServer(ITOrderService orderService, RedisTemplate<String, Object> redisTemplate, MqTool mqTool, RedisUtil redisUtil,ISysConfigService sysConfigService,ITConfigService configService,ITCourierService courierService) {
        super(NAME, HuolalaServer.class, "3028", "3018", "3003", "3006", "3025");
        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 ="HLL";

    @Override
    public APIEntity<OrderDetailDO> orderInquiryAndPlace(TOrder order) {
        log.error("##################################货拉拉下单业务#######################");
        //下单
        TConfig vehicleCfg=configService.getById(order.getVehicleConfigId());
        if (vehicleCfg != null && "ddc".equals(vehicleCfg.getConfigMark())){
            return APIEntity.fail("【货拉拉推单取消】订单：{}，非货拉拉订单。",order.getOrderNum());
        }
        order.setTravelType(vehicleCfg.getConfigMark());
        order.setHuoToken(orderService.getHuolalaToken());
        //order = orderService.huoLalaOrderPrice(order);
        JSONObject res= HllUtils.getEorderRequest(order);
        log.info("货拉拉推送返回数据：{}",res);
        if (!res.getString("msg").equals("success")){
            YiXunGmsUtils.sendTxt(order.getMailingPhone(),"您的订单："+order.getOrderNum()+"由于："+res.getJSONObject("data").getString("message"));
            orderService.cancelAndRefund(order);
            return APIEntity.fail("【货拉拉下单失败】{}",res.getString("resultMessage"));
        }
        //将货拉拉订单号存入订单中
        OrderDetailDO detailDO=new OrderDetailDO();
        detailDO.setThirdName(NAME);
        detailDO.setThirdNum(res.getJSONObject("data").getString("order_display_id"));
        detailDO.setOrderNumber(order.getOrderNum());
        detailDO.setDistance(String.valueOf(order.getOrderDistance()));
        detailDO.setOrderPrice(order.getOrderExpectPrice());

        /*order.setThirdNum(detailDO.getThirdNum());
        order.setThird(true);*/
        order.setThirdName("HLL");
        orderService.updateById(order);
        return APIEntity.success(detailDO);
    }

    /**
     * 货拉拉补付计算
     * @param order
     * @return
     */
    /*public BigDecimal huolalaSupplyPay(TOrder order){
        JSONObject res= HllUtils.getEorderConfirm(order);
        log.info("货拉拉取人账单：{}",res);
        return null;
    }*/

    /**
     * 获取订单详情
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderDetail(String orderNum, String thirdNum) {
        //先查询缓存订单
        OrderDetailDO detailDO= redisUtil.get(ThirdBase.getCacheKey(orderNum,NAME),OrderDetailDO.class);
        if (detailDO==null){
            detailDO=new OrderDetailDO();
        }
        detailDO.setThirdName(NAME);
        detailDO.setThirdNum(thirdNum);
        detailDO.setOrderNumber(orderNum);
        //查询价格
        JSONObject huolalaDetail = HllUtils.getEOrderDetail(orderService.getHuolalaToken(),thirdNum);
        if (huolalaDetail==null){
            log.error("订单：{}，无法查询价格，返回空当前状态：{}",orderNum,detailDO.getStatus());
            return APIEntity.fail("【货拉拉核查价格失败】订单：{}尚未生产运单信息",orderNum);
        }
        log.error("订单价格核查：订单号：{}，三方单号：{}",orderNum,thirdNum);
        log.error("订单价格核查,返回信息：{}",huolalaDetail.getFloatValue("send_bill_price_fen"));
        BigDecimal price= BigDecimal.valueOf(huolalaDetail.getFloatValue("send_bill_price_fen")).divide(new BigDecimal("100"));
        detailDO.setOrderPrice(price);
        return  APIEntity.success(detailDO);
    }

    @Override
    public APIEntity<CourierVo> courierInfo(String orderNum, String thirdNum) {
        TOrder order = orderService.getByNum(orderNum);
       /* if("待接单".equals(order.getOrderStatus()) && order.getCourierId() == null){
            return APIEntity.fail("该订单骑手未接单！");
        }*/
        TCourier courier=courierService.getById(order.getCourierId());
        JSONObject res = HllUtils.getCureierDetail(orderService.getHuolalaToken(),thirdNum);
        if(res.getInteger("ret") != 0){
            return APIEntity.fail(res.getString("msg"));
        }
        JSONObject data=res.getJSONObject("data").getJSONObject("driver_info");
        log.info("@@@@@@@@@@@货拉拉派送员信息：{}",data);
        AddressVo addressVo=null;

        CourierVo courierVo= VoBase.copy(courier,CourierVo.class);
        courierVo.setCourierName(data.getString("name"));
        courierVo.setCourierPhone(data.getString("phone_no"));
        if(data.getJSONObject("lat_lon") !=null){
            String location = data.getJSONObject("lat_lon").getString("lon")+","+data.getJSONObject("lat_lon").getString("lat");
            addressVo = MapUtils.getAddressReGeo(location);
        }else {
            return APIEntity.success();
        }
        courierVo.setLastLocation(addressVo);
        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("##################################货拉拉取消订单业务#######################");
        TOrder order = orderService.getByNum(orderNum);
        if(order == null){
            return APIEntity.success();
        }
        //不是货拉拉的订单直接返回
        if (StringUtils.isBlank(order.getThirdName()) || !order.getThirdName().equals(NAME)){
            return APIEntity.success();
        }
        String token = orderService.getHuolalaToken();
        //获取订单详情中状态
        Integer deductStatus = HllUtils.getEOrderDetail(token,thirdNum).getInteger("order_status");
        //获取取消原因
        /*JSONObject jsonObject = HllUtils.getEOrderCancelReason(token,String.valueOf(deductStatus),thirdNum);
        log.info("########################################:{}",jsonObject.getJSONArray("data"));*/
        //取消订单
        JSONObject jsonObject = HllUtils.getEOrderCancel(token, String.valueOf(deductStatus),thirdNum);
        log.info("货拉拉订单取消返回状态:{}",jsonObject.getString("msg"));
        return APIEntity.success();
    }

    @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(huolalaDetail);
    }

    /**
     * 获取第三方的订单流转记录
     *
     * @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));
    }

}
