package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.StringUtils;
import com.liquidnet.client.admin.zhengzai.admin.service.impl.utils.CodeUtil;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.ShunfengSignUtils;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinTableStatusConst;
import com.liquidnet.service.kylin.dao.*;
import com.liquidnet.service.kylin.dto.param.*;
import com.liquidnet.service.kylin.dto.vo.express.KylinOrderExpressRouteVo;
import com.liquidnet.service.kylin.dto.vo.express.KylinOrderExpressVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.IKylinOrderExpress;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 演出 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-05
 */
@Service
@Slf4j
public class PerformancesExpressServiceImpl extends ServiceImpl<KylinOrderExpressMapper, KylinOrderExpress> implements IKylinOrderExpress {

    @Value("${liquidnet.shunfeng.custid}")
    private String custid;
    @Value("${liquidnet.shunfeng.jCompany}")
    private String jCompany;
    @Value("${liquidnet.shunfeng.jContact}")
    private String jContact;
    @Value("${liquidnet.shunfeng.jTel}")
    private String jTel;
    @Value("${liquidnet.shunfeng.jProvince}")
    private String jProvince;
    @Value("${liquidnet.shunfeng.jCity}")
    private String jCity;
    @Value("${liquidnet.shunfeng.jAddress}")
    private String jAddress;
    @Value("${liquidnet.shunfeng.expressType}")
    private Integer expressType;
    @Value("${liquidnet.shunfeng.depositumInfo}")
    private String depositumInfo;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private ShunfengSignUtils shunfengSignUtils;

    @Autowired
    private KylinPerformancesMapper performancesMapper;

    @Autowired
    private KylinOrderTicketsMapper kylinOrderTicketsMapper;

    @Autowired
    private KylinOrderExpressMapper kylinOrderExpressMapper;

    @Autowired
    private KylinOrderExpressFeeInfoMapper kylinOrderExpressFeeInfoMapper;

    @Autowired
    private KylinOrderExpressRouteMapper kylinOrderExpressRouteMapper;

    @Autowired
    private KylinOrderExpressPerformancesMapper kylinOrderExpressPerformancesMapper;

    @Autowired
    private KylinOrderTicketRelationsMapper kylinOrderTicketRelationsMapper;

    @Autowired
    private KylinOrderTicketStatusMapper kylinOrderTicketStatusMapper;

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private CodeUtil codeUtil;

    public List<PerformanceExpressPerformanceListAdminDao> getPerformancesList(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<PerformanceExpressPerformanceListAdminDao> voList = new ArrayList();
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(performanceExpressSearchAdminParam);
            voList = performancesMapper.performanceExpressPerformanceList(map);
            if (!CollectionUtil.isEmpty(voList)) {
                for (PerformanceExpressPerformanceListAdminDao info : voList) {
                    PerformanceExpressPerformanceListAdminDao countInfo = performancesMapper.countExpressNumber(info.getPerformancesId());
                    if (null != countInfo) {
                        info.setTotalNumber(countInfo.getTotalNumber());
                    }
                }
            }
        } catch (Exception e) {
        }
        return voList;
    }

    public List<PerformanceExpressPerformanceOrderListAdminDao> getPerformancesOrderList(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<PerformanceExpressPerformanceOrderListAdminDao> voList = new ArrayList();
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(performanceExpressSearchAdminParam);
            voList = kylinOrderTicketsMapper.performanceExpressPerformanceOrderList(map);
        } catch (Exception e) {
        }
        return voList;
    }

    public ResponseDto placeOrder(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        for (String orderTicketsId : ids) {
            // 已经存在未取消的下单数据过滤掉
            Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            if (null != orderExpressInfo) {
                continue;
            }
            KylinOrderTickets orderInfo = kylinOrderTicketsMapper.selectOne(
                    new QueryWrapper<KylinOrderTickets>().eq("order_tickets_id", orderTicketsId)
            );
            KylinOrderTicketStatus orderStatus = kylinOrderTicketStatusMapper.selectOne(
                    new QueryWrapper<KylinOrderTicketStatus>().eq("order_id", orderTicketsId)
            );
            if (orderStatus.getStatus() != KylinTableStatusConst.ORDER_STATUS1 && orderStatus.getStatus() != KylinTableStatusConst.ORDER_STATUS6) {
                return ResponseDto.failure("当前状态不能下单");
            }
            // 生成预快递单 防止因失败没办法再次发起也不能主动获取数据
            KylinOrderExpress kylinOrderExpressPre = new KylinOrderExpress();
            String orderExpressId = IDGenerator.nextSnowId();
            kylinOrderExpressPre.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS1);
            kylinOrderExpressPre.setOrderExpressId(orderExpressId);
            kylinOrderExpressPre.setOrderTicketsId(orderTicketsId);
            // 防止重复前面加上 "NEW" 因取消后再发起订单号也不能一致所有后面做补位操作
            Integer placeCount = kylinOrderExpressMapper.selectCount(
                    new QueryWrapper<KylinOrderExpress>()
                            .eq("order_tickets_id", orderTicketsId)
            );
            String codeNum = StringUtils.leftPad(String.valueOf(placeCount), 3, "0");
            String OrderExpressCode = "NEW" + orderInfo.getOrderCode().concat(codeNum);
            kylinOrderExpressPre.setOrderExpressCode(OrderExpressCode);
            kylinOrderExpressPre.setExpressType(expressType);
            kylinOrderExpressPre.setCreatedAt(DateUtil.getNowTime());
            kylinOrderExpressMapper.insert(kylinOrderExpressPre);

            // 请求下单数据
            Map<String, String> hBody = new HashMap<>();
            hBody.put("custid", custid);
            hBody.put("jCompany", jCompany);
            hBody.put("jContact", jContact);
            hBody.put("jTel", jTel);
            hBody.put("jProvince", jProvince);
            hBody.put("jCity", jCity);
            hBody.put("jAddress", jAddress);

            // TODO: 2021/6/30 前端选择
            hBody.put("payMethod", "2");// 运费付款方式：0-寄付月结；1-寄付现结；2-收方付；3-第三方付；
            hBody.put("expressType", expressType.toString());// 顺丰特快

            hBody.put("depositumInfo", depositumInfo);

            hBody.put("orderId", OrderExpressCode);

            hBody.put("depositumNo", orderInfo.getNumber().toString());

            hBody.put("dContact", orderInfo.getExpressContacts());
            hBody.put("dMobile", orderInfo.getExpressPhone());
            hBody.put("dAddress", orderInfo.getExpressAddress());

            // 生成签名并请求
            String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/placeOrder");
            System.out.println(result);
            HashMap hashMap = new HashMap();
            try {
                hashMap = JsonUtils.fromJson(result, HashMap.class);
            } catch (Exception e) {
                return ResponseDto.failure(result);
            }
            if (null == hashMap.get("succ") || hashMap.get("succ").equals("fail")) {
                String msg = "";
                if (null == hashMap.get("succ")) {
                    msg = result;
                } else {
                    msg = (String) hashMap.get("msg");
                }
                return ResponseDto.failure(msg);
            } else {
                HashMap hashMapResult = (HashMap) hashMap.get("result");
                KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS2);
                kylinOrderExpress.setMailno((String) hashMapResult.get("mailno"));
                kylinOrderExpress.setFilterResult(hashMapResult.get("filter_result").toString());
                kylinOrderExpress.setRemark((String) hashMapResult.get("remark"));
                kylinOrderExpress.setOrigincode((String) hashMapResult.get("origincode"));
                kylinOrderExpress.setDestcode((String) hashMapResult.get("destcode"));
                kylinOrderExpress.setTwoDimensionCode((String) hashMapResult.get("twoDimensionCode"));

                kylinOrderExpress.setReturn_tracking_no((String) hashMapResult.get("return_tracking_no"));
                kylinOrderExpress.setSourceTransferCode((String) hashMapResult.get("sourceTransferCode"));
                kylinOrderExpress.setSourceCityCode((String) hashMapResult.get("sourceCityCode"));
                kylinOrderExpress.setSourceDeptCode((String) hashMapResult.get("sourceDeptCode"));
                kylinOrderExpress.setSourceTeamCode((String) hashMapResult.get("sourceTeamCode"));
                kylinOrderExpress.setDestCityCode((String) hashMapResult.get("destCityCode"));
                kylinOrderExpress.setDestDeptCode((String) hashMapResult.get("destDeptCode"));
                kylinOrderExpress.setDestDeptCodeMapping((String) hashMapResult.get("destDeptCodeMapping"));
                kylinOrderExpress.setDestTeamCode((String) hashMapResult.get("destTeamCode"));
                kylinOrderExpress.setDestTeamCodeMapping((String) hashMapResult.get("destTeamCodeMapping"));
                kylinOrderExpress.setDestTransferCode((String) hashMapResult.get("destTransferCode"));
                kylinOrderExpress.setDestRouteLabel((String) hashMapResult.get("destRouteLabel"));
                kylinOrderExpress.setProName((String) hashMapResult.get("proName"));
                kylinOrderExpress.setCargoTypeCode((String) hashMapResult.get("cargoTypeCode"));
                kylinOrderExpress.setLimitTypeCode((String) hashMapResult.get("limitTypeCode"));
                kylinOrderExpress.setExpressTypeCode((String) hashMapResult.get("expressTypeCode"));
                kylinOrderExpress.setCodingMapping((String) hashMapResult.get("codingMapping"));
                kylinOrderExpress.setCodingMappingOut((String) hashMapResult.get("codingMappingOut"));
                kylinOrderExpress.setXbFlag((String) hashMapResult.get("xbFlag"));
                kylinOrderExpress.setPrintFlag((String) hashMapResult.get("printFlag"));
                kylinOrderExpress.setProCode((String) hashMapResult.get("proCode"));
                kylinOrderExpress.setPrintIcon((String) hashMapResult.get("printIcon"));
                kylinOrderExpress.setAbFlag((String) hashMapResult.get("abFlag"));
                kylinOrderExpress.setDestPortCode((String) hashMapResult.get("destPortCode"));
                kylinOrderExpress.setDestPortCode((String) hashMapResult.get("destPortCode"));
                kylinOrderExpress.setDestCountry((String) hashMapResult.get("destCountry"));
                kylinOrderExpress.setDestPostCode((String) hashMapResult.get("destPostCode"));
                kylinOrderExpress.setGoodsValueTotal((String) hashMapResult.get("goodsValueTotal"));
                kylinOrderExpress.setCurrencySymbol((String) hashMapResult.get("currencySymbol"));
                kylinOrderExpress.setGoodsNumber((String) hashMapResult.get("goodsNumber"));
                kylinOrderExpress.setTwoDimensionCode2((String) hashMapResult.get("twoDimensionCode2"));
                kylinOrderExpress.setNewIcon((String) hashMapResult.get("newIcon"));
                kylinOrderExpress.setNewAbflag((String) hashMapResult.get("newAbflag"));

                kylinOrderExpress.setUpdatedAt(DateUtil.getNowTime());
                kylinOrderExpressMapper.update(
                        kylinOrderExpress
                        , new UpdateWrapper<KylinOrderExpress>().in("order_express_id", orderExpressId)
                );

                KylinOrderExpressVo kylinOrderExpressVo = new KylinOrderExpressVo();
                BeanUtils.copyProperties(kylinOrderExpressPre, kylinOrderExpressVo);
                kylinOrderExpressVo.setMailno(kylinOrderExpress.getMailno());
                kylinOrderExpressVo.setExpressStatus(kylinOrderExpress.getExpressStatus());
                dataUtils.setOrderExpressInfo(orderTicketsId, kylinOrderExpressVo);

                // 记录演出数量
                KylinOrderTicketRelations relationsInfo = kylinOrderTicketRelationsMapper.selectOne(new QueryWrapper<KylinOrderTicketRelations>().eq("order_id", orderTicketsId));
                KylinOrderExpressPerformances expressPerformances = kylinOrderExpressPerformancesMapper.selectOne(new QueryWrapper<KylinOrderExpressPerformances>().eq("performances_id", relationsInfo.getPerformanceId()));
                KylinOrderExpressPerformances kylinOrderExpressPerformances = new KylinOrderExpressPerformances();
                if (null == expressPerformances) {
                     String orderExpressPerformancesId = IDGenerator.nextSnowId();
                     kylinOrderExpressPerformances.setOrderExpressPerformancesId(orderExpressPerformancesId);
                     kylinOrderExpressPerformances.setPerformancesId(relationsInfo.getPerformanceId());
                     kylinOrderExpressPerformances.setTotal1(1);
                    kylinOrderExpressPerformances.setCreatedAt(DateUtil.getNowTime());
                    kylinOrderExpressPerformancesMapper.insert(kylinOrderExpressPerformances);
                 } else {
                    kylinOrderExpressPerformances.setTotal1(expressPerformances.getTotal1() + 1);
                    kylinOrderExpressPerformances.setUpdatedAt(DateUtil.getNowTime());
                    kylinOrderExpressPerformancesMapper.update(kylinOrderExpressPerformances,
                            new QueryWrapper<KylinOrderExpressPerformances>().eq("performances_id", relationsInfo.getPerformanceId()));
                 }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto cancelOrder(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        log.error("cancelOrder {}", "");
        log.info("cancelOrder {}", "");
        log.debug("cancelOrder {}", "");
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
        for (String orderTicketsId : ids) {
            log.error("id {}", orderTicketsId);
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            if (null != orderExpressInfo) {
                log.error("orderExpressInfo {}", "true");
                Map<String, String> hBody = new HashMap<>();
                hBody.put("orderId", orderExpressInfo.getOrderExpressCode());

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/cancelOrder");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                log.error("result {}", result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                    kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS3);
                    kylinOrderExpress.setUpdatedAt(DateUtil.getNowTime());
                    kylinOrderExpressMapper.update(
                            kylinOrderExpress
                            , new UpdateWrapper<KylinOrderExpress>().in("order_express_id", orderExpressInfo.getOrderExpressId())
                    );
                    dataUtils.delOrderExpressInfo(orderTicketsId);
                    mongoTemplate.remove(Query.query(Criteria.where("orderTicketsId").is(orderTicketsId)), KylinOrderExpressRouteVo.class.getSimpleName());

                    // 记录演出数量
                    KylinOrderTicketRelations relationsInfo = kylinOrderTicketRelationsMapper.selectOne(new QueryWrapper<KylinOrderTicketRelations>().eq("order_id", orderTicketsId));
                    KylinOrderExpressPerformances expressPerformances = kylinOrderExpressPerformancesMapper.selectOne(new QueryWrapper<KylinOrderExpressPerformances>().eq("performances_id", relationsInfo.getPerformanceId()));
                    KylinOrderExpressPerformances kylinOrderExpressPerformances = new KylinOrderExpressPerformances();
                    if (null != expressPerformances) {
                        kylinOrderExpressPerformances.setTotal1(expressPerformances.getTotal1() - 1);
                        kylinOrderExpressPerformances.setUpdatedAt(DateUtil.getNowTime());
                        kylinOrderExpressPerformancesMapper.update(kylinOrderExpressPerformances,
                                new QueryWrapper<KylinOrderExpressPerformances>().eq("performances_id", relationsInfo.getPerformanceId()));
                    }
                }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto getResult(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            if (null != orderExpressInfo) {
                Map<String, String> hBody = new HashMap<>();
                hBody.put("orderId", orderExpressInfo.getOrderExpressCode());
                hBody.put("searchType", "1"); //查询类型：1,正向单查询，传入的orderid为正向定单号，2，退货单查询，传入的orderid为退货原始订单号

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/getResult");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    HashMap hashMapResult = (HashMap) hashMap.get("result");
                    KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                    kylinOrderExpress.setExpressStatus(KylinTableStatusConst.ORDER_EXPRESS_STATUS2);
                    kylinOrderExpress.setMailno((String) hashMapResult.get("mailno"));
                    kylinOrderExpress.setFilterResult(hashMapResult.get("filter_result").toString());
                    kylinOrderExpress.setRemark((String) hashMapResult.get("remark"));
                    kylinOrderExpress.setOrigincode((String) hashMapResult.get("origincode"));
                    kylinOrderExpress.setDestcode((String) hashMapResult.get("destcode"));
                    kylinOrderExpress.setPrintIcon((String) hashMapResult.get("printIcon"));
                    kylinOrderExpress.setPrintFlag((String) hashMapResult.get("printFlag"));
                    kylinOrderExpress.setTwoDimensionCode((String) hashMapResult.get("twoDimensionCode"));
                    kylinOrderExpress.setUpdatedAt(DateUtil.getNowTime());
                    kylinOrderExpressMapper.update(
                            kylinOrderExpress
                            , new UpdateWrapper<KylinOrderExpress>().in("order_express_id", orderExpressInfo.getOrderExpressId())
                    );
                }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto getFreight(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            KylinOrderTickets orderInfo = kylinOrderTicketsMapper.selectOne(
                    new QueryWrapper<KylinOrderTickets>().eq("order_tickets_id", orderTicketsId)
            );
            if (null != orderExpressInfo) {
                Map<String, String> hBody = new HashMap<>();
                hBody.put("jProvince", jProvince);
                hBody.put("jCity", jCity);
                hBody.put("jAddress", jAddress);

                hBody.put("dProvince", orderInfo.getProvince());
                hBody.put("dCity", orderInfo.getCity());
                hBody.put("dAddress", orderInfo.getExpressAddress());
                hBody.put("expressType", expressType.toString());
                // hBody.put("parcelWeighs", 2.00);
                // hBody.put("volume", "10,10,20");

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/getFreight");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    HashMap hashMapResult = (HashMap) hashMap.get("result");
                    KylinOrderExpress kylinOrderExpress = new KylinOrderExpress();
                    BigDecimal price = dataUtils.getBigDecimal(hashMapResult.get("price"));
                    kylinOrderExpress.setFreightPrice(price);
                    kylinOrderExpress.setUpdatedAt(DateUtil.getNowTime());
                    kylinOrderExpressMapper.update(
                            kylinOrderExpress
                            , new UpdateWrapper<KylinOrderExpress>().in("order_express_id", orderExpressInfo.getOrderExpressId())
                    );
                    // {"result":{"deliverTime":"2021-07-01 18:00:00,2021-07-01 18:00:00","price":"23元","businessTypeDesc":"顺丰特快","businessType":"1"},"succ":"ok","msg":null}
                }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto getListFreight(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            if (null != orderExpressInfo) {
                Map<String, String> hBody = new HashMap<>();
                hBody.put("orderId", orderExpressInfo.getOrderExpressCode());

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/getListFreight");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    HashMap resultResult = (HashMap) hashMap.get("result");
                    List<HashMap> feeList = (List) resultResult.get("feeList");
                    if (!CollectionUtil.isEmpty(feeList)) {
                        kylinOrderExpressFeeInfoMapper.delete(new QueryWrapper<KylinOrderExpressFeeInfo>().eq("order_express_id", orderExpressInfo.getOrderExpressId()));
                        for (HashMap feeInfo : feeList) {
                            KylinOrderExpressFeeInfo kylinOrderExpressFeeInfo = new KylinOrderExpressFeeInfo();
                            String orderExpressFeeInfoId = IDGenerator.nextSnowId();
                            kylinOrderExpressFeeInfo.setOrderExpressFeeInfoId(orderExpressFeeInfoId);
                            kylinOrderExpressFeeInfo.setOrderExpressId(orderExpressInfo.getOrderExpressId());
                            kylinOrderExpressFeeInfo.setType((String) feeInfo.get("type"));
                            kylinOrderExpressFeeInfo.setName((String) feeInfo.get("name"));
                            kylinOrderExpressFeeInfo.setValue(new BigDecimal(feeInfo.get("value").toString()));
                            kylinOrderExpressFeeInfo.setCreatedAt(DateUtil.getNowTime());
                            kylinOrderExpressFeeInfoMapper.insert(kylinOrderExpressFeeInfo);
                        }
                    }
                }
            }
        }
        return ResponseDto.success();
    }

    public ResponseDto listOrderRoute(PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam) {
        List<String> ids = performanceExpressSearchAdminParam.getIds();
        Integer[] expressStatus = {KylinTableStatusConst.ORDER_EXPRESS_STATUS1, KylinTableStatusConst.ORDER_EXPRESS_STATUS3};
        for (String orderTicketsId : ids) {
            KylinOrderExpress orderExpressInfo = kylinOrderExpressMapper.selectOne(
                    new QueryWrapper<KylinOrderExpress>().eq("order_tickets_id", orderTicketsId)
                            .notIn("express_status", expressStatus)
            );
            if (null != orderExpressInfo) {
                Map<String, String> hBody = new HashMap<>();
                hBody.put("orderId", orderExpressInfo.getOrderExpressCode());

                // 生成签名并请求
                String result = shunfengSignUtils.generateSignatureAndRequestNew(hBody, "/public/order/v1/listOrderRoute");
                HashMap hashMap = JsonUtils.fromJson(result, HashMap.class);
                System.out.println(result);
                if (hashMap.get("succ").equals("fail")) {
                    String msg = (String) hashMap.get("msg");
                    return ResponseDto.failure(msg);
                } else {
                    List<HashMap> resultResult = (List) hashMap.get("result");
                    if (!CollectionUtil.isEmpty(resultResult)) {
                        kylinOrderExpressRouteMapper.delete(new QueryWrapper<KylinOrderExpressRoute>().eq("order_express_id", orderExpressInfo.getOrderExpressId()));
                        for (HashMap routeInfo : resultResult) {
                            KylinOrderExpressRoute kylinOrderExpressRoute = new KylinOrderExpressRoute();
                            String orderExpressRouteId = IDGenerator.nextSnowId();
                            kylinOrderExpressRoute.setOrderExpressRouteId(orderExpressRouteId);
                            kylinOrderExpressRoute.setOrderExpressId(orderExpressInfo.getOrderExpressId());
                            kylinOrderExpressRoute.setAcceptAddress((String) routeInfo.get("accept_address"));
                            kylinOrderExpressRoute.setAcceptDate((String) routeInfo.get("accept_date"));
                            kylinOrderExpressRoute.setAcceptTime((String) routeInfo.get("accept_time"));
                            kylinOrderExpressRoute.setAcceptTotaltime((String) routeInfo.get("accept_totaltime"));
                            kylinOrderExpressRoute.setRemark((String) routeInfo.get("remark"));
                            kylinOrderExpressRoute.setOpcode((String) routeInfo.get("opcode"));
                            kylinOrderExpressRoute.setCreatedAt(DateUtil.getNowTime());
                            kylinOrderExpressRouteMapper.insert(kylinOrderExpressRoute);
                            // 这里没清缓存 推送正常的话这个用不到
                        }
                    }
                }
            }
        }
        return ResponseDto.success();
    }

    //    @Async
    public void batchPlaceOrder(String performanceId) {
        int count;
        int limitNum = 1;
        int mid = 0;
        do {
            List<KylinOrderTickets> orderList = kylinOrderTicketsMapper.getCanPlaceOrderList(performanceId, mid, limitNum);

            if (!CollectionUtil.isEmpty(orderList)) {
                List<String> orderIds = orderList.stream().map(KylinOrderTickets -> KylinOrderTickets.getOrderTicketsId()).collect(Collectors.toList());
                PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam = new PerformanceExpressSearchAdminParam();
                performanceExpressSearchAdminParam.setIds(orderIds);
                placeOrder(performanceExpressSearchAdminParam);
            }

            count = orderList.size();
            if (count > 0) {
                KylinOrderTickets lastInfo = orderList.get(count - 1);
                mid = lastInfo.getMid();
            }
        } while (count >= limitNum);
    }

    //    @Async
    public void batchCancelOrder(String performanceId) {
        int count;
        int limitNum = 1;
        int mid = 0;
        do {
            List<KylinOrderTickets> orderList = kylinOrderTicketsMapper.getCanCancelOrderList(performanceId, mid, limitNum);

            if (!CollectionUtil.isEmpty(orderList)) {
                List<String> orderIds = orderList.stream().map(KylinOrderTickets -> KylinOrderTickets.getOrderTicketsId()).collect(Collectors.toList());
                PerformanceExpressSearchAdminParam performanceExpressSearchAdminParam = new PerformanceExpressSearchAdminParam();
                performanceExpressSearchAdminParam.setIds(orderIds);
                cancelOrder(performanceExpressSearchAdminParam);
            }

            count = orderList.size();
            if (count > 0) {
                KylinOrderTickets lastInfo = orderList.get(count - 1);
                mid = lastInfo.getMid();
            }
        } while (count >= limitNum);
    }

    public void print() {
        String html = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<body>\n" +
                "\t<!-- 顺丰快递面单打印，尺寸：100mm*150mm模版 -->\n" +
                "\t<div\n" +
                "\t\tid=\"shunfeng-express\"\n" +
                "\t\tstyle=\"width: 96mm;\n" +
                "\t\t\theight: 150mm;\n" +
                "\t\t\tpadding-top: 5mm;\n" +
                "\t\t\tborder: 1px solid #000;\n" +
                "\t\t\ttext-align: center;\"\n" +
                "\t>\n" +
                "\t\t<!-- 1. 运单打印系统来源及时间等 -->\n" +
                "\t\t<div \n" +
                "\t\t\tclass=\"sourceAndPrintTime\"\n" +
                "\t\t\tstyle=\"width: 100%;\n" +
                "\t\t\t\tfont-family: 宋体;\n" +
                "\t\t\t\tfont-size: 4pt;\n" +
                "\t\t\t\tdisplay: flex;\n" +
                "\t\t\t\tflex-direction: row;\n" +
                "\t\t\t\tjustify-content: space-between;\n" +
                "\t\t\t\talign-items: flex-end;\"\n" +
                "\t\t>\n" +
                "\t\t\t<!-- 1.1 打印系统来源(太长放不下了，所以去掉了) -->\n" +
                "\t\t\t<!-- <div class=\"source\">\n" +
                "\t\t\t\tSCP顺丰云打印\n" +
                "\t\t\t</div> -->\n" +
                "\t\t\t<!-- 1.2 打印次数/时间 -->\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"printTime\"\n" +
                "\t\t\t\tstyle=\"width: 50%;\n" +
                "\t\t\t\t\tfont-family: 宋体;\n" +
                "\t\t\t\t\tfont-size: 4pt;\n" +
                "\t\t\t\t\tdisplay: flex;\n" +
                "\t\t\t\t\tflex-direction: row;\n" +
                "\t\t\t\t\tjustify-content: center;\n" +
                "\t\t\t\t\talign-items: flex-end;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t第一次打印 2020-05-05 12:00 第8/10个\n" +
                "\t\t\t</div>\n" +
                "\t\t\t<!-- 3  时效类型 -->\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"timeOfDeliveryType\"\n" +
                "\t\t\t\tstyle=\"font-family: 黑体;\n" +
                "\t\t\t\t\tfont-size: 18pt;\n" +
                "\t\t\t\t\tfont-weight: bolder;\n" +
                "\t\t\t\t\tmargin-right: 2mm;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t<!-- 3.1 特快即日、特快A、特快、标快、标快陆运、特惠、电商标快 -->\n" +
                "\t\t\t\t特快\n" +
                "\t\t\t</div>\n" +
                "\t\t</div>\n" +
                "\n" +
                "\n" +
                "\t\t<!-- 2. 条码区 -->\n" +
                "\t\t<div class=\"barCodeArea\">\n" +
                "\t\t\t<!-- 2.1 条码 -->\n" +
                "\t\t\t<div class=\"barCode\">\n" +
                "\t\t\t\t<img src=\"https://img.zhengzai.tv/static/img/logo_small.png\" style=\"width: 90%; height: 13mm; margin: 0 5mm;\">\n" +
                "\t\t\t</div>\n" +
                "\t\t\t<!-- 2.2 子母件单号、汉字、件数标识、 -->\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"childAndParentParts\"\n" +
                "\t\t\t\tstyle=\"font-family: 黑体;\n" +
                "\t\t\t\t\tfont-size: 10pt;\n" +
                "\t\t\t\t\tdisplay: flex;\n" +
                "\t\t\t\t\tflex-direction: column;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t<div>\n" +
                "\t\t\t\t\t子单号：SF1 010 874 393 776\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t\t<div>\n" +
                "\t\t\t\t\t母单号：SF1 010 874 393 776\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t</div>\n" +
                "\t\t</div>\n" +
                "\n" +
                "\t\t<!-- 4\t目的地 -->\n" +
                "\t\t<!-- 4.1 路由信息  暂无-->\n" +
                "\t\t<div \n" +
                "\t\t\tclass=\"destinationArea\"\n" +
                "\t\t\tstyle=\"margin: 0 auto;\n" +
                "\t\t\t\tborder: 1px solid #000;\n" +
                "\t\t\t\tborder-bottom: none;\n" +
                "\t\t\t\twidth: 92mm;\"\n" +
                "\t\t>\n" +
                "\t\t\t<!-- 2.3 运单号 -->\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"expressNumber\"\n" +
                "\t\t\t\tstyle=\"font-size: 22pt; font-weight: bold;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t755W-BA-0123456789\n" +
                "\t\t\t</div>\n" +
                "\t\t\t<!-- 5\t收方信息 -->\t\n" +
                "\t\t\t<div class=\"destinationInfo\" style=\"text-align: left;\">\n" +
                "\t\t\t\t<!-- 5.1 收 -->\n" +
                "\t\t\t\t<div class=\"imgShou\" style=\"display: inline-block; width: 9mm; text-align: center;\">\n" +
                "\t\t\t\t\t<img src=\"./images/iconShou.png\" style=\"width:7mm; height:7mm\">\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t\t<!-- 5.2 收件人姓名/电话/地址 -->\n" +
                "\t\t\t\t<div\n" +
                "\t\t\t\t\tclass=\"recipientInfo\"\n" +
                "\t\t\t\t\tstyle=\"display: inline-block; width: 62mm; font-family: 宋体; font-size: 9pt; text-align: left;\"\n" +
                "\t\t\t\t>\n" +
                "\t\t\t\t\t<div>\n" +
                "\t\t\t\t\t\t<span>收货姓名</span>\n" +
                "\t\t\t\t\t\t<span>18510980989</span>\n" +
                "\t\t\t\t\t</div>\n" +
                "\t\t\t\t\t<div>\n" +
                "\t\t\t\t\t\t<span>收货地址北京市朝阳区摩登天空测试地址</span>\n" +
                "\t\t\t\t\t</div>\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t\t<!-- 5.3 单元区域编码 暂无-->\n" +
                "\t\t\t\t<!-- 6\t代收货款 -->\n" +
                "\t\t\t\t<div class=\"iconCOD\" style=\"display: inline-block;\">\n" +
                "\t\t\t\t\t<!-- 6.1 COD -->\n" +
                "\t\t\t\t\t<img src=\"./images/COD.jpg\" style=\"width: 17mm; height:9mm\">\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t</div>\n" +
                "\t\t</div>\n" +
                "\n" +
                "\t\t<table\n" +
                "\t\t\tclass=\"QrCodeArea\"\n" +
                "\t\t\tborder=\"1\"\n" +
                "\t\t\tstyle=\"margin: 0 auto; border: 1px solid #000; width: 92.5mm; border-collapse:collapse;\"\n" +
                "\t\t>\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<td class=\"daofuInfo\" style=\"font-family: 宋体; font-size: 9pt;\">\n" +
                "\t\t\t\t\t到付22元\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t\t<td rowspan=\"3\" class=\"QrCode\">\n" +
                "\t\t\t\t\t<img src=\"./images/erweima.png\" style=\"width: 25mm; height: 25mm\">\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t\t<!-- 13\t已验视 -->\n" +
                "\t\t\t\t<td\n" +
                "\t\t\t\t\trowspan=\"3\"\n" +
                "\t\t\t\t\tclass=\"yiyanshiInfo\"\n" +
                "\t\t\t\t\tstyle=\"font-family: 黑体; font-size: 22pt; font-weight: bold; color: #272727b3; writing-mode: vertical-lr;\"\n" +
                "\t\t\t\t>\n" +
                "\t\t\t\t\t已验视\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t\t<!-- 产品名称\t限时限时KC24字段 -->\n" +
                "\t\t\t\t<td\n" +
                "\t\t\t\t\trowspan=\"2\"\n" +
                "\t\t\t\t\tclass=\"limitTime\"\n" +
                "\t\t\t\t\tstyle=\"font-family: 宋体; font-size: 12pt; width: 20mm;\"\n" +
                "\t\t\t\t>\n" +
                "\t\t\t\t\t限时\n" +
                "\t\t\t\t\tKC24\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<td rowspan=\"2\" class=\"jigangInfo\" style=\"font-family: 黑体; font-size: 22pt; font-weight: bold;\">\n" +
                "\t\t\t\t\tA22\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<td class=\"\">\n" +
                "\t\t\t\t\t1A\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t</table>\n" +
                "\n" +
                "\t\t<!-- 14\t寄方信息 -->\n" +
                "\t\t<div\n" +
                "\t\t\tclass=\"jiInfo\"\n" +
                "\t\t\tstyle=\"border-left: 1px solid #000;\n" +
                "\t\t\t\tborder-right: 1px solid #000;\n" +
                "\t\t\t\twidth: 92mm;\n" +
                "\t\t\t\tmargin: 0 auto;\n" +
                "\t\t\t\ttext-align: left;\"\n" +
                "\t\t>\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"imgShou\"\n" +
                "\t\t\t\tstyle=\"display: inline-block; width: 9mm; text-align: center;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t<img src=\"./images/iconJi.png\" style=\"width:7mm; height:7mm\">\n" +
                "\t\t\t</div>\n" +
                "\t\t\t<!-- 14.1 寄件人人姓名/电话/地址 -->\n" +
                "\t\t\t<div\n" +
                "\t\t\t\tclass=\"recipientInfo\" \n" +
                "\t\t\t\tstyle=\"display: inline-block; width: 62mm; font-family: 宋体; font-size: 9pt; text-align: left;\"\n" +
                "\t\t\t>\n" +
                "\t\t\t\t<div>\n" +
                "\t\t\t\t\t<span>寄件人姓名</span>\n" +
                "\t\t\t\t\t<span>18510980989</span>\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t\t<div>\n" +
                "\t\t\t\t\t<span>寄件地址北京市朝阳区摩登天空测试地址</span>\n" +
                "\t\t\t\t</div>\n" +
                "\t\t\t</div>\n" +
                "\t\t</div>\n" +
                "\t\t\n" +
                "\t\t<table\n" +
                "\t\t\tclass=\"otherInfo\"\n" +
                "\t\t\tborder=\"1\"\n" +
                "\t\t\tstyle=\"\n" +
                "\t\t\t\tmargin: 0 auto;\n" +
                "\t\t\t\tborder: 1px solid #000;\n" +
                "\t\t\t\twidth: 92.5mm;\n" +
                "\t\t\t\tfont-family: 宋体;\n" +
                "\t\t\t\tfont-size: 9pt;\n" +
                "\t\t\t\ttext-align: left;\n" +
                "\t\t\t\tborder-collapse:collapse;\"\n" +
                "\t\t>\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<!-- 15\t托寄物 -->\n" +
                "\t\t\t\t<td rowspan=\"2\">\n" +
                "\t\t\t\t\t托寄物：\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t\t<!-- 16\t增值服务 -->\n" +
                "\t\t\t\t<td>\n" +
                "\t\t\t\t\t增值服务：\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t\t<!-- 17\t其他信息 -->\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<!-- 17. 1重量 -->\n" +
                "\t\t\t\t<!-- 17.2 付款方式、费用等 -->\n" +
                "\t\t\t\t<td>\n" +
                "\t\t\t\t\t<div>计费重量：1kg</div>\n" +
                "\t\t\t\t\t<div>实际重量： 1kg</div>\n" +
                "\t\t\t\t\t<div>费用合计：22元</div>\n" +
                "\t\t\t\t\t<div>付款方式：寄付现结</div>\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t\t<tr>\n" +
                "\t\t\t\t<!-- 18\t客户自定义区 -->\n" +
                "\t\t\t\t<td>\n" +
                "\t\t\t\t\t客户自定义区\n" +
                "\t\t\t\t\t备注\n" +
                "\t\t\t\t\t转寄协议客户\n" +
                "\t\t\t\t\t订单等信息\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t\t<!-- 19\t图标区域 -->\n" +
                "\t\t\t\t<td>\n" +
                "\t\t\t\t\t图标区域\n" +
                "\t\t\t\t\t贴纸信息\n" +
                "\t\t\t\t</td>\n" +
                "\t\t\t</tr>\n" +
                "\t\t</table>\n" +
                "\t\t\n" +
                "\t</div>\n" +
                "</body>\n" +
                "\n" +
                "\n" +
                "</html>";
//        codeUtil.html2img(html);
    }

}
