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

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.util.capacity.ShanSongUtils;
import com.bohuikeji.delivery.backstage.util.capacity.UUPaotuiUtils;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
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.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.TreeMap;

import static com.bohuikeji.delivery.backstage.util.OrderUtils.getSurplusTime;

/**
 * UU跑腿服务类
 * @author 孙劲辉
 */
@Slf4j
@Component
public class UUServer extends ThirdBase{


    /**
     * 子类向父类注册自己
     *
     */
    public UUServer(ITOrderService orderService,ITConfigService configService,ITCourierService courierService) {
        super(NAME,UUServer.class,"1","3","5","10","-1");
        this.orderService = orderService;
        this.configService = configService;
        this.courierService = courierService;
    }
    final ITOrderService orderService;
    final ITConfigService configService;
    final ITCourierService courierService;
    /**
     * 服务名
     */
    public static final String NAME ="UU";

    /**
     * 询价并下单，子类各自实现业务逻辑
     *
     * @param order
     */
    @Override
    public APIEntity<OrderDetailDO> orderInquiryAndPlace(TOrder order) {
        log.info("##################################UU跑腿下单业务#######################");
        for (Integer fran : frans) {
            if (order.getFranId().equals(fran)){
                return APIEntity.fail("【推送取消】该加盟商设置不推送UU跑腿");
            }
        }
        if (order.getFranId().equals(168)){
            return APIEntity.fail("【推送取消】铜仁加盟商设置不推送顺丰同城");
        }
        if(order.getPlayerId() == 203){
            return APIEntity.fail("【推送取消】周立武订单暂时不推送UU同城");
        }
        /*if("麦芽田".equals(order.getOrderChannel())){
            log.error("发现麦芽田订单:{}，取消推送!",order.getOrderNum());
            return APIEntity.fail("【推送取消】麦芽田订单暂时不推送UU同城");
        }*/
        //判断下单选择的车辆来指定对应的交通方式
        TConfig vehicleCfg=configService.getById(order.getVehicleConfigId());
        if(!"ddc".equals(vehicleCfg.getConfigMark())){
            return APIEntity.fail("【UU推单取消】车辆类型：{}，大车不推送UU。",order.getVehicleName());
        }
         if (!isContinue(order)){
             return APIEntity.fail("【推送取消】订单已被接取，或者订单已取消！");
         }
        //订单向第三方询价
        TreeMap<String,String> params=new TreeMap<>();
        params.put("origin_id",order.getOrderNum());
        List<AddressVo> addressList= MapUtils.gdToBd(order.getMailingAddress(),order.getReceiptAddress());
        params.put("from_address",addressList.get(0).getAddress());
        params.put("from_usernote",addressList.get(0).getDetail());
        params.put("from_lat",addressList.get(0).getLat());
        params.put("from_lng",addressList.get(0).getLng());
        params.put("city_name",addressList.get(0).getCity());
        params.put("to_address",addressList.get(1).getAddress());
        params.put("to_usernote",addressList.get(1).getDetail());
        params.put("to_lat",addressList.get(1).getLat());
        params.put("to_lng",addressList.get(1).getLng());
        params.put("send_type","0");
        String goodsType="其他";
        switch (order.getCargoName()){
            case "商务文件":
            case "广告印务":
                goodsType="文件";break;
            case "电子产品":
                goodsType="手机";break;
            case "生日蛋糕":
                goodsType="蛋糕";break;
            case "鲜花礼品":
                goodsType="鲜花";break;
            default:
                goodsType="其他";break;
        }
        params.put("goods_type",goodsType);
        LocalDateTime endTime=getSurplusTime(order);
        Duration duration = Duration.between(LocalDateTime.now(),endTime);
        //取件时间大于俩小时记为预约订单
        if(duration.toHours()>=2){
            params.put("subscribe_type","1");
            params.put("subscribe_time",endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }else {
            params.put("subscribe_type","0");
        }
        if(order.getInsured()){
            params.put("goods_price",order.getWorthName().replace("元",""));
        }
        APIEntity<JSONObject> req= UUPaotuiUtils.orderTest(params);
        if (!req.checkSuccess()){
            return APIEntity.fail(req.getMessage());
        }
        JSONObject body=req.getBody();
        //价格是否需要满足推送条件
        BigDecimal price=new BigDecimal(body.getString("need_paymoney"));
        /*if(!isPush(order.getOrderExpectPrice(),price)){
            return APIEntity.fail("【推送取消】订单金额不满足推送条件，订单预估金额："+order.getOrderExpectPrice().toPlainString()+"，UU金额："+price.toPlainString());
        }*/
        String price_token=body.getString("price_token");
        TreeMap<String,String> params2=new TreeMap<>();
        params2.put("price_token",price_token);
        params2.put("order_price",body.getString("total_money"));
        params2.put("balance_paymoney",body.getString("need_paymoney"));
        params2.put("receiver",order.getReceiptName());
        params2.put("receiver_phone",order.getReceiptPhone());
        if(StringUtils.isNotBlank(order.getOrderRemarks())){
            params2.put("note",order.getOrderRemarks());
        }
        params2.put("callback_url", UUPaotuiUtils.NOTICE_URL);
        params2.put("push_type","0");
        params2.put("special_type","0");
        params2.put("callme_withtake","1");
        params2.put("pubusermobile",order.getMailingPhone());
        params2.put("ordersource","3");
        params2.put("pay_type","1");
        //下单
        APIEntity<JSONObject> res2= UUPaotuiUtils.orderPlace(params2);
        if (res2.checkSuccess()){
            JSONObject body2=res2.getBody();
            log.error("【UU订单推送成功】返回信息：{}",body2.toJSONString());
            //执行SQL之前更新订单状态，延迟5秒后取消订单
            order=orderService.getById(order.getOrderId());
            //如果订单状态已经变更
            if (!"待接单".equals(order.getOrderStatus())){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //订单状态已变更取消订单
                UUPaotuiUtils.orderCancel(order.getOrderNum(),body2.getString("ordercode"),"订单已取消");
                return APIEntity.fail("【推送取消】订单："+order.getOrderNum()+",状态已变更为："+order.getOrderStatus());
            }
            OrderDetailDO detail=new OrderDetailDO();
            detail.setOrderNumber(order.getOrderNum());
            detail.setThirdNum(body2.getString("ordercode"));
            detail.setThirdName(NAME);
            detail.setOrderPrice(price);
            detail.setStatus("1");
            return APIEntity.success(detail);
        }
        return APIEntity.fail(res2.getMessage());
    }

    /**
     * 获取订单详情
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderDetail(String orderNum, String thirdNum) {
        APIEntity<JSONObject> res=UUPaotuiUtils.orderDetail(orderNum,thirdNum);
        if (!res.checkSuccess()){
            return APIEntity.fail(res.getMessage());
        }
        JSONObject data=res.getBody();
        OrderDetailDO detail=new OrderDetailDO();
        detail.setThirdName(NAME);
        detail.setOrderNumber(orderNum);
        detail.setThirdNum(thirdNum);
        detail.setDistance(data.getString("distance"));
        detail.setOrderPrice(new BigDecimal(data.getString("order_price")));
        int status=data.getIntValue("state");
        detail.setStatus(status+"");
        detail.setStatusDesc(queryStatusDesc(status));
        detail.setCourierName(data.getString("driver_name"));
        detail.setCourierPhone(data.getString("driver_mobile"));
        detail.setCourierLocation(data.getString("driver_lastloc"));
        detail.setEstimateTime("预计到达时间："+data.getString("expectedarrive_time"));
        return APIEntity.success(detail);
    }

    @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());
        APIEntity<JSONObject> res=UUPaotuiUtils.orderDetail(orderNum,thirdNum);
        if (!res.checkSuccess()){
            return APIEntity.fail(res.getMessage());
        }
        JSONObject data=res.getBody();
        log.info("@@@@@@@@@@@@@UU跑腿派送员信息：{}",data);
        if(StringUtils.isBlank(data.getString("driver_lastloc"))){
            return APIEntity.fail("派送员未开启定位！");
        }
        CourierVo courierVo= VoBase.copy(courier,CourierVo.class);
        courierVo.setCourierName(data.getString("driver_name"));
        courierVo.setCourierPhone(data.getString("driver_mobile"));
        AddressVo addressVo=null;
        if(StringUtils.isNotBlank(data.getString("driver_lastloc"))){
            addressVo = MapUtils.getAddressReGeo(data.getString("driver_lastloc"));
        }
        courierVo.setLastLocation(addressVo);
        return APIEntity.success(courierVo);
    }

    /**
     * 取消订单
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<JSONObject> orderCancel(String orderNum, String thirdNum) {
        return UUPaotuiUtils.orderCancel(orderNum,thirdNum,"系统取消订单");
    }

    @Override
    public APIEntity<JSONObject> orderTip(String orderNum, String thirdNum, BigDecimal tipAmount) {
        UUPaotuiUtils.uuAddorderTip(orderNum,thirdNum,tipAmount);
        return null;
    }

    @Override
    public List<TOrderCircu> orderRecord(String orderNum, String thirdNum) {
        return null;
    }

    /**
     * 使用状态码计算文本描述
     *
     * @param statusCode
     * @return
     */
    @Override
    public String queryStatusDesc(int statusCode) {
        switch (statusCode){
            case 1:return ("下单成功");
            case 3:return ("跑男抢单");
            case 4:return ("已到达");
            case 5:return ("已取件");
            case 6:return ("到达目的地");
            case 10:return ("收件人已收货");
            case -1:return ("订单取消");
            default:return ("未知");
        }
    }

    @Override
    public void orderReview(String orderNum, String thirdNum) {

    }
}
