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.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.thread.OrderCalLBackThread;
import com.bohuikeji.delivery.backstage.thread.sfOderCancelThread;
import com.bohuikeji.delivery.backstage.util.capacity.SFCityUtils;
import com.bohuikeji.frame.module.admin.component.MqTool;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.thread.CachedThreadPool;
import com.bohuikeji.frame.module.admin.utils.MapUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 顺丰快递服务类
 * @author Admin
 */
@Slf4j
@Component
public class SfCityServer extends ThirdBase {

    final MqTool mqTool;
    final ITOrderService orderService;
    final ITConfigService configService;
    final ITCourierService courierService;

    /**
     * 子类向父类注册自己
     *
     */
    public SfCityServer(MqTool mqTool,ITOrderService orderService,ITConfigService configService,ITCourierService courierService) {
        super(NAME,SfCityServer.class, "0", "10", "15", "17", "2");
        this.mqTool=mqTool;
        this.orderService = orderService;
        this.configService = configService;
        this.courierService = courierService;
    }

    /**
     * 服务名
     */
    public static final String NAME ="SF";
    public String[] vehicles={"car","truck","car"};

    /**
     * 询价并下单，子类各自实现业务逻辑
     * 【注意】编写该方法时，下单成功务必再次查询数据库并判断订单状态，如发生变更及时取消
     *
     * @param order 订单
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderInquiryAndPlace(TOrder order) {
        log.error("##################################顺丰同城下单业务#######################");
        /*for (Integer fran : frans) {
            if (order.getFranId().equals(fran)){
                return APIEntity.fail("【推送取消】该加盟商设置不推送UU跑腿");
            }
        }*/
        if(order.getContactPhone().equals("15540709945")){
            return APIEntity.fail("【推送取消】周立武订单暂时不推送闪送同城");
        }
        if (order.getFranId().equals(168)){
            return APIEntity.fail("【推送取消】铜仁加盟商设置不推送顺丰同城");
        }
        if (!isContinue(order)){return APIEntity.fail("【推送取消】订单已被接取，或者订单已取消！"); }
        //判断下单选择的车辆来指定对应的交通方式
        TConfig vehicleCfg=configService.getById(order.getVehicleConfigId());
        if(StringUtils.isNotBlank(vehicleCfg.getConfigMark()) && !"ddc".equals(vehicleCfg.getConfigMark())){
            return APIEntity.fail("【顺丰取消】车辆类型：{}，顺丰不推送大车订单。",order.getVehicleName());
        }
        JSONObject data= SFCityUtils.orderEstimate(order).getJSONObject("result");
        log.error("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%:{}",data);
        if (data==null){
            return APIEntity.fail("【顺丰同城计算金额失败】。");
        }
        BigDecimal diffePrice=data.getBigDecimal("total_pay_money").divide(new BigDecimal("100"));
        if(diffePrice.subtract(order.getOrderFactPrice()).compareTo(new BigDecimal("5.00")) > 0){
            return APIEntity.fail("【顺丰同城订单金额高于标准订单金额禁止推送】。");
        }
        JSONObject res= SFCityUtils.establishOrder(order).getJSONObject("result");
        if (res==null){
            return APIEntity.fail("【顺丰下单失败】。");
        }
        BigDecimal price=res.getBigDecimal("total_pay_money").divide(new BigDecimal("100"));
        OrderDetailDO detailDO=new OrderDetailDO();
        detailDO.setThirdName(NAME);
        detailDO.setThirdNum(res.getString("sf_order_id"));
        detailDO.setOrderNumber(order.getOrderNum());
        detailDO.setDistance(String.valueOf(order.getOrderDistance()));
        detailDO.setOrderPrice(price);
        //1分钟后复核下单结果
        //mqTool.sendDelayMsg(detailDO, SfOrderPlaceCheck.class,Duration.ofSeconds(5));
        return APIEntity.success(detailDO);
    }

    /**
     * 获取订单详情
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderDetail(String orderNum, String thirdNum) {
        JSONObject res= SFCityUtils.getSfOrderStatus(thirdNum).getJSONObject("result");
        if (res==null){
            log.error("顺丰查询订单详情失败，返回null，订单号：{},三方单号：{}",orderNum,thirdNum);
            return APIEntity.fail("未找到订单费用信息，可能尚未取件！");
        }
        OrderDetailDO detailDO=new OrderDetailDO();
        detailDO.setOrderNumber(res.getString("out_order_id"));
        detailDO.setThirdNum(res.getString("order_id"));
        detailDO.setThirdName(this.name);
        BigDecimal allPrice=res.getBigDecimal("total_price").divide(new BigDecimal("100"));
        detailDO.setOrderPrice(allPrice);
        return APIEntity.success(detailDO);
    }

    /**
     * 获取派送员的实时信息
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @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= SFCityUtils.getSfCourierInfo(thirdNum);
        if(res.getInteger("error_code") != 0){
            return APIEntity.fail(res.getString("error_msg"));
        }
        JSONObject data=res.getJSONObject("result");
        String location = data.getString("rider_lng")+","+data.getString("rider_lat");
        CourierVo courierVo= VoBase.copy(courier,CourierVo.class);
        courierVo.setCourierName(data.getString("rider_name"));
        courierVo.setCourierPhone(data.getString("rider_phone"));
        AddressVo addressVo = MapUtils.getAddressReGeo(location);
        courierVo.setLastLocation(addressVo);
        return APIEntity.success(courierVo);
    }

    /**
     * 取消订单
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<JSONObject> orderCancel(String orderNum, String thirdNum) {
        if(StringUtils.isNotBlank(thirdNum)){
            try {
                CachedThreadPool.execute(new sfOderCancelThread(thirdNum));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       /* JSONObject res= SFCityUtils.sfCancelOrder(thirdNum);
        if (res!=null){
           *//* if (res.getIntValue("error_code")==0){
                return APIEntity.success();
            }*//*
        }*/
        return APIEntity.success();
    }

    /**
     * 顺丰小费
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @param tipAmount
     * @return
     */
    @Override
    public APIEntity<JSONObject> orderTip(String orderNum, String thirdNum,BigDecimal tipAmount) {
       JSONObject res= SFCityUtils.sfAddorderTip(thirdNum,tipAmount);
        log.info("顺丰添加小费返回结果信息：{}",res);
        return APIEntity.success(res);
    }

    /**
     * 获取第三方的订单流转记录
     *
     * @param orderNum 订单号
     * @param thirdNum 三方单号
     * @return 第三方没有此类接口返回null或者size=0
     */
    @Override
    public List<TOrderCircu> orderRecord(String orderNum, String thirdNum) {
        JSONArray res= SFCityUtils.sfListorderFeed(thirdNum).getJSONArray("feed");
        if (res==null){
            return null;
        }
        return res.stream().map(item->{
            TOrderCircu circ=new TOrderCircu();
            JSONObject json=(JSONObject) item;
            circ.setChangeStatus(json.getString("content"));
            circ.setChangeTime(LocalDateTime.ofInstant(json.getDate("create_time").toInstant(), ZoneId.systemDefault()));
            return circ;

        }).collect(Collectors.toList());

    }

    /**
     * 使用状态码计算文本描述
     *
     * @param statusCode
     * @return
     */
    @Override
    public String queryStatusDesc(int statusCode) {
        switch (statusCode){
            case 50:
            case 54:
            case 51:
                return "已收件";
            case 21:
            case 204:
            case 125:
            case 46:
            case 43:
            case 41:
            case 30:
            case 31:
                return "运输中";
            case 34:
            case 44:
            case 99:
            case 123:
            case 630:
            case 634:
            case 642:
            case 643:
            case 658:
            case 663:
            case 880:
                return "派送中";
            case 80:
            case 8000:
                return "已签收";
            default:return "异常件";
        }
    }

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