package com.bohuikeji.delivery.backstage.controller.callback;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.controller.api.customer.CustomerV2Api;
import com.bohuikeji.delivery.backstage.entity.TCustomerWallet;
import com.bohuikeji.delivery.backstage.entity.TMaltField;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.*;
import com.bohuikeji.delivery.backstage.util.capacity.SfExpressUtils;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Map;

/**
 * 第三方配送业务回调通知类
 * @author 孙劲辉
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/api/callback")
public class ThirdCallBack {

   final ThirdUtils thirdUtils;
   final ShansongServer shansongServer;
   final UUServer uuServer;
   final ITCallBackService callBackService;
   final CustomerV2Api customerV2Api;
   final RedisUtil redisUtil;
   final ITOrderService orderService;
   final ITCourierService courierService;
   final ITMaltFieldService maltFieldService;
   final ITCustomerWalletService customerWalletService;

    /**
     * 闪送——订单回调通知
     * @param req
     * @return
     */
    @PostMapping("/shansong/order/notice")
    public Object ShanSongNotice(@RequestBody JSONObject req){
        callBackService.saveCallBack(req,"SS");
        OrderDetailDO detail= thirdUtils.getRedisDetail(req.getString("orderNo"),ShansongServer.NAME);
        if (detail!=null){
            detail.setStatus(String.valueOf(req.getIntValue("status")));
            detail.setStatusDesc(shansongServer.queryStatusDesc(req.getIntValue("status")));
            JSONObject courierJson= req.getJSONObject("courier");
            if (courierJson!=null){
                detail.setCourierPhone(courierJson.getString("mobile"));
                detail.setCourierName(courierJson.getString("name"));
                detail.setEstimateTime(courierJson.getString("estimateDeliveryTimeTip"));
                detail.setCourierLocation(courierJson.getString("longitude"+","+courierJson.getString("latitude")));
            }
            thirdUtils.callBack(detail,req);
        }
        else {
            log.error("【闪送回调错误】无法找到缓存的订单，可能该订单已取消：{}",req.toJSONString());
        }
        JSONObject res=new JSONObject();
        res.put("status",200);
        res.put("msg","SUCCESS");
        return res;
    }

    /**
     * UU跑腿回调
     * @param req
     * @return
     */
    @PostMapping("/uu/order/notice")
    public Object uuNotice(@RequestBody String  req){
        try {
            req=URLDecoder.decode(req,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        req=req.substring(req.indexOf("=")+1);
        JSONObject json=JSONObject.parseObject(req);
        log.error("UU跑腿回调进去：{}", req);
        OrderDetailDO detail= thirdUtils.getRedisDetail(json.getString("origin_id"), UUServer.NAME);
        if (detail!=null){
            detail.setStatus(json.getString("state"));
            detail.setCourierName(json.getString("driver_name"));
            detail.setCourierPhone(json.getString("driver_mobile"));
            detail.setStatusDesc(uuServer.queryStatusDesc(json.getIntValue("state")));
            thirdUtils.callBack(detail,json);
        }else {
            log.error("【UU跑腿回调错误】无法找到缓存的订单，可能该订单已取消：{}",req);
        }
        JSONObject res=new JSONObject();
        res.put("status",200);
        res.put("msg","SUCCESS");
        return res;
    }

    /**
     * 京东回调通知
     * @param body
     * @return
     */
    @PostMapping("/jd/order/notice")
    public JSONObject orderNotice(@RequestParam("request_body")String body){
        log.error("京东回调通知：{}",body);
        JSONObject json=JSONObject.parseObject(body);
        //callBackService.saveCallBack(json,"JD");
        OrderDetailDO detail= thirdUtils.getRedisDetail(json.getString("orderId"), JdServer.NAME);
        if (detail!=null){
            detail.setStatus(json.getString("traceNode"));
            detail.setStatusDesc(json.getString("traceMark"));
            detail.setCourierName(json.getString("operator"));
            detail.setCourierPhone(StringUtils.strGetPhone(json.getString("traceMark")));
            thirdUtils.callBack(detail,json);
        }
        else{
            log.error("京东回调错误，无法找到订单信息：{}",body);
        }

        JSONObject res=new JSONObject();
        res.put("statusCode",0);
        res.put("statusMessage","SUCCESS");
        return res;
    }
    /**
     * 顺丰同城回调
     * @param req
     * @return
     */
    @PostMapping("/sf/city/order/notice")
    public JSONObject sfOrderNotice(@RequestBody String  req){
        log.error("##################################顺丰同城操作回调通知#######################");
        try {
            req=URLDecoder.decode(req,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        req=req.substring(req.indexOf("=")+1);
        JSONObject json=JSONObject.parseObject(req);
        //callBackService.saveCallBack(json,"SF");
        log.error("顺丰回调通知：{}",json);
        OrderDetailDO detail= thirdUtils.getRedisDetail(json.getString("shop_order_id"), SfCityServer.NAME);
        if (detail!=null){
            detail.setStatus(json.getString("order_status"));
            detail.setThirdNum(json.getString("sf_order_id"));
            detail.setStatusDesc(json.getString("status_desc"));
            String recEmpName= json.getString("operator_name");
            String recEmpPhone=json.getString("operator_phone");
            if (StringUtils.isNotBlank(recEmpName)&&StringUtils.isNotBlank(recEmpPhone)){
                detail.setCourierName(recEmpName);
                detail.setCourierPhone(recEmpPhone);
            }
            thirdUtils.callBack(detail,json);
        }else {
            log.error("【闪送回调错误】无法找到缓存的订单，可能该订单已取消：{}",req);
        }
        JSONObject res=new JSONObject();
        res.put("error_code",0);
        res.put("error_msg","success");
        return res;
    }

    /**
     * 顺丰快递回调
     * @param req
     * @return
     */
    @PostMapping("/sf/order/notice")
    public APIEntity sfOrderExpressNotice(@RequestBody String  req){
        log.error("顺丰快递回调通知：{}",req);
        JSONObject json=JSONObject.parseObject(req);
        if(json.getString("actionCode").equals("110") && !"54".equals(json.getString("oriActionCode"))){
            return APIEntity.success();
        }
        if(json.getString("actionCode").equals("200") && !"80".equals(json.getString("oriActionCode"))){
            return APIEntity.success();
        }
        //callBackService.saveCallBack(json,"SFKD");
        OrderDetailDO detail= thirdUtils.getRedisDetail(json.getString("orderCode"), SfExpressServer.NAME);
        if (detail!=null){
            detail.setStatus(json.getString("actionCode"));
            detail.setThirdNum(json.getString("waybillNo"));
            detail.setStatusDesc(json.getString("actionDesc"));
            JSONArray  schedule = SfExpressUtils.orderScheduleInfo(null,json.getString("waybillNo"));
            log.error("根据顺分订单号查询调度信息：{}",schedule);
            if(schedule.size()>0){
                JSONObject jsonObject = schedule.getJSONObject(schedule.size()-1);
                log.error("获取最新的调度信息：{}",jsonObject);
                String recEmpName= jsonObject.getString("empCode");
                String recEmpPhone=jsonObject.getString("empPhone");
                if (StringUtils.isNotBlank(recEmpName)&&StringUtils.isNotBlank(recEmpPhone)){
                    detail.setCourierName(recEmpName);
                    detail.setCourierPhone(recEmpPhone);
                }
            }
            String sendEmpName= json.getString("sendEmpName");
            String sendEmpPhone=json.getString("sendEmpPhone");
            if (StringUtils.isNotBlank(sendEmpName)&&StringUtils.isNotBlank(sendEmpPhone)){
                detail.setCourierName(sendEmpName);
                detail.setCourierPhone(sendEmpPhone);
            }
            thirdUtils.callBack(detail,json);
        }
        log.error("顺丰快递订单回调信息：{}",json);
        return APIEntity.success();
    }

    /**
     * 货拉拉回调
     * @param req
     * @return
     */
    @PostMapping("/hll/order/notice")
    public APIEntity hllOrderNotice(@RequestBody String  req){
        JSONObject json=JSONObject.parseObject(req);
        log.error("##################################货拉拉操作回调通知#######################");
        log.error("货拉拉回调通知详情：{}",json);
        OrderDetailDO detail= thirdUtils.getRedisDetail(json.getJSONObject("data").getString("outside_order_id"), HuolalaServer.NAME);
        if (detail!=null){
            detail.setStatus(json.getString("action_type"));
            detail.setThirdNum(json.getJSONObject("data").getString("order_display_id"));
            detail.setCourierName("同城急送");//4006900105
            detail.setCourierPhone("16604712000");
            thirdUtils.hllCallBack(detail,json);
        }
        return APIEntity.success();
    }

    /**
     * 快递100回调
     * @param req
     * @return
     */
    @PostMapping("/kd/order/notice")
    public JSONObject kdOrderNotice(@RequestBody String req){
        log.error("##################################快递100下单回调通知#######################");
        try {
            req=URLDecoder.decode(req,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        req=req.substring(req.indexOf("=")+1);
        String str = req.substring(0, req.indexOf("&"));
        JSONObject json=JSONObject.parseObject(str);
        log.error("快递100回调通知详情2：{},kuaidinum:{}",json,json.getString("kuaidinum"));
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("third_num",json.getString("kuaidinum")));
        OrderDetailDO detail= thirdUtils.getRedisDetail(order.getOrderNum(), KDHundredServer.NAME);
        log.error("快递100回调通知详情3：{}",detail);
        if (detail!=null){
            JSONObject jsonObject = json.getJSONObject("data");
            detail.setStatus(jsonObject.getString("status"));
            detail.setThirdNum(json.getString("kuaidinum"));
            if("10".equals(detail.getStatus())){
                detail.setOrderPrice(new BigDecimal(jsonObject.getString("freight")));
            }
            detail.setCourierName(jsonObject.getString("courierName"));//4006900105
            detail.setCourierPhone(jsonObject.getString("courierMobile"));
            thirdUtils.kdCallBack(detail,json);
        }
        JSONObject responseJson = new JSONObject();
        responseJson.put("result",true);
        responseJson.put("returnCode","200");
        responseJson.put("message","成功");
        return responseJson;
    }

    /**
     * 快递100回调
     * @param req
     * @return
     */
    @PostMapping("/kd/info/notice")
    public JSONObject infokdNotice(@RequestBody String req){
        log.error("##################################快递100订单信息回调通知#######################");
        log.error("快递100回调通知详情1：{}",req);
        JSONObject responseJson = new JSONObject();
        responseJson.put("result",true);
        responseJson.put("returnCode","200");
        responseJson.put("message","成功");
        return responseJson;
    }


    /**
     * 麦芽田解绑回调
     * @param req
     * @return
     */
    @PostMapping("/malt/order/notice/token_unbind")
    public JSONObject maltOrderNotice(@RequestBody String  req){
        log.error("##################################麦芽田解绑回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        TMaltField tMaltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("shop_id",jsonObject.getInteger("shop_id")));
        if(tMaltField != null){
            maltFieldService.updateById(tMaltField.setMaltState("已解绑"));
        }
        JSONObject responseJson = new JSONObject();
        responseJson.put("code",200);
        responseJson.put("message","成功");
        return responseJson;
    }
    /**
     * 麦芽田查询当前余额
     * @param req
     * @return
     */
   /* @PostMapping("/malt/order/notice/token_unbind")
    public JSONObject maltTokenUnbind (@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田获取余额回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        log.error("麦芽田回调通知详情：{}",jsonObject);
        TMaltField maltField = maltFieldService.getOne(new QueryWrapper<TMaltField>().eq("",jsonObject.getString("shop_id")));
        TCustomerWallet customerWallet = customerWalletService.getByCustomerId(maltField.getCusId());
        JSONObject responseJson = new JSONObject();
        JSONObject data = new JSONObject();//响应参数
        data.put("balance",customerWallet.getWalletPrice().multiply(new BigDecimal("100")));
        data.put("at_time",System.currentTimeMillis()/1000L);
        responseJson.put("code",200);
        responseJson.put("data",data.toJSONString());
        responseJson.put("message","ok");
        return responseJson;
    }*/

    /**
     * 麦芽田计费回调
     * @param req
     * @return
     */
    @PostMapping("/malt/order/notice/valuating")
    public JSONObject maltOrderValuating (@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田计费操作回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        return maltFieldService.getbody("valuating",jsonObject);
    }


    /**
     * 麦芽田下单回调
     * @param req
     * @return
     */
    @PostMapping("/malt/order/notice/send")
    public JSONObject maltOrderSend(@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田下单操作回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        return maltFieldService.getbody("send",jsonObject);
    }

    /**
     * 麦芽田查询骑手当前位置
     * @param req
     * @return
     */
    @PostMapping("/malt/order/notice/rider_location")
    public JSONObject maltOrderRiderLocation(@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田操作回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        return maltFieldService.getbody("rider_location",jsonObject);
    }

    /**
     * 麦芽田查询订单配送详情
     * @param req
     * @return
     */
    @PostMapping("/malt/order/notice/query_info")
    public JSONObject maltOrderQueryInfo(@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田操作回调通知#######################");
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        return maltFieldService.getbody("query_info",jsonObject);
    }

    @PostMapping("/malt/order/notice/cancel")
    public JSONObject maltOrderCancel(@RequestBody String  req) throws Exception {
        log.error("##################################麦芽田取消操作回调通知#######################");
        JSONObject responseJson = new JSONObject();
        JSONObject json=JSONObject.parseObject(req);
        JSONObject jsonObject = json.getJSONObject("data");
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("malt_field_num",jsonObject.getString("source_order_no")));//初始化订单
        String[] states={"已完成","派送中","待派送"};
        for (String state : states) {
            if(order == null){
                responseJson.put("code",200);
                responseJson.put("message","成功");
                return responseJson;
            }
            if(state.equals(order.getOrderStatus())){
                responseJson.put("code",400);
                responseJson.put("message","派送中的订单不可取消");
                return responseJson;
            }
        }
        responseJson.put("code",200);
        responseJson.put("message","成功");
        customerV2Api.cancel(String.valueOf(order.getOrderId()),order.getPlayerId(),null);
        log.error("麦芽田回调响应结果：{}",responseJson);
        return responseJson;
    }
}
