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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.JdUtils;
import com.bohuikeji.delivery.backstage.util.capacity.SFCityUtils;
import com.bohuikeji.delivery.backstage.util.capacity.ShanSongUtils;
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.exception.WebVerifiedException;
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.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 闪送配送服务业务类
 * @author Admin
 */
@Slf4j
@Component
public class ShansongServer extends ThirdBase {

    public ShansongServer(ITOrderService orderService, RedisUtil redisUtil, ITConfigService configService,ITCourierService courierService) {
        super(NAME,ShansongServer.class,"20","30","40","50","60");
        this.orderService = orderService;
        this.redisUtil=redisUtil;
        this.configService=configService;
        this.courierService = courierService;
    }
    final ITOrderService orderService;
    final RedisUtil redisUtil;
    final ITConfigService configService;
    final ITCourierService courierService;

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

    /**
     * 询价并下单，子类各自实现业务逻辑
     *
     * @param order
     */
    @Override
    public APIEntity<OrderDetailDO> orderInquiryAndPlace(TOrder order) {
        log.error("##################################闪送下单业务#######################");
        /*if(order.getContactPhone().equals("15540709945")){
            log.error("发现麦芽田订单:{}，取消推送!",order.getOrderNum());
            return APIEntity.fail("【推送取消】周立武订单暂时不推送闪送同城");
        }*/
        if (!isContinue(order)){return APIEntity.fail("【推送取消】订单已被接取，或者订单已取消！"); }
        //判断下单选择的车辆来指定对应的交通方式
        TConfig vehicleCfg=configService.getById(order.getVehicleConfigId());
        if("car".equals(vehicleCfg.getConfigMark())){
            if(ShanSongUtils.travelWay(order.getMailingAddress().getAdcode()) == null){
                throw new WebVerifiedException("该城市暂未开通汽车配送服务!");
            }
            order.setTravelWay(ShanSongUtils.travelWay(order.getMailingAddress().getAdcode()));
        }
        log.info("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%:{}",order.getOrderNum());
        //订单向第三方询价
        APIEntity<JSONObject> res= ShanSongUtils.orderQueryBilling(order);
        if (!res.checkSuccess()){
            return APIEntity.fail(res.getMessage());
        }
        JSONObject data=res.getBody();
        //闪送订单实付价格
        BigDecimal price=new BigDecimal(data.getString("totalFeeAfterSave")).divide(new BigDecimal("100"), 2, RoundingMode.DOWN);
        //价格是否需要满足推送条件
        if(!order.getFranId().equals(168)){
            if(!isPush(order.getOrderExpectPrice(),price)){
                return APIEntity.fail("【推送取消】订单金额不满足推送条件，订单预估金额："+order.getOrderExpectPrice().toPlainString()+"，闪送金额："+price.toPlainString());
            }
        }
        OrderDetailDO detail=new OrderDetailDO();
        detail.setOrderPrice(price);
        detail.setThirdName(NAME);
        detail.setThirdNum(data.getString("orderNumber"));
        detail.setOrderNumber(order.getOrderNum());
        detail.setStatus("20");
        int discKm=Math.round(data.getLongValue("totalDistance")/1000f);
        detail.setDistance(String.valueOf(Math.max(discKm, 1)));
        //下单
        APIEntity<JSONObject> res2= ShanSongUtils.orderPlace(detail.getThirdNum());
        if (res2.checkSuccess()){
            log.error("【闪送订单推送成功】返回信息：{}",data.toJSONString());
            //执行SQL之前更新订单状态，延迟5秒后取消订单
            order=orderService.getById(order.getOrderId());
            //如果订单状态已经变更，取消订单(下单成功立即取消有一定概率闪送返回找不到订单，所以等5秒)
            if (!"待接单".equals(order.getOrderStatus())){
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //订单状态已变更，取消订单
                ShanSongUtils.orderCancel(detail.getThirdNum());
                return APIEntity.fail("【推送取消】订单："+order.getOrderNum()+",状态已变更为："+order.getOrderStatus());
            }
            return APIEntity.success(detail);
        }
        return APIEntity.fail(res2.getMessage());

    }

    /**
     * 获取订单详情
     *
     * @param orderNum 系统订单号
     * @param thirdNum 第三方订单号
     * @return
     */
    @Override
    public APIEntity<OrderDetailDO> orderDetail(String orderNum, String thirdNum) {
        //先查询缓存订单
        OrderDetailDO detail= redisUtil.get(ThirdBase.getCacheKey(orderNum,NAME),OrderDetailDO.class);
        if (detail==null){
            detail=new OrderDetailDO();
        }
        APIEntity<JSONObject> res=ShanSongUtils.orderQuery(thirdNum,orderNum);
        if (!res.checkSuccess()){
            return APIEntity.fail(res.getMessage());
        }
        JSONObject data=res.getBody();
        detail.setThirdName(NAME);
        detail.setThirdNum(thirdNum);
        detail.setOrderNumber(orderNum);
        int status=data.getIntValue("orderStatus");
        detail.setStatus(status+"");
        detail.setStatusDesc(queryStatusDesc(status));
        JSONObject courier=data.getJSONObject("courier");
        if(courier==null){
            return null;
        }
        JSONArray jsonArray = courier.getJSONArray("deliveryProcessTrail");
        if(jsonArray == null){
            return null;
        }
        JSONObject object =jsonArray.getJSONObject(jsonArray.size()-1);
        if (courier!=null){
            detail.setCourierName(courier.getString("name"));
            detail.setCourierPhone(courier.getString("mobile"));
            detail.setCourierLocation(object.getString("longitude")+","+object.getString("latitude"));
            detail.setEstimateTime(courier.getString("estimateDeliveryTimeTip"));
        }
        JSONArray priceList=data.getJSONArray("feeInfoList");
        BigDecimal price=new BigDecimal("0");
        if (priceList!=null){
            for (int i = 0; i < priceList.size(); i++) {
                price=price.add(priceList.getJSONObject(i).getBigDecimal("fee"));
            }
        }
        detail.setOrderPrice(price.divide(new BigDecimal("100"),2,RoundingMode.DOWN));
        return APIEntity.success(detail);
    }

    @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);
        APIEntity<JSONObject> res = ShanSongUtils.courierQuery(thirdNum);
        if (res == null){
            return APIEntity.fail("未查询到派送员实时信息");
        }
        JSONObject data=res.getBody();
        if(data==null){
            return APIEntity.success(courierVo);
        }
        if(data==null){
            return APIEntity.success(courierVo);
        }
        String location=null;
        JSONArray lonLat = data.getJSONArray("deliveryProcessTrail");
        if(lonLat != null&& !lonLat.equals("[]") && lonLat.size()>=1){
            JSONObject job = (JSONObject) lonLat.get(lonLat.size()-1);
            location = job.getString("longitude")+","+job.getString("latitude");
            AddressVo addressVo = MapUtils.getAddressReGeo(location);
            courierVo.setLastLocation(addressVo);
        }else {
            courierVo.setLastLocation(null);
        }
        courierVo.setCourierName(data.getString("name"));
        courierVo.setCourierPhone(data.getString("mobile"));
        return APIEntity.success(courierVo);
    }

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

    @Override
    public APIEntity<JSONObject> orderTip(String orderNum, String thirdNum, BigDecimal tipAmount) {
        APIEntity<JSONObject> res = ShanSongUtils.ssAddorderTip(thirdNum,tipAmount);
        log.info("闪送添加小费返回结果信息：{}",res);
        return res;
    }

    @Override
    public List<TOrderCircu> orderRecord(String orderNum, String thirdNum) {
        APIEntity<JSONObject> res=ShanSongUtils.orderQuery(thirdNum,orderNum);
        if (res.checkSuccess()){
            return res.getBody().getJSONArray("statusChangeLog").stream().map(v->{
                TOrderCircu circu=new TOrderCircu();
                JSONObject json=(JSONObject) v;
                circu.setChangeStatus(queryStatusDesc(json.getIntValue("orderStatus")));
                circu.setChangeTime(LocalDateTime.parse(json.getString("updateTime"), StringUtils.dataTimeFormat));
                return circu;
            }).collect(Collectors.toList());
        }

        return null;
    }

    /**
     * 使用状态码计算文本描述
     *
     * @param statusCode
     * @return
     */
    @Override
    public String queryStatusDesc(int statusCode) {
        switch (statusCode){
            case 20:return ("派单中");
            case 30:return("取件中");
            case 40:return("闪送中");
            case 50:return("已完成");
            case 60:return("已取消");
            default:return("未知");
        }
    }

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