package com.iamberry.wechat.handles.polyapi;


import com.alibaba.fastjson.JSON;
import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.OrderItem;
import com.iamberry.wechat.core.entity.product.Product;
import com.iamberry.wechat.core.entity.product.ProductColor;
import com.iamberry.wechat.core.entity.receive.ChargerReceive;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.porduct.ProductService;
import com.iamberry.wechat.face.receive.ChargReceiveService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.SendMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对接菠萝派接口
 */
@Controller
public class ExternalDockPolyApiHandler {

    private static Logger logger = LoggerFactory.getLogger(ExternalDockPolyApiHandler.class);

    @Autowired
    private AdminOrderService adminOrderService;

    @Autowired
    private ProductService productService;

    @Autowired
    private SendMessageUtil sendMessageUtil;

    @Autowired
    private ChargReceiveService chargReceiveService;

    /**
     * DES对称加密
     */
    private static MD5 md5 = new MD5();


    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 请求示例：
     * appkey=438b2f6ff103422a98a9349507293bb2
     * &method=Differ.JH.Business.GetOrder
     * &bizcontent={"OrderStatus":"JH_01","PlatOrderNo":"20182270207","StartTime":"2016-07-26 10:59:10","EndTime":"2016-08-02 10:59:10","TimeType":"JH_02","PageIndex":"1","PageSize":"20"}
     * &token=9415c33b04d24c7dae320b0185f42fb0
     * &sign=347e07a557e2720256e64e1e828eff1b
     */

    /**
     *  请求响应
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/select_order")
    public Map<String,Object> getOrder(HttpServletRequest request) throws Exception {

        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> requstMap = new HashMap<String,Object>();
        try{
            requstMap =  verification(request);
        }catch (Exception e){
            map.put("code","40000");
            map.put("message","请求未能识别");
            map.put("submessage","参数有误");
            map.put("numtotalorder",0);
            return map;
        }

        if(requstMap == null ){
            map.put("code","40000");
            map.put("message","请求未能识别");
            map.put("submessage","参数有误");
            map.put("numtotalorder",0);
            return map;
        }

        String method =  request.getParameter("method");
        switch (method){
            case "Differ.JH.Business.GetOrder" :  //订单下载
                map = selectSalesOrder(requstMap);
                break;
            case "Differ.JH.Business.CheckRefundStatus" :  //退款检测 ：即使没有退款功能，该接口也需要有，否则影响发货流程，可以统一返回没有退款）
                map = selectOrderRefundStatus(requstMap);
                break;
            case "Differ.JH.Business.Send" :  //订单发货
                map = orderDelivery(requstMap);
                break;
            case "Differ.JH.Business.UpdateSellerMemo" :  //修改订单备注
                map = updateOrderRemark(requstMap);
                break;
            case "Differ.JH.Business.DownloadProduct" :  //商品下载
                //map = downProduct(requstMap);
                break;
            case "Differ.JH.Business.SyncStock" :  //商品库存同步
                break;
            case "Differ.JH.Business.GetRefund" :  //退货退款单下载
                map = downRefundOrder(requstMap);
                break;
            default:
                map.put("code","40000");
                map.put("message","请求未能识别");
                map.put("submessage","参数有误");
                map.put("numtotalorder",0);
                break;
        }
        return map;
    }

    /**
     * 订单查询（订单下载）
     * @param requstMap
     * @return
     */
    private Map<String,Object> selectSalesOrder(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();

        /*订单交易状态(等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05，所有订单=JH_99)*/
        String orderStatus = (String) requstMap.get("OrderStatus");
        String platOrderNo = (String) requstMap.get("PlatOrderNo"); //平台订单号，若不为空，则代表查询单个订单的数据，查询单个订单时，可不传时间、状态等
        String startTime = (String) requstMap.get("StartTime");
        String endTime =  (String) requstMap.get("EndTime");
        String timeType = (String) requstMap.get("TimeType");  //订单时间类别(订单修改时间=JH_01，订单创建时间=JH_02) (管家抓单默认JH_01)
        Integer pageIndex = Integer.valueOf(requstMap.get("PageIndex").toString());
        Integer pageSize = Integer.valueOf(requstMap.get("PageSize").toString());

        Order order = new Order();
        if(platOrderNo != null && !"".equals(platOrderNo)){
            order.setSalesOrderid(platOrderNo);
        }

        // TODO: 2018/2/7  只查询代发货的信息，
       if(orderStatus == null || "".equals(orderStatus) || "JH_01".equals(orderStatus) || "JH_03".equals(orderStatus)
               || "JH_04".equals(orderStatus) || "JH_05".equals(orderStatus) ){
           List<Map<String,Object>> orders = new ArrayList<>();
           map.put("code","10000");
           map.put("message","SUCCESS");
           map.put("orders",orders);
           map.put("numtotalorder",0);
       }else if("JH_99".equals(orderStatus)){
           orderStatus = "JH_02";
       }

       //设置订单状态
       this.setStatus(order,orderStatus);

       //只查询创建时间的订单
        order.setSelectDateType(2);

        try {
            order.setBeginDate(sdf.parse(startTime));
            order.setEndDate(sdf.parse(endTime));
        }catch (ParseException e){
            logger.info("=========日期转换失败=========");
            map.put("code","40000");
            map.put("message","查询出错");
            map.put("submessage","查询出错");
            map.put("numtotalorder",0);
            return map;
        }

        order.getPage().setPageSize(pageSize);
        order.getPage().setPageNumber(pageIndex);
        order.getPage().initRecordBegin();
        Integer orderNum = adminOrderService.selectOrderNum(order);
        List<Order> orderList = adminOrderService.selectShopOrderByPola(order);
        List<Map<String,Object>> orders = new ArrayList<>();
        map.put("code","10000");
        map.put("message","SUCCESS");
        String orderId = "";
        for(Order or : orderList){
            List<OrderItem> orderItemList = adminOrderService.getShopOrderItemByOrderIdToPola(or.getSalesOrderid());
            or.setOrderItemList(orderItemList);
            try {
                orders.add(getOrderMap(or));
                orderId += or.getSalesOrderid() + ",";
            }catch (Exception e){
                e.printStackTrace();
                logger.info("订单无法被转换为接口所需要的数据！");
            }
        }

        /*加入领取充电器的订单--start*/
//        ChargerReceive chargerReceive = new ChargerReceive();
//        chargerReceive.setReceiveStatus(2);
//        List<ChargerReceive> chargerReceiveList = chargReceiveService.getChargerReceiveList(chargerReceive);
//        for (ChargerReceive cr : chargerReceiveList){
//            orders.add(getReceive(cr));
//        }
        /*加入领取充电器的订单--end*/

        map.put("orders",orders);
        map.put("numtotalorder",orderNum);
        logger.info("------订单下载，返回订单个数：" + orderList.size() + "--------- 订单id：" + orderId +  "---------");
        return map;
    }

    /**
     * 订单退款状态查询
     * @param requstMap
     * @return
     */
    private Map<String,Object> selectOrderRefundStatus(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();
        String orderId = (String) requstMap.get("OrderID"); //平台订单号

        Order order;
        if(orderId != null && !"".equals(orderId)){
            order = adminOrderService.selectShopOrderByPolaById(orderId);
            if(order == null){
                map.put("code","40000");
                map.put("message","未查询到该订单");
                map.put("submessage","未查询到该订单");
                return map;
            }
        }else{
            map.put("code","40000");
            map.put("message","订单号不能为空");
            map.put("submessage","订单号不能为空");
            return map;
        }
        map.put("refundStatus",this.getOrderRefundStatus(order.getSalesStatus()));     //退款状态   必填
        String refundStatusdescription = "";
        if(order.getSalesReturnDes() != null){
            refundStatusdescription = order.getSalesReturnDes();
        }
        map.put("refundStatusdescription",refundStatusdescription);  //选填 退款说明
        List<Map<String,Object>> childrenrefundStatus = new ArrayList<>();
        List<OrderItem> orderItemList = adminOrderService.getShopOrderItemByOrderIdToPola(order.getSalesOrderid());
        for(OrderItem orderItem : orderItemList){
            Map<String,Object> childrenrefund = new HashMap<String, Object>();
            childrenrefund.put("refundno","");      //退款订单号    可选
            childrenrefund.put("ProductName",orderItem.getItemProductName());      //退款商品名称    可选
            childrenrefund.put("refundStatus",this.getOrderRefundStatus(order.getSalesStatus()));      //退款状态    可选
            childrenrefund.put("refundStatusdescription",refundStatusdescription);      //选填 退款说明
            childrenrefundStatus.add(childrenrefund);
        }
        logger.info("------退款检测，查询订单id：" + order.getSalesOrderid() + "--订单状态：" + order.getSalesStatus() +  "---------");
        map.put("childrenrefundStatus",childrenrefundStatus);  //子订单退款说明
        map.put("code","10000");
        map.put("message","返回订单退款状态成功，订单id："+  order.getSalesOrderid() +"订单状态为："+ this.getDescription(order.getSalesStatus()));
        map.put("submessage","返回订单退款状态成功");
        return map;
    }

    /**
     * 订单发货
     * @param requstMap
     * @return
     */
    private Map<String,Object> orderDelivery(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();
        /*订单发货类别(自己联系物流=JH_01，在线下单=JH_02，无需物流=JH_03，自定义物流=JH_04，家装发货=JH_05，国际物流=JH_06)*/
        String SendType = (String) requstMap.get("SendType");
        String LogisticName = (String) requstMap.get("LogisticName"); //快递名称
        String LogisticType = (String) requstMap.get("LogisticType"); //快递类别(JH前缀为国内快递 ，JHI为国际快递)详见物流公司代码对照表
        String LogisticNo = (String) requstMap.get("LogisticNo"); //快递运单号
        String PlatOrderNo = (String) requstMap.get("PlatOrderNo"); //平台订单号
        Integer IsSplit = Integer.valueOf(requstMap.get("IsSplit").toString()) ; //是否拆单发货(拆单=1 ，不拆单=0)
        /*平台子订单交易单号，支持订单拆分为不同商品不同数量发货,
            多个商品用"|"隔开, 为空则视为整单发货
            包含子订单编号和商品发货数量，格式suborderno1:count1|suborderno2:count2发货数量需为大于0的整数
        */
        String SubPlatOrderNo = (String) requstMap.get("SubPlatOrderNo");
        String SenderName = (String) requstMap.get("SenderName"); //发货人姓名
        String SenderTel = (String) requstMap.get("SenderTel"); //发货人联系电话
        String SenderAddress = (String) requstMap.get("SenderAddress"); //发货人地址(省市区之间以空格分隔)
        Integer IsHwgFlag = Integer.valueOf(requstMap.get("IsHwgFlag").toString()); //是否为海外购(是=1；否=0)

        Order order;
        if(PlatOrderNo != null && !"".equals(PlatOrderNo)) {
            order = adminOrderService.selectShopOrderByPolaById(PlatOrderNo);
            if(order == null){
                map.put("code","40000");
                map.put("message","未查询到该订单");
                map.put("submessage","未查询到该订单");
                return map;
            }
        }else{
            map.put("code","40000");
            map.put("message","订单号不能为空");
            map.put("submessage","订单号不能为空");
            return map;
        }
        Boolean flag = false;
        if(order.getSalesStatus() == 2){ //判断订单是否支持发货
            Order or = new Order();
            or.setSalesOrderid(PlatOrderNo);
            or.setSalesPostFirm(this.selectFirm(LogisticType));      //设置快递公司
            or.setSalesPostNum(LogisticNo);       //设置快递单号
            or.setSalesStatus(5);        //发货
            flag = adminOrderService.deliverOrderByOrderId(or);
            //给用户发送消息-已发货的通知
            String  firm = this.selectFirm(LogisticType);  //快递公司
            String  num = LogisticNo;       //快递单号
            try {

                /*微信推送发货信息*/
                sendMessageUtil.orderSendSuccess(
                        "尊敬的朵粉，您的订单已发货，物流信息:",
                        order.getSalesOrderid(),
                        SendMessageUtil.hashmap.get(firm),
                        num,
                        order.getSalesAddressInfo(),
                        "如有问题请致电400-678-1860或直接在微信留言，soodo上朵将第一时间为您服务！（点击查看订单详情）",
                        order.getSalesOpenid(),
                        ResultInfo.ORDER_DETAIL+order.getSalesOrderid()
                );
            } catch (Exception e) {
                logger.info("订单号："+ order.getSalesOrderid() +"的订单已发货，发送微信消息失败!");
                logger.info("失败原因：订单编号"+order.getSalesOrderid() + "快递公司:"+SendMessageUtil.hashmap.get(firm) +"快递单号"+num+"地址" +order.getSalesAddressInfo()+"openid:"+order.getSalesOpenid()+"remark:"+ResultInfo.ORDER_DETAIL+order.getSalesOrderid());
            }
        }
        logger.info("---- 订单发货，发货订单id：" + order.getSalesOrderid() + "-- 订单状态：" + order.getSalesStatus() +  "-----是否发货成功："+ flag);
        if(flag){
            map.put("code","10000");
            map.put("message","订单发货成功");
            map.put("submessage","订单发货成功");
        }else{
            logger.info("订单发货失败，不支持发货操作,订单id：" + order.getSalesOrderid());
            map.put("code","40000");
            map.put("message","参数有误");
            map.put("submessage","订单不支持发货操作");
        }
        return map;
    }

    /**
     * 修改备注
     * @param requstMap
     * @return
     */
    private Map<String,Object> updateOrderRemark(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();

        String orderId = (String) requstMap.get("PlatOrderNo");     //订单id
        String remark = (String) requstMap.get("SellerMemo");      //备注
        //卖家旗帜(无=JH_None，灰=JH_Gray，红=JH_Red，黄=JH_Yellow，绿=JH_Green，蓝=JH_Blue，紫=JH_Purple)
        String sellerFlag = (String) requstMap.get("SellerFlag");

        Order order = new Order();
        order.setSalesOrderid(orderId);
        if(orderId != null && !"".equals(orderId)) {
            order = adminOrderService.selectShopOrderByPolaById(orderId);
            if(order == null){
                map.put("code","40000");
                map.put("message","未查询到该订单");
                map.put("submessage","未查询到该订单");
                return map;
            }
        }else{
            map.put("code","40000");
            map.put("message","订单号不能为空");
            map.put("submessage","订单号不能为空");
            return map;
        }
        Order or = new Order();
        or.setSalesOrderid(orderId);
        or.setSalesUserRemark(remark);
        Integer flag  = adminOrderService.updateOrderByPola(or);
        if(flag > 0){
            map.put("code","10000");
            map.put("message","修改订单备注成功");
            map.put("submessage","修改订单备注成功");
        }else{
            logger.info("修改订单备注失败，订单id：" + order.getSalesOrderid());
            map.put("code","40000");
            map.put("message","参数有误");
            map.put("submessage","修改订单备注失败");
        }
        return map;
    }

    /**
     *  退货退款单下载
     * @param requstMap
     * @return
     */
    private Map<String,Object> downRefundOrder(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();

        String beginTime = (String) requstMap.get("BeginTime");     //开始时间
        String endTime = (String) requstMap.get("EndTime");     //结束时间
        String pageIndex = (String) requstMap.get("PageIndex");     //页码(默认值：1)
        String pageSize = (String) requstMap.get("PageSize");     //每页条数(默认值：10)

//        map.put("code","10000");
//        map.put("message","退货退款单下载");
//        map.put("submessage","退货退款单下载");

        return map;
    }

    /**
     * 获取商品
     * @param requstMap
     * @return
     */
    private Map<String,Object> downProduct(Map<String,Object> requstMap){
        Map<String,Object> map = new HashMap<String,Object>();

        Integer productId = null;
        String ProductId = requstMap.get("ProductId").toString();
        if(ProductId != null && !"".equals(ProductId) ){
            productId = Integer.valueOf(ProductId);     //可选，商品外部商家编码（注，网店管家目前尚未支持此参数的查询）
        }
        String productName = (String) requstMap.get("ProductName");     //商品名称
        String status = (String) requstMap.get("Status");     //商品状态(已上架商品=JH_01，已下架商品=JH_02，所有商品=JH_99)
        Integer pageIndex = Integer.valueOf(requstMap.get("PageIndex").toString()) ;     //开始时间
        Integer pageSize = Integer.valueOf(requstMap.get("PageSize").toString());     //开始时间

        Product product = new Product();

        if(status == null || "".equals(status) || "JH_99".equals(status)){
            product.setProductStatus(1);
        }else  if("JH_02".equals(status)){
            List<Map<String,Object>>  goodslist = new ArrayList<>();
            map.put("code","40000");
            map.put("totalcount",0);
            map.put("goodslist",goodslist);
            map.put("message","获取商品集合成功");
            map.put("submessage","获取商品集合成功");
            return map;
        }
        product.setProductId(productId);
        product.getPage().setPageSize(pageSize);
        product.getPage().setPageNumber(pageIndex);
        List<Product> productList = productService.selectAllProductInfo(product);

        Integer num = productService.selectAllProductNum(product);
        if(num < 1){
            num = 1;
        }
        map.put("totalcount",num);         //商品总数量(默认值：1)
        List<Map<String,Object>>  goodslist = new ArrayList<>();
        for (Product pt : productList){
            Map<String,Object> goods = new HashMap<String,Object>();
            goods.put("PlatProductID",String.valueOf(pt.getProductId()));      //平台商品ID 必填
            goods.put("name",pt.getProductName());               //商品名称 必填
            //外部商家编码（注：若与管家对接，这里需要返回与管家商品相匹配的编号，方便管家商品与平台商品的匹配）
            goods.put("OuterID",String.valueOf(pt.getProductId()));      //
            double discount = pt.getProductDiscount().intValue() / 100;
            goods.put("price",discount);      //商品价格
            // TODO: 2018/2/8 商品库存待确定
            goods.put("num",10000);      //商品数量
            goods.put("pictureurl","");      //图片URL  可选
            goods.put("whsecode","");      //商品所在仓库编号  可选
            List<ProductColor> colors = pt.getColorList(); //获取颜色集合
            List<Map<String,Object>>  colorList = new ArrayList<>();
            for(ProductColor productColor : colors){
                Map<String,Object> colorMap = new HashMap<String,Object>();
                colorMap.put("SkuID",String.valueOf(productColor.getColorId()));      //平台规格ID

                // TODO: 2018/2/21 判断是否是货号编码
                //规格外部商家编码（注：若与管家对接，这里需要返回与管家商品相匹配的编号，方便管家商品与平台商品的匹配）
                colorMap.put("skuOuterID",productColor.getColorPolyCode());
                double colorDiscount = productColor.getColorDiscount().intValue() / 100;
                colorMap.put("skuprice",colorDiscount);      //规格价格
                colorMap.put("skuQuantity",10000);      //规格数量
                colorMap.put("skuname",productColor.getColorName());      //规格名称
                colorMap.put("colors","");      //规格属性  可选
                colorMap.put("skupictureurl","");      //规格图片URL  可选
                colorList.add(colorMap);
            }
            goods.put("skus",colorList);      //规格集合
            goodslist.add(goods);
        }
        map.put("goodslist",goodslist);
        map.put("code","10000");
        map.put("message","获取商品集合成功");
        map.put("submessage","获取商品集合成功");
        return map;
    }

    /**
     * 获取快递公司代号，
     * @param LogisticType
     * @return
     */
    private String selectFirm(String LogisticType){
        switch (LogisticType){
            case "JH_001": //EMS
                return "ems";
            case "JH_002": //圆通
                return "yto";
            case "JH_003": //韵达
                return "yunda";
            case "JH_004": //天天快递
                return "ttkdex";
            case "JH_005": //申通
                return "sto";
            case "JH_006": //中通
                return "zto";
            case "JH_007": //宅急送
                return "zjs";
//            case "JH_008": //快捷快递
//                return "";
//            case "JH_009": //全峰快递
//                return "";
//            case "JH_010": //国通快递
//                return "";
//            case "JH_011": //德邦物流
//                return "";
            case "JH_012": //百世汇通
                return "htky";
//            case "JH_013": //优速快递
//                return "";
            case "JH_014": //顺丰
                return "sf";
//            case "JH_015": //中铁快运
//                return "";
            case "JH_019": //龙邦速递
                return "longbanwuliu";
            case "JH_028": //汇通快运
                return "htky";
//            case "JH_037": //邮政包裹平邮
//                return "";
//            case "JH_046": //京东快递
//                return "";
            case "JH_092": //EMS经济快递
                return "ems";
//            case "JH_115": //万象
//                return "";
//            case "JH_091": //百世物流
//                return "";
            default:
                return LogisticType;
        }
    }

    /**
     * 查询退款状态
     *
     *  本系统状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货  6：申请退货中
     *  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     *
     * 退款状态(没有退款=JH_07，买家已经申请退款等待卖家同意=JH_01，卖家已经同意退款等待买家退货=JH_02，
     * 买家已经退货等待卖家确认收货=JH_03，卖家拒绝退款=JH_04，退款关闭=JH_05，退款成功=JH_06，其他=JH_99)
     *
     * @param status
     * @return
     */
    private String getOrderRefundStatus(Integer status){
        switch (status){
            case 0:
                return "JH_07";
            case 1:
                return "JH_07";
            case 2:
                return "JH_07";
            case 3:
                return "JH_01";
            case 4:
                return "JH_06";
            case 5:
                return "JH_07";
            case 6:
                return "JH_01";
            case 7:
                return "JH_02";
            case 8:
                return "JH_06";
            case 9:
                return "JH_07";
            case 10:
                return "JH_07";
            case 11:
                return "JH_07";
            case 12:
                return "JH_07";
            default:
                return "JH_07";
        }
    }

    /***
     * 订单下载 拼接map
     * 如果不用传参数请去掉，否则有可能会报错
     * @param order
     * @return
     */
    private  Map<String,Object> getOrderMap(Order order){
        String[] addressInfo = order.getSalesAddressInfo().split("-");
        String town = "";  //获取街道

        if(addressInfo.length > 3){
            Integer qu = order.getSalesAddressInfo().indexOf(addressInfo[3]);
            town = order.getSalesAddressInfo().substring(qu,order.getSalesAddressInfo().length());
        }

        Map<String,Object> orderMap = new HashMap<String,Object>();
        orderMap.put("PlatOrderNo",order.getSalesOrderid()); //订单号
        orderMap.put("tradeStatus",this.getStatus(order.getSalesStatus())); //订单状态
        orderMap.put("tradeStatusdescription",this.getDescription(order.getSalesStatus()));   //订单交易说明, 可选
        orderMap.put("tradetime",sdf.format(order.getSalesCreateDate())); //订单生成时间  必选 //交易时间(格式:yyyy-MM-dd HH:mm:ss)
        orderMap.put("payorderno","");  //支付单号
        orderMap.put("country","CN");   //国家简称
        orderMap.put("province",addressInfo[0]);    //省  必填
        orderMap.put("city",addressInfo[1]);        //市 必填
        orderMap.put("area",addressInfo[2]);        //区 必填
        orderMap.put("town",town);
        orderMap.put("address",order.getSalesAddressInfo());    //全部地址 必填
        orderMap.put("zip",order.getSalesAddressPostnum());     //邮编
        orderMap.put("phone",order.getSalesAddressTel());       //手机号码   必填
        //orderMap.put("mobile","");
       // orderMap.put("email","");
        String remark = order.getSalesUserRemark();
        if(remark == null){
            orderMap.put("customerremark","");      //买家备注
        }else{
            orderMap.put("customerremark",order.getSalesUserRemark());      //买家备注
        }

        String adminRemark = order.getSalesAdminRemark();
        if(adminRemark == null){
            orderMap.put("sellerremark",""); //卖家备注
        }else{
            orderMap.put("sellerremark",adminRemark);//卖家备注
        }

        orderMap.put("postfee",0);     //邮资
        orderMap.put("goodsfee",0);    //货款金额
        double yetAmount = order.getSalesYetAmount().intValue() / 100;
        double amount = order.getSalesAmount().intValue() / 100;
        orderMap.put("totalmoney",yetAmount);   //合计应收（针对卖家）
        orderMap.put("favourablemoney",amount-yetAmount);        //订单总优惠金额
        orderMap.put("commissionvalue",0);  //佣金
        //orderMap.put("taxamount","");   //订单税费总额
        //orderMap.put("tariffamount","");   //订单关税金额
       // orderMap.put("addedvalueamount","");   //订单增值税金额
       // orderMap.put("consumptiondutyamount","");   //订单消费税金额

        orderMap.put("sendstyle",this.getSendstyle(order.getSalesPostFirm()));   //货运方式  可选
        //orderMap.put("qq","");
        if(order.getSalesTransactionDate() != null){
            orderMap.put("paytime",sdf.format(order.getSalesTransactionDate()));     //支付时间  ，必填 支付时间(格式:yyyy-MM-dd HH:mm:ss)
        }
        //orderMap.put("invoicetitle","");    //发票抬头
        //orderMap.put("codservicefee","");   //纳税人识别号
        //orderMap.put("couponprice",""); //货币类型
        //orderMap.put("cardtype","");    //证件类型(身份证=JH_01，护照=JH_02，港澳通行证=JH_03)
        //orderMap.put("idcard","");      //证件号码
        //orderMap.put("idcardtruename","");      //证件真实姓名
        orderMap.put("receivername",order.getSalesAddressName());      //收货人真实姓名
        orderMap.put("nick",order.getUserNickname());      //必填  买家昵称
        //orderMap.put("whsecode","");      //商品所在仓库编号
        //orderMap.put("IsHwgFlag","");      //是否为海外购(是=1；否=0)
        orderMap.put("ShouldPayType","担保交易");      //必填  结算方式（可选值有：担保交易；银行收款；现金收款；货到付款；欠款记应收；客户预付款；多种结算）
        List<Map<String,Object>> goodinfos = new ArrayList<>();
        for (OrderItem orderItem: order.getOrderItemList()){
            Map<String,Object> orderItemMap = new HashMap<String,Object>();
            orderItemMap.put("ProductId",orderItem.getColorPolyCode()); //必填 平台商品ID或SKUID(SKUID优先)
            orderItemMap.put("suborderno",orderItem.getItemId());  //子订单号（若需要支持拆单发货，则必填）
            orderItemMap.put("tradegoodsno",orderItem.getColorPolyCode());    //必填  部商家编码或外部SKU编码(SKU编码优先)。注意，如果要与管家对接，这里一般返回管家的商品编码，作为平台的外部商家编码，与管家商品映射。
            orderItemMap.put("tradegoodsname",orderItem.getItemProductName());  //必填 商品交易名称
            orderItemMap.put("tradegoodsspec",orderItem.getProductColor());  //颜色    必填   商品交易规格
            orderItemMap.put("goodscount",orderItem.getItemNum());  //必填  商品数量  int
            double money = orderItem.getItemProductDiscount().intValue() / 100;
            orderItemMap.put("price",money);       //单价 必填  decimal
            orderItemMap.put("discountmoney",0);   //子订单优惠金额  decimal
            orderItemMap.put("taxamount",0);    //商品税费  decimal
            orderItemMap.put("refundStatus",this.getRefundStatus(order.getSalesStatus()));    //退款状态(没有退款=JH_07，买家已经申请退款等待卖家同意=JH_01，卖家已经同意退款等待买家退货=JH_02，买家已经退货等待卖家确认收货=JH_03，卖家拒绝退款=JH_04，退款关闭=JH_05，退款成功=JH_06，其他=JH_99)
            orderItemMap.put("Status",this.getOrderItemStatus(order.getSalesStatus()));      //子订单交易状态(其他=JH_99，等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05)
            orderItemMap.put("remark","");  //货品备注
            goodinfos.add(orderItemMap);
        }
        orderMap.put("goodinfos",goodinfos);
        return orderMap;
    }

    /***
     * 订单下载 拼接map -- 领取充电器
     * 如果不用传参数请去掉，否则有可能会报错
     * @param cr
     * @return
     */
    private  Map<String,Object> getReceive(ChargerReceive cr){
        String[] addressInfo = cr.getReceiveAddressInfo().split("-");
        String town = "";  //获取街道

        if(addressInfo.length > 3){
            Integer qu = cr.getReceiveAddressInfo().indexOf(addressInfo[3]);
            town = cr.getReceiveAddressInfo().substring(qu,cr.getReceiveAddressInfo().length());
        }

        Map<String,Object> orderMap = new HashMap<String,Object>();
        orderMap.put("PlatOrderNo",cr.getReceiveOrderId()); //订单号
        orderMap.put("tradeStatus","JH_02"); //订单状态
        orderMap.put("tradeStatusdescription","等待发货");   //订单交易说明, 可选
        orderMap.put("tradetime",sdf.format(cr.getReceiveCreateTime())); //订单生成时间  必选 //交易时间(格式:yyyy-MM-dd HH:mm:ss)
        orderMap.put("payorderno","");  //支付单号
        orderMap.put("country","CN");   //国家简称
        orderMap.put("province",addressInfo[0]);    //省  必填
        orderMap.put("city",addressInfo[1]);        //市 必填
        orderMap.put("area",addressInfo[2]);        //区 必填
        orderMap.put("town",town);
        orderMap.put("address", cr.getReceiveAddressInfo());    //全部地址 必填
        orderMap.put("zip",cr.getReceiveAddressPostnum());     //邮编
        orderMap.put("phone",cr.getReceiveAddressTel());       //手机号码   必填
        //orderMap.put("mobile","");
        // orderMap.put("email","");

        orderMap.put("customerremark","免费领取电动牙刷充电器");      //备注

        //orderMap.put("sellerremark","");
        orderMap.put("postfee",0);     //邮资
        orderMap.put("goodsfee",0);    //货款金额
        double yetAmount = cr.getReceivePostage().intValue() / 100;
        double amount = cr.getReceivePostage().intValue() / 100;
        orderMap.put("totalmoney",yetAmount);   //合计应收（针对卖家）
        orderMap.put("favourablemoney",amount-yetAmount);        //订单总优惠金额
        orderMap.put("commissionvalue",0);  //佣金
        //orderMap.put("taxamount","");   //订单税费总额
        //orderMap.put("tariffamount","");   //订单关税金额
        // orderMap.put("addedvalueamount","");   //订单增值税金额
        // orderMap.put("consumptiondutyamount","");   //订单消费税金额

        orderMap.put("sendstyle",this.getSendstyle(cr.getReceivePostFirm()));   //货运方式  可选
        //orderMap.put("qq","");
        if(cr.getReceiveTransactionDate() != null){
            orderMap.put("paytime",sdf.format(cr.getReceiveTransactionDate()));     //支付时间  ，必填 支付时间(格式:yyyy-MM-dd HH:mm:ss)
        }
        //orderMap.put("invoicetitle","");    //发票抬头
        //orderMap.put("codservicefee","");   //纳税人识别号
        //orderMap.put("couponprice",""); //货币类型
        //orderMap.put("cardtype","");    //证件类型(身份证=JH_01，护照=JH_02，港澳通行证=JH_03)
        //orderMap.put("idcard","");      //证件号码
        //orderMap.put("idcardtruename","");      //证件真实姓名
        orderMap.put("receivername",cr.getReceiveAddressName());      //收货人真实姓名
        orderMap.put("nick",cr.getUserNickname());      //必填  买家昵称
        //orderMap.put("whsecode","");      //商品所在仓库编号
        //orderMap.put("IsHwgFlag","");      //是否为海外购(是=1；否=0)
        orderMap.put("ShouldPayType","担保交易");      //必填  结算方式（可选值有：担保交易；银行收款；现金收款；货到付款；欠款记应收；客户预付款；多种结算）
        List<Map<String,Object>> goodinfos = new ArrayList<>();


//            Map<String,Object> orderItemMap = new HashMap<String,Object>();
//            orderItemMap.put("ProductId",orderItem.getColorPolyCode()); //必填 平台商品ID或SKUID(SKUID优先)
//            orderItemMap.put("suborderno",orderItem.getItemId());  //子订单号（若需要支持拆单发货，则必填）
//            orderItemMap.put("tradegoodsno",orderItem.getColorPolyCode());    //必填  部商家编码或外部SKU编码(SKU编码优先)。注意，如果要与管家对接，这里一般返回管家的商品编码，作为平台的外部商家编码，与管家商品映射。
//            orderItemMap.put("tradegoodsname",orderItem.getItemProductName());  //必填 商品交易名称
//            orderItemMap.put("tradegoodsspec",orderItem.getProductColor());  //颜色    必填   商品交易规格
//            orderItemMap.put("goodscount",orderItem.getItemNum());  //必填  商品数量  int
//            double money = orderItem.getItemProductDiscount().intValue() / 100;
//            orderItemMap.put("price",money);       //单价 必填  decimal
//            orderItemMap.put("discountmoney",0);   //子订单优惠金额  decimal
//            orderItemMap.put("taxamount",0);    //商品税费  decimal
//            orderItemMap.put("refundStatus",this.getRefundStatus(order.getSalesStatus()));    //退款状态(没有退款=JH_07，买家已经申请退款等待卖家同意=JH_01，卖家已经同意退款等待买家退货=JH_02，买家已经退货等待卖家确认收货=JH_03，卖家拒绝退款=JH_04，退款关闭=JH_05，退款成功=JH_06，其他=JH_99)
//            orderItemMap.put("Status",this.getOrderItemStatus(order.getSalesStatus()));      //子订单交易状态(其他=JH_99，等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05)
//            orderItemMap.put("remark","");  //货品备注
//            goodinfos.add(orderItemMap);


        orderMap.put("goodinfos",goodinfos);
        return orderMap;
    }

    /**
     * 设置查询的订单状态
     *
     * 本系统状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货
     * 6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     *
     * 订单交易状态(等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05，所有订单=JH_99)
     *
     * @param order
     * @param status
     */
    private void setStatus(Order order,String status){
        switch (status){
            case "JH_01":
                order.setSalesStatus(1);
                break;
            case "JH_02":
                order.setSalesStatus(2);
                break;
            case "JH_03":
                order.setSalesStatus(12);
                break;
            case "JH_04":
                order.setSalesStatus(12);
                break;
            case "JH_05":
                order.setSalesStatus(8);
                break;
            case "JH_99":
                break;
            default:
                order.setSalesStatus(2);
                break;
        }
    }

    /**
     * 返回订单状态
     *
     * 状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货
     * 6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     *
     * 订单交易状态(等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05，所有订单=JH_99)
     *
     * @param status
     * @return
     */
    private String getStatus(int status){
        switch (status){
            case 0:
                return "JH_05";
            case 1:
               return "JH_01";
            case 2:
                return "JH_02";
            case 3:
                return "JH_03";
            case 4:
                return "JH_05";
            case 5:
                return "JH_03";
            case 6:
                return "JH_03";
            case 7:
                return "JH_03";
            case 8:
               return "JH_05";
            case 9:
               return "JH_03";
            case 10:
                return "JH_05";
            case 11:
                return "JH_03";
            case 12:
                return "JH_04";
            default:
                return "JH_05";
        }
    }

    /**
     * 返回子订单退款状态（可选值）
     *
     * 本系统状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货
     * 6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     *
     * 退款状态(没有退款=JH_07，买家已经申请退款等待卖家同意=JH_01，卖家已经同意退款等待买家退货=JH_02，买家已经退货等待卖家确认收货=JH_03，
     * 卖家拒绝退款=JH_04，退款关闭=JH_05，退款成功=JH_06，其他=JH_99)
     *
     * @param status
     * @return
     */
    private String getRefundStatus(int status){
        switch (status){
            case 0:
                return "";
            case 1:
                return "";
            case 2:
                return "";
            case 3:
                return "JH_01";
            case 4:
                return "JH_06";
            case 5:
                return "";
            case 6:
                return "";
            case 7:
                return "JH_02";
            case 8:
                return "JH_06";
            case 9:
                return "";
            case 10:
                return "";
            case 11:
                return "";
            case 12:
                return "";
            default:
                return "";
        }
    }

    /**
     * 返回子订单状态（可选值）
     *
     * 本系统状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货
     * 6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     *
     * 订单交易状态(等待买家付款=JH_01，等待卖家发货=JH_02，等待买家确认收货=JH_03，交易成功=JH_04，交易关闭=JH_05，所有订单=JH_99)
     *
     * @param status
     * @return
     */
    private String getOrderItemStatus(int status){
        switch (status){
            case 0:
                return "";
            case 1:
                return "JH_01";
            case 2:
                return "JH_02";
            case 3:
                return "";
            case 4:
                return "JH_05";
            case 5:
                return "";
            case 6:
                return "";
            case 7:
                return "";
            case 8:
                return "JH_05";
            case 9:
                return "";
            case 10:
                return "";
            case 11:
                return "";
            case 12:
                return "JH_04";
            default:
                return "";
        }
    }

    /**
     * 获取订单交易说明
     * 状态  0：取消订单  1：待支付  2：已支付、待发货  3：退款申请中  4：已退款  5：已发货
     * 6：申请退货中  7：退货中  8：订单退货，订单关闭  9：换货中  10：换货完成  11申请换货中  12订单完成
     * @param status
     * @return
     */
    private String getDescription(int status){
        switch (status){
            case 0:
                return "取消订单";
            case 1:
                return "等待买家付款";
            case 2:
                return "等待发货";
            case 3:
                return "退款申请中";
            case 4:
                return "已退款";
            case 5:
                return "已发货";
            case 6:
                return "申请退货中";
            case 7:
                return "退货中";
            case 8:
                return "订单已退货";
            case 9:
                return "换货中";
            case 10:
                return "换货完成";
            case 11:
                return "申请换货中";
            case 12:
                return "订单完成";
            default:
                return "其他";
        }
    }

    /**
     * 返回配送方式
     * @param sendsStyle
     * @return
     */
    private String getSendstyle(String sendsStyle){
        String sendStyle = SendMessageUtil.hashmap.get(sendsStyle);
        if(sendStyle == null){
            sendStyle = "";
        }
        return sendStyle;
    }


    /**
     * 校验请求和返回参数
     * @param request
     * @return
     */
    private Map<String,Object> verification(HttpServletRequest request) throws Exception {

        String bizcontent =  request.getParameter("bizcontent");
        String appkey =  request.getParameter("appkey");
        String method =  request.getParameter("method");
        String token =  request.getParameter("token");
        String sign =  request.getParameter("sign");

        String polyapiAppKey = NameUtils.getConfig("polyapi_appKey");
        String polyapiAppSecret = NameUtils.getConfig("polyapi_AppSecret");
        if(appkey != null && appkey.equals(polyapiAppKey)){
            /**
             * 签名验证：
             * 将除Sign参数外的所有“参数 参数值”进行字典排序生成串，而后将AppSecret加到该串的首尾，将得到的字符串转小写,进行MD5加密，此时的生成的串即为Sign。
             */
           String signatureText = polyapiAppSecret + "appkey" + appkey + "bizcontent" + bizcontent + "method" + method + "token" + token + polyapiAppSecret;
           signatureText = signatureText.toLowerCase();
           String signaTrue = md5.GetMD5Code(signatureText);
           if(sign == null || !sign.equals(signaTrue)){
               logger.info("-----------签名验证失败---------------，signaTrue："+signaTrue);
               logger.info("-----------签名验证失败---------------，sign："+sign);
               throw new Exception("签名验证失败");
           }
           //logger.info("-----------菠萝派调用接口，签名验证通过。接口调用方法名："+method +"接口参数：" + bizcontent);
        }
        Map requstMap = (Map) JSON.parse(bizcontent);
        return requstMap;
    }

}
