package com.sqx.modules.utils.fieYun;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sqx.common.utils.Result;
import com.sqx.modules.activity.service.ActivityService;
import com.sqx.modules.activity.vo.ActivityOrderVO;
import com.sqx.modules.activity.vo.ActivityVO;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.entity.TbCoupon;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.coupon.service.TbCouponService;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.service.GoodsShopService;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.printInfo.entity.*;
import com.sqx.modules.printInfo.service.PrintInfoDetailService;
import com.sqx.modules.printInfo.service.PrintInfoService;
import com.sqx.modules.printInfo.service.PrintInfoShopService;
import com.sqx.modules.utils.fieYun.model.OrderForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
public class FeiYunUtils {
    private static ActivityService activityService;

    private static UserService userService;

    private static TbCouponService tbCouponService;

    private static GoodsShopService goodsShopService;

    private static CommonInfoService commonInfoService;

    private static PrintInfoShopService printInfoShopService;

    private static PrintInfoService printInfoService;

    private static AppOrderService appOrderService;

    private static PrintInfoDetailService printInfoDetailService;

    @Autowired
    public void setPrintInfoDetailService(PrintInfoDetailService printInfoDetailService) {
        FeiYunUtils.printInfoDetailService = printInfoDetailService;
    }

    @Autowired
    public void setAppOrderService(AppOrderService appOrderService) {
        FeiYunUtils.appOrderService = appOrderService;
    }

    @Autowired
    public void setActivityService(ActivityService activityService) {
        FeiYunUtils.activityService = activityService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        FeiYunUtils.userService = userService;
    }

    @Autowired
    public void setTbCouponService(TbCouponService tbCouponService) {
        FeiYunUtils.tbCouponService = tbCouponService;
    }

    @Autowired
    public void setGoodsShopService(GoodsShopService goodsShopService) {
        FeiYunUtils.goodsShopService = goodsShopService;
    }

    @Autowired
    public void setCommonInfoService(CommonInfoService commonInfoService) {
        FeiYunUtils.commonInfoService = commonInfoService;
    }

    @Autowired
    public void setPrintInfoShopService(PrintInfoShopService printInfoShopService) {
        FeiYunUtils.printInfoShopService = printInfoShopService;
    }

    @Autowired
    public void setPrintInfoService(PrintInfoService printInfoService) {
        FeiYunUtils.printInfoService = printInfoService;
    }

    /**
     * 添加打印机接口
     *
     * @param snlist 提示：打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100行(台)。
     * @return 正确例子：{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999  （错误：识别码不正确）"]},"serverExecutedTime":3}
     * 错误：{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37}
     */
    public static String addprinter(String snlist) {
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printerAddlist"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("printerContent", snlist));

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }

    /**
     * 修改打印机接口
     *
     * @param snlist 提示：打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100行(台)。
     * @return 正确例子：{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999  （错误：识别码不正确）"]},"serverExecutedTime":3}
     * 错误：{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37}
     */
    public static String updatePrinter(String snlist, String name) {
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printerEdit"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", snlist));
        nvps.add(new BasicNameValuePair("name", name));
        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 删除打印机接口
     *
     * @param snlist 提示：打印机编号(必填) # 打印机识别码(必填) # 备注名称(选填) # 流量卡号码(选填)，多台打印机请换行（\n）添加新打印机信息，每次最多100行(台)。
     * @return 正确例子：{"msg":"ok","ret":0,"data":{"ok":["sn#key#remark#carnum","316500011#abcdefgh#快餐前台"],"no":["316500012#abcdefgh#快餐前台#13688889999  （错误：识别码不正确）"]},"serverExecutedTime":3}
     * 错误：{"msg":"参数错误 : 该帐号未注册.","ret":-2,"data":null,"serverExecutedTime":37}
     */
    public static String deletePrinter(String snlist) {
        try {
            String URL = commonInfoService.findOne(325).getValue();
            String USER = commonInfoService.findOne(326).getValue();
            String UKEY = commonInfoService.findOne(327).getValue();
            //通过POST请求，发送打印信息到服务器
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(30000)//读取超时
                    .setConnectTimeout(30000)//连接超时
                    .build();

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(requestConfig)
                    .build();

            HttpPost post = new HttpPost(URL);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("user", USER));
            String STIME = String.valueOf(System.currentTimeMillis() / 1000);
            nvps.add(new BasicNameValuePair("stime", STIME));
            nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
            nvps.add(new BasicNameValuePair("apiname", "Open_printerDelList"));//固定值,不需要修改
            nvps.add(new BasicNameValuePair("snlist", snlist));

            CloseableHttpResponse response = null;
            String result = null;
            try {
                post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
                response = httpClient.execute(post);
                int statecode = response.getStatusLine().getStatusCode();
                if (statecode == 200) {
                    HttpEntity httpentity = response.getEntity();
                    if (httpentity != null) {
                        result = EntityUtils.toString(httpentity);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    post.abort();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除打印机异常:" + e.getMessage(), e);
        }
        return null;
    }


    /**
     * 小票机打印订单接口
     *
     * @param sn       打印机编号
     * @param classify 分类 1加油成功出票模版  2提货券推送模版  3加油订单结算模版  4商品消费结算
     * @return 成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    public static String print(String sn, Integer classify, TbOrder tbOrder, Integer isAppend) {
        try {
            //标签说明：
            //单标签:
            //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
            //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
            //成对标签：
            //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
            //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,""为右对齐
            //拼凑订单内容时可参考如下格式
            //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

            //region 以前的代码
            /*content = "<CB>测试打印</CB><BR>";
            content += "名称　　　　　 单价  数量 金额<BR>";
            content += "--------------------------------<BR>";
            content += "饭　　　　　　 1.0    1   1.0<BR>";
            content += "炒饭　　　　　 10.0   10  10.0<BR>";
            content += "蛋炒饭　　　　 10.0   10  100.0<BR>";
            content += "鸡蛋炒饭　　　 100.0  1   100.0<BR>";
            content += "番茄蛋炒饭　　 1000.0 1   100.0<BR>";
            content += "西红柿蛋炒饭　 1000.0 1   100.0<BR>";
            content += "西红柿鸡蛋炒饭 100.0  10  100.0<BR>";
            content += "备注：加辣<BR>";
            content += "--------------------------------<BR>";
            content += "合计：xx.0元<BR>";
            content += "送货地点：广州市南沙区xx路xx号<BR>";
            content += "联系电话：13888888888888<BR>";
            content += "订餐时间：2016-08-08 08:08:08<BR>";
            content += "<QR>http://www.dzist.com</QR>";*/
            //endregion

            //region 获取配置的打印模板信息  没设置的就正常不加粗
            GoodsShop shopData = goodsShopService.selectGoodDatas(tbOrder.getShopId());
            UserEntity parentUser = userService.selectUserById(tbOrder.getParentUserId());
            TbCoupon tbCoupon = tbCouponService.selectCoupon(tbOrder.getCouponId());
            ActivityOrderVO activity = tbOrder.getOrderId() == null ? null : activityService.selectByOrder(tbOrder.getOrderId());
            UserEntity user = userService.selectUserById(tbOrder.getUserId());//用户

            List<PrintModelResult> resultData = new ArrayList<>();
            List<PrintInfo> infos = printInfoService.printInfos();
            List<Integer> typeIds = infos.stream().map(PrintInfo::getTypeId).distinct().collect(Collectors.toList());
            PrintInfoShop pis = printInfoShopService.selectPrintInfoShopById(tbOrder.getShopId().intValue());
            if (pis == null) {
                for (Integer typeId : typeIds) {
                    List<PrintInfo> nowInfos = infos.stream().filter(e -> e.getTypeId().intValue() == typeId.intValue()).collect(Collectors.toList());
                    PrintModelResult data = new PrintModelResult();
                    List<PrintModelDetailResult> details = new ArrayList<>();
                    List<PrintModelTypeResult> types = new ArrayList<>();
                    for (PrintInfo nowInfo : nowInfos) {
                        PrintModelDetailResult detailData = new PrintModelDetailResult();
                        detailData.setId(nowInfo.getId());
                        detailData.setPrintField(nowInfo.getPrintField());
                        detailData.setPrintName(nowInfo.getPrintName());
                        detailData.setIsCheck(0);
                        details.add(detailData);

                        PrintModelTypeResult typeData = new PrintModelTypeResult();
                        typeData.setId(nowInfo.getId());
                        typeData.setIsBlod(0);
                        typeData.setWordSize(0);
                        typeData.setPrintField(nowInfo.getPrintField());
                        typeData.setPrintName(nowInfo.getPrintName());
                        types.add(typeData);

                    }
                    if (nowInfos != null && nowInfos.size() > 0) {
                        data.setId(typeId);
                        data.setName(nowInfos.get(0).getTypeName());
                    }
                    data.setDetails(details);
                    data.setTypes(types);
                    resultData.add(data);
                }
            } else {
                //要修改获取逻辑
                if (pis.getBaseInfo().isEmpty()) {
                    PrintModelResult data = new PrintModelResult();
                    List<PrintInfo> nowInfos = infos.stream().filter(e -> e.getTypeId().intValue() == ePrintStatu.Base.getValue()).collect(Collectors.toList());
                    List<PrintModelDetailResult> details = new ArrayList<>();
                    List<PrintModelTypeResult> types = new ArrayList<>();
                    for (PrintInfo nowInfo : nowInfos) {
                        PrintModelDetailResult detailData = new PrintModelDetailResult();
                        detailData.setId(nowInfo.getId());
                        detailData.setPrintField(nowInfo.getPrintField());
                        detailData.setPrintName(nowInfo.getPrintName());
                        detailData.setIsCheck(0);
                        details.add(detailData);

                        PrintModelTypeResult typeData = new PrintModelTypeResult();
                        typeData.setId(nowInfo.getId());
                        typeData.setIsBlod(0);
                        typeData.setWordSize(0);
                        typeData.setPrintField(nowInfo.getPrintField());
                        typeData.setPrintName(nowInfo.getPrintName());
                        types.add(typeData);
                    }
                    data.setId(ePrintStatu.Base.getValue());
                    data.setName(nowInfos.get(0).getTypeName());
                    data.setDetails(details);
                    data.setTypes(types);
                    resultData.add(data);
                } else {
                    ObjectMapper objectMapper = new ObjectMapper();
                    PrintModelResult data = objectMapper.readValue(pis.getBaseInfo(), PrintModelResult.class);
                    resultData.add(data);
                }

                if (pis.getGoodInfo().isEmpty()) {
                    PrintModelResult data = new PrintModelResult();
                    List<PrintInfo> nowInfos = infos.stream().filter(e -> e.getTypeId().intValue() == ePrintStatu.Good.getValue()).collect(Collectors.toList());
                    List<PrintModelDetailResult> details = new ArrayList<>();
                    List<PrintModelTypeResult> types = new ArrayList<>();
                    for (PrintInfo nowInfo : nowInfos) {
                        PrintModelDetailResult detailData = new PrintModelDetailResult();
                        detailData.setId(nowInfo.getId());
                        detailData.setPrintField(nowInfo.getPrintField());
                        detailData.setPrintName(nowInfo.getPrintName());
                        detailData.setIsCheck(0);
                        details.add(detailData);

                        PrintModelTypeResult typeData = new PrintModelTypeResult();
                        typeData.setId(nowInfo.getId());
                        typeData.setIsBlod(0);
                        typeData.setWordSize(0);
                        typeData.setPrintField(nowInfo.getPrintField());
                        typeData.setPrintName(nowInfo.getPrintName());
                        types.add(typeData);
                    }
                    data.setId(ePrintStatu.Good.getValue());
                    data.setName(nowInfos.get(0).getTypeName());
                    data.setDetails(details);
                    data.setTypes(types);
                    resultData.add(data);
                } else {
                    ObjectMapper objectMapper = new ObjectMapper();
                    PrintModelResult data = objectMapper.readValue(pis.getGoodInfo(), PrintModelResult.class);
                    resultData.add(data);
                }

                if (pis.getPayInfo().isEmpty()) {
                    PrintModelResult data = new PrintModelResult();
                    List<PrintInfo> nowInfos = infos.stream().filter(e -> e.getTypeId().intValue() == ePrintStatu.Pay.getValue()).collect(Collectors.toList());
                    List<PrintModelDetailResult> details = new ArrayList<>();
                    List<PrintModelTypeResult> types = new ArrayList<>();
                    for (PrintInfo nowInfo : nowInfos) {
                        PrintModelDetailResult detailData = new PrintModelDetailResult();
                        detailData.setId(nowInfo.getId());
                        detailData.setPrintField(nowInfo.getPrintField());
                        detailData.setPrintName(nowInfo.getPrintName());
                        detailData.setIsCheck(0);
                        details.add(detailData);

                        PrintModelTypeResult typeData = new PrintModelTypeResult();
                        typeData.setId(nowInfo.getId());
                        typeData.setIsBlod(0);
                        typeData.setWordSize(0);
                        typeData.setPrintField(nowInfo.getPrintField());
                        typeData.setPrintName(nowInfo.getPrintName());
                        types.add(typeData);
                    }
                    data.setId(ePrintStatu.Pay.getValue());
                    data.setName(nowInfos.get(0).getTypeName());
                    data.setDetails(details);
                    data.setTypes(types);
                    resultData.add(data);
                } else {
                    ObjectMapper objectMapper = new ObjectMapper();
                    PrintModelResult data = objectMapper.readValue(pis.getPayInfo(), PrintModelResult.class);
                    resultData.add(data);
                }

                if (pis.getUserInfo().isEmpty()) {
                    PrintModelResult data = new PrintModelResult();
                    List<PrintInfo> nowInfos = infos.stream().filter(e -> e.getTypeId().intValue() == ePrintStatu.User.getValue()).collect(Collectors.toList());
                    List<PrintModelDetailResult> details = new ArrayList<>();
                    List<PrintModelTypeResult> types = new ArrayList<>();
                    for (PrintInfo nowInfo : nowInfos) {
                        PrintModelDetailResult detailData = new PrintModelDetailResult();
                        detailData.setId(nowInfo.getId());
                        detailData.setPrintField(nowInfo.getPrintField());
                        detailData.setPrintName(nowInfo.getPrintName());
                        detailData.setIsCheck(0);
                        details.add(detailData);

                        PrintModelTypeResult typeData = new PrintModelTypeResult();
                        typeData.setId(nowInfo.getId());
                        typeData.setIsBlod(0);
                        typeData.setWordSize(0);
                        typeData.setPrintField(nowInfo.getPrintField());
                        typeData.setPrintName(nowInfo.getPrintName());
                        types.add(typeData);
                    }
                    data.setId(ePrintStatu.User.getValue());
                    data.setName(nowInfos.get(0).getTypeName());
                    data.setDetails(details);
                    data.setTypes(types);
                    resultData.add(data);
                } else {
                    ObjectMapper objectMapper = new ObjectMapper();
                    PrintModelResult data = objectMapper.readValue(pis.getUserInfo(), PrintModelResult.class);
                    resultData.add(data);
                }

            }

            List<OrderGoods> orderGoodsList = tbOrder.getOrderGoodsList();
            StringBuilder stringBuilder = new StringBuilder();
            int max = Integer.parseInt(commonInfoService.findOne(420).getValue());
            for (int i = 0; i < max; i++) {
                //region 基本信息：平台名称 店铺名 订单号 送达时间 订单类型
                Optional<PrintModelResult> oBaseInfo = resultData.stream().filter(e -> e.getId().intValue() == ePrintStatu.Base.getValue()).findFirst();
                List<PrintModelTypeResult> baseTypes = oBaseInfo.get().getTypes();

                //region 平台名称
                String bplatformNameType_start = null;
                String bplatformNameType_end = null;
                //endregion
                //region 商铺名
                String bshopName_start = null;
                String bshopName_end = null;
                //endregion
                //region 订单类型
                String borderTypeExtra_start = null;
                String borderTypeExtra_end = null;
                //endregion
                //region 订单号
                String borderNumber_start = null;
                String borderNumber_end = null;
                //endregion

                StringBuilder baseStringBuilder = new StringBuilder();
                for (PrintModelTypeResult baseType : baseTypes) {

                    StringBuilder start = new StringBuilder();
                    StringBuilder end = new StringBuilder();
                    if (baseType.getWordSize().intValue() == eWordSize.Amplify.getValue()) {
                        start.append("<B>");
                        end.append("</B>");
                    }
                    if (baseType.getIsBlod().intValue() == eWordSize.Normal.getValue()) {//这里normal表示加粗
                        start.append("<BOLD>");
                        end.append("</BOLD>");
                    }
                    int isCheck = 0;
                    Optional<PrintModelDetailResult> oCheck = oBaseInfo.get().getDetails().stream().filter(e -> e.getPrintField().equals(baseType.getPrintField())).findFirst();
                    if (oCheck != null && oCheck.isPresent()) {
                        isCheck = oCheck.get().getIsCheck().intValue();
                    }
                    switch (baseType.getPrintField()) {
                        case "platform_name":
                            bplatformNameType_start = "<C>" + start.toString();
                            bplatformNameType_end = end.toString() + "</C>";
                            break;
                        case "shop_name":
                            bshopName_start = "<C>" + start.toString();
                            bshopName_end = end.toString() + "</C>";
                            break;
                        case "order_type_extra":
                            borderTypeExtra_start = start.toString();
                            borderTypeExtra_end = end.toString();
                            break;
                        case "order_number":
                            borderNumber_start = start.toString();
                            borderNumber_end = end.toString();
                            break;
                        case "expect_delivery_time":
                            baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getExpectDeliveryTime() == null ? "即时送达" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tbOrder.getExpectDeliveryTime())).append(end.toString()).append("<BR>");
                            break;
                        case "user_nick_name":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getUserNickName() == null ? (user == null ? "" : user.getNickName()) : tbOrder.getUserNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_phone":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getShopPhone() == null ? (shopData == null ? "" : shopData.getPhone()) : tbOrder.getShopPhone()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "distribution_distance_start":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getDistributionDistance() == null ? (shopData == null ? "" : String.valueOf(shopData.getDistributionDistance())) : tbOrder.getDistributionDistance()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "detailed_address":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getDetailedAddress() == null ? (tbOrder == null ? "" : shopData.getDetailedAddress()) : tbOrder.getDetailedAddress()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "remark":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getRemark()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_receiving_time":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getShopReceivingTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_id":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(shopData != null ? shopData.getBusinessHours() + "-" + shopData.getLockHours() : "").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "parent_user_id":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(parentUser == null ? "" : parentUser.getNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_money":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getPayMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "auto_send_order":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getAutoSendOrder().intValue() == 0 ? "开启" : "关闭").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "errand_money":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getErrandMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pack_money":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getPackMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_code":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getOrderCode()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_type":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getPayType().intValue() == 1 ? "微信支付" : (tbOrder.getPayType().intValue() == 2 ? "余额支付" : "支付宝支付")).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_time":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getPayTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "create_time":
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbOrder.getCreateTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "address":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String addressDetail = jsonObject.getString("addressDetail");
                                    String city = jsonObject.getString("city");
                                    String district = jsonObject.getString("district");
                                    String province = jsonObject.getString("province");
                                    baseStringBuilder.append(start.toString()).append(province).append(city).append(district).append(addressDetail).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "phone":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String phone = jsonObject.getString("userPhone");
                                    baseStringBuilder.append(start.toString()).append(phone).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_name":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String userName = jsonObject.getString("userName");
                                    baseStringBuilder.append(start.toString()).append(userName).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_id"://显示isVip和vipExpirationTime
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append("是否会员：").append(user == null ? "" : (user.getIsVip().intValue() == 1 ? "是" : "否")).append(end.toString()).append("<BR>");
                                baseStringBuilder.append(start.toString()).append("会员有效期：").append(user == null ? "" : user.getVipExpirationTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "coupon_id"://拿优惠券表中的优惠券名称
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(tbCoupon == null ? "" : tbCoupon.getCouponName()).append(end.toString()).append("<BR>");
                            }
                            break;

                        case "activity_title"://通过订单ID去activity_part_record表中查到activity_id后再去activity表中获取活动标题
                            if (isCheck == 1) {
                                baseStringBuilder.append(start.toString()).append(baseType.getPrintName() + "：").append(activity == null ? "" : activity.getTitle()).append(end.toString()).append("<BR>");
                            }
                            break;
                        default:
                            break;
                    }
                }

                if (bplatformNameType_start != null) {
                    stringBuilder.append(bplatformNameType_start).append("#").append(tbOrder.getOrderSequence()).append("-").append("墨轩云商").append(bplatformNameType_end);
                }
                if (bshopName_start != null) {
                    stringBuilder.append(bshopName_start).append(tbOrder.getShopName()).append(bshopName_end);
                }
                if (borderTypeExtra_start != null) {
                    stringBuilder.append(borderTypeExtra_start).append("类型：").append(eOrderTypeExtra.stringOf(tbOrder.getOrderTypeExtra())).append(borderTypeExtra_end).append("<BR>");
                }
                if (borderNumber_start != null) {
                    stringBuilder.append(borderNumber_start).append("订单号：").append(tbOrder.getOrderNumber()).append(borderNumber_end).append("<BR>");
                }

                stringBuilder.append(baseStringBuilder.toString());

                //endregion
                stringBuilder.append("--------------------------------<BR>");

                //region 商品信息：商品名称 单价 数量 备注 金额

                //region 字号样式
                Optional<PrintModelResult> oGoodInfo = resultData.stream().filter(e -> e.getId().intValue() == ePrintStatu.Good.getValue()).findFirst();
                List<PrintModelTypeResult> goodTypes = oGoodInfo.get().getTypes();
                //region 商品名称
                String goods_name_start = null;
                String goods_name_end = null;
                //endregion
                //region 单价
                String goods_price_start = null;
                String goods_price_end = null;
                //endregion
                //region 数量
                String goods_num_start = null;
                String goods_num_end = null;
                //endregion
                //region 备注
                String remark_start = null;
                String remark_end = null;
                //endregion
                //region 金额
                String sum_money_start = null;
                String sum_money_end = null;
                //endregion

                StringBuilder goodStringBuilder = new StringBuilder();
                for (PrintModelTypeResult type : goodTypes) {

                    StringBuilder start = new StringBuilder();
                    StringBuilder end = new StringBuilder();
                    if (type.getWordSize().intValue() == eWordSize.Amplify.getValue()) {
                        start.append("<B>");
                        end.append("</B>");
                    }
                    if (type.getIsBlod().intValue() == eWordSize.Normal.getValue()) {//这里normal表示加粗
                        start.append("<BOLD>");
                        end.append("</BOLD>");
                    }
                    int isCheck = 0;
                    Optional<PrintModelDetailResult> oCheck = oGoodInfo.get().getDetails().stream().filter(e -> e.getPrintField().equals(type.getPrintField())).findFirst();
                    if (oCheck != null && oCheck.isPresent()) {
                        isCheck = oCheck.get().getIsCheck().intValue();
                    }
                    switch (type.getPrintField()) {
                        case "goods_name":
                            goods_name_start = start.toString();
                            goods_name_end = end.toString();
                            break;
                        case "goods_price":
                            goods_price_start = start.toString();
                            goods_price_end = end.toString();
                            break;
                        case "goods_num":
                            goods_num_start = start.toString();
                            goods_num_end = end.toString();
                            break;
                        case "remark":
                            remark_start = start.toString();
                            remark_end = end.toString();
                            break;
                        case "sum_money":
                            if (isCheck == 1) {
                                sum_money_start = start.toString();
                                sum_money_end = end.toString();
                            }
                            break;

                        case "platform_name":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append("#").append(tbOrder.getOrderSequence()).append("-").append("墨轩云商").append(end.toString());
                            }
                            break;
                        case "shop_name":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(tbOrder.getShopName()).append(end.toString());
                            }
                            break;
                        case "order_type_extra":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(eOrderTypeExtra.stringOf(tbOrder.getOrderTypeExtra())).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_number":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderNumber()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "user_nick_name":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getUserNickName() == null ? (user == null ? "" : user.getNickName()) : tbOrder.getUserNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_phone":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopPhone() == null ? (shopData == null ? "" : shopData.getPhone()) : tbOrder.getShopPhone()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "distribution_distance_start":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDistributionDistance() == null ? (shopData == null ? "" : String.valueOf(shopData.getDistributionDistance())) : tbOrder.getDistributionDistance()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "detailed_address":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDetailedAddress() == null ? (tbOrder == null ? "" : shopData.getDetailedAddress()) : tbOrder.getDetailedAddress()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_receiving_time":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopReceivingTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_id":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(shopData != null ? shopData.getBusinessHours() + "-" + shopData.getLockHours() : "").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "parent_user_id":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(parentUser == null ? "" : parentUser.getNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_money":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "auto_send_order":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getAutoSendOrder().intValue() == 0 ? "开启" : "关闭").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "errand_money":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getErrandMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pack_money":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPackMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_code":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderCode()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_type":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayType().intValue() == 1 ? "微信支付" : (tbOrder.getPayType().intValue() == 2 ? "余额支付" : "支付宝支付")).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_time":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "create_time":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getCreateTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "address":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String addressDetail = jsonObject.getString("addressDetail");
                                    String city = jsonObject.getString("city");
                                    String district = jsonObject.getString("district");
                                    String province = jsonObject.getString("province");
                                    goodStringBuilder.append(start.toString()).append(province).append(city).append(district).append(addressDetail).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "phone":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String phone = jsonObject.getString("userPhone");
                                    goodStringBuilder.append(start.toString()).append(phone).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_name":
                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String userName = jsonObject.getString("userName");
                                    goodStringBuilder.append(start.toString()).append(userName).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_id"://显示isVip和vipExpirationTime
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append("是否会员：").append(user == null ? "" : (user.getIsVip().intValue() == 1 ? "是" : "否")).append(end.toString()).append("<BR>");
                                goodStringBuilder.append(start.toString()).append("会员有效期：").append(user == null ? "" : user.getVipExpirationTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "coupon_id"://拿优惠券表中的优惠券名称
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbCoupon == null ? "" : tbCoupon.getCouponName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "expect_delivery_time":
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getExpectDeliveryTime() == null ? "即时送达" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tbOrder.getExpectDeliveryTime())).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "activity_title"://通过订单ID去activity_part_record表中查到activity_id后再去activity表中获取活动标题
                            if (isCheck == 1) {
                                goodStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(activity == null ? "" : activity.getTitle()).append(end.toString()).append("<BR>");
                            }
                            break;
                        default:
                            break;
                    }
                }
                //endregion
                if (goods_name_start != null) {
                    //长度十个字
                    stringBuilder.append(goods_name_start).append("名称").append(goods_name_end);
                    if (sum_money_start != null) {
                        stringBuilder.append("　　　　　　");
                    } else {
                        stringBuilder.append("　　　　　　　　");
                    }

                }

                if (goods_price_start != null) {
                    stringBuilder.append(goods_price_start).append("单价").append(goods_price_end).append("　 ");
                }

                if (goods_num_start != null) {
                    stringBuilder.append(goods_num_start).append("数量").append(goods_num_end).append("　 ");
                }

                if (sum_money_start != null) {
                    stringBuilder.append(sum_money_start).append("金额").append(sum_money_end);
                }

                stringBuilder.append("<BR>");

                stringBuilder.append("--------------------------------<BR>");
                BigDecimal packMoney = BigDecimal.ZERO;
                BigDecimal goodsMoney = BigDecimal.ZERO;
                for (OrderGoods orderGoods : orderGoodsList) {
                    BigDecimal sumMoney = orderGoods.getGoodsPrice().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
                    BigDecimal sumPack = orderGoods.getGoodsPack().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
                    packMoney = packMoney.add(sumPack);
                    goodsMoney = goodsMoney.add(sumMoney);
                    String name;
                    if (StringUtils.isNotEmpty(orderGoods.getSkuMessage())) {
                        name = orderGoods.getGoodsName() + "（" + orderGoods.getSkuMessage() + "）";
                    } else {
                        name = orderGoods.getGoodsName();
                    }
                    stringBuilder.append(goods_name_start).append(name).append(goods_name_end);

                    StringBuilder space = new StringBuilder();
                    if (sum_money_start != null) {
                        for (int len = name.length(); len < 8; len++) {
                            space.append("　");
                        }
                    }else{
                        for (int len = name.length(); len < 10; len++) {
                            space.append("　");
                        }
                    }

                    stringBuilder.append(space.toString());
                    stringBuilder.append(goods_price_start).append(orderGoods.getGoodsPrice()).append(goods_price_end);
                    if (orderGoods.getGoodsPrice().doubleValue() < 10) {
                        stringBuilder.append("　   ");
                    } else if (orderGoods.getGoodsPrice().doubleValue() < 100) {
                        stringBuilder.append("　  ");
                    } else {
                        stringBuilder.append("　 ");
                    }
                    stringBuilder.append(goods_num_start).append("x" + orderGoods.getGoodsNum()).append(goods_num_end);
                    stringBuilder.append("　  ");
                    if (sum_money_start != null) {
                        stringBuilder.append(sum_money_start).append(sumMoney).append(sum_money_end);
                    }
                    stringBuilder.append("<BR>");
                    //stringBuilder.append("<BR>");
                }
                stringBuilder.append("--------------------------------<BR>");
                String remark = tbOrder.getRemark();
                if (StringUtils.isEmpty(remark)) {
                    remark = "";
                }
                stringBuilder.append(remark_start).append("备注：").append(remark).append(remark_end).append("<BR>");

                stringBuilder.append(goodStringBuilder.toString());
                //endregion

                stringBuilder.append("--------------------------------<BR>");

                //region 支付信息：打包费 商品费 优惠券 跑腿费 优惠活动 合计

                //region 字号样式
                Optional<PrintModelResult> oPayInfo = resultData.stream().filter(e -> e.getId().intValue() == ePrintStatu.Pay.getValue()).findFirst();
                List<PrintModelTypeResult> payTypes = oPayInfo.get().getTypes();
                //region 打包费
                String pack_money_start = null;
                String pack_money_end = null;
                //endregion
                //region 商品费
                String goods_money_start = null;
                String goods_money_end = null;
                //endregion
                //region 优惠券
                String coupon_money_start = null;
                String coupon_money_end = null;
                //endregion
                //region 跑腿费
                String errand_money_start = null;
                String errand_money_end = null;
                //endregion
                //region 优惠活动
                String activity_title_start = null;
                String activity_title_end = null;
                //endregion
                //region 合计
                String pay_money_start = null;
                String pay_money_end = null;
                //endregion

                StringBuilder payStringBuilder = new StringBuilder();
                for (PrintModelTypeResult type : payTypes) {

                    StringBuilder start = new StringBuilder();
                    StringBuilder end = new StringBuilder();
                    if (type.getWordSize().intValue() == eWordSize.Amplify.getValue()) {
                        start.append("<B>");
                        end.append("</B>");
                    }
                    if (type.getIsBlod().intValue() == eWordSize.Normal.getValue()) {//这里normal表示加粗
                        start.append("<BOLD>");
                        end.append("</BOLD>");
                    }
                    int isCheck = 0;
                    Optional<PrintModelDetailResult> oCheck = oPayInfo.get().getDetails().stream().filter(e -> e.getPrintField().equals(type.getPrintField())).findFirst();
                    if (oCheck != null && oCheck.isPresent()) {
                        isCheck = oCheck.get().getIsCheck().intValue();
                    }
                    switch (type.getPrintField()) {
                        case "pack_money":
                            pack_money_start = start.toString();
                            pack_money_end = end.toString();
                            break;
                        case "goods_money":
                            goods_money_start = start.toString();
                            goods_money_end = end.toString();
                            break;
                        case "coupon_money":
                            coupon_money_start = start.toString();
                            coupon_money_end = end.toString();
                            break;
                        case "errand_money":
                            errand_money_start = start.toString();
                            errand_money_end = end.toString();
                            break;
                        case "activity_title":
                            activity_title_start = start.toString();
                            activity_title_end = end.toString();
                            break;
                        case "pay_money":
                            pay_money_start = start.toString();
                            pay_money_end = end.toString();
                            break;
                        case "platform_name":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append("#").append(tbOrder.getOrderSequence()).append("-").append("墨轩云商").append(end.toString());
                            }
                            break;
                        case "shop_name":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(tbOrder.getShopName()).append(end.toString());
                            }
                            break;
                        case "order_type_extra":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(eOrderTypeExtra.stringOf(tbOrder.getOrderTypeExtra())).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_number":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderNumber()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "user_nick_name":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getUserNickName() == null ? (user == null ? "" : user.getNickName()) : tbOrder.getUserNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_phone":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopPhone() == null ? (shopData == null ? "" : shopData.getPhone()) : tbOrder.getShopPhone()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "distribution_distance_start":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDistributionDistance() == null ? (shopData == null ? "" : String.valueOf(shopData.getDistributionDistance())) : tbOrder.getDistributionDistance()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "detailed_address":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDetailedAddress() == null ? (tbOrder == null ? "" : shopData.getDetailedAddress()) : tbOrder.getDetailedAddress()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "remark":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getRemark()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_receiving_time":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopReceivingTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_id":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(shopData != null ? shopData.getBusinessHours() + "-" + shopData.getLockHours() : "").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "parent_user_id":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(parentUser == null ? "" : parentUser.getNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "auto_send_order":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getAutoSendOrder().intValue() == 0 ? "开启" : "关闭").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_code":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderCode()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_type":
                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayType().intValue() == 1 ? "微信支付" : (tbOrder.getPayType().intValue() == 2 ? "余额支付" : "支付宝支付")).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_time":

                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "create_time":

                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getCreateTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "address":

                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String addressDetail = jsonObject.getString("addressDetail");
                                    String city = jsonObject.getString("city");
                                    String district = jsonObject.getString("district");
                                    String province = jsonObject.getString("province");
                                    payStringBuilder.append(start.toString()).append(province).append(city).append(district).append(addressDetail).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "phone":

                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String phone = jsonObject.getString("userPhone");
                                    payStringBuilder.append(start.toString()).append(phone).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_name":

                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String userName = jsonObject.getString("userName");
                                    payStringBuilder.append(start.toString()).append(userName).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_id"://显示isVip和vipExpirationTime

                            if (isCheck == 1) {

                                payStringBuilder.append(start.toString()).append("是否会员：").append(user == null ? "" : (user.getIsVip().intValue() == 1 ? "是" : "否")).append(end.toString()).append("<BR>");
                                payStringBuilder.append(start.toString()).append("会员有效期：").append(user == null ? "" : user.getVipExpirationTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "coupon_id"://拿优惠券表中的优惠券名称

                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbCoupon == null ? "" : tbCoupon.getCouponName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "expect_delivery_time":

                            if (isCheck == 1) {
                                payStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getExpectDeliveryTime() == null ? "即时送达" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tbOrder.getExpectDeliveryTime())).append(end.toString()).append("<BR>");
                            }
                            break;
                        default:
                            break;
                    }
                }
                //endregion

                stringBuilder.append(pack_money_start).append("打包费：").append(packMoney).append("元").append(pack_money_end + "<BR>");
                stringBuilder.append(goods_money_start).append("商品费：").append(goodsMoney).append("元").append(goods_money_end + "<BR>");
                if (tbOrder.getCouponMoney() != null) {
                    stringBuilder.append(coupon_money_start).append("优惠券：").append("-" + tbOrder.getCouponMoney()).append("元").append(coupon_money_end + "<BR>");
                } else {
                    stringBuilder.append(coupon_money_start).append("优惠券：").append("-0").append("元").append(coupon_money_end + "<BR>");
                }
                BigDecimal errandMoney = tbOrder.getErrandMoney();
                if (errandMoney == null) {
                    errandMoney = BigDecimal.ZERO;
                }
                BigDecimal errandMoneyT = errandMoney.setScale(2, BigDecimal.ROUND_HALF_UP);
                stringBuilder.append(errand_money_start).append("跑腿费：").append(errandMoneyT).append("元").append(errand_money_end + "<BR>");
                //从这个表里拿优惠活动 activity_part_record 活动参与记录表
                stringBuilder.append(activity_title_start).append("优惠活动：").append(activity == null ? "" : activity.getTitle()).append(activity_title_end + "<BR>");
                BigDecimal patMoney = tbOrder.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP);
                stringBuilder.append(pay_money_start).append("合计：").append(patMoney).append("元").append(pay_money_end + "<BR>");
                stringBuilder.append(payStringBuilder.toString());
                //endregion
                stringBuilder.append("--------------------------------<BR>");
                //region 用户信息：姓名 电话号 地址 订餐时间 商家联系电话

                //region 字号样式
                Optional<PrintModelResult> oUserInfo = resultData.stream().filter(e -> e.getId().intValue() == ePrintStatu.User.getValue()).findFirst();
                List<PrintModelTypeResult> userTypes = oUserInfo.get().getTypes();
                //region 姓名
                String user_name_start = null;
                String user_name_end = null;
                //endregion
                //region 电话号
                String phone_start = null;
                String phone_end = null;
                //endregion
                //region 地址
                String address_detail_start = null;
                String address_detail_end = null;
                //endregion
                //region 订餐时间
                String pay_time_start = null;
                String pay_time_end = null;
                //endregion

                StringBuilder userStringBuilder = new StringBuilder();
                for (PrintModelTypeResult type : userTypes) {

                    StringBuilder start = new StringBuilder();
                    StringBuilder end = new StringBuilder();
                    if (type.getWordSize().intValue() == eWordSize.Amplify.getValue()) {
                        start.append("<B>");
                        end.append("</B>");
                    }
                    if (type.getIsBlod().intValue() == eWordSize.Normal.getValue()) {//这里normal表示加粗
                        start.append("<BOLD>");
                        end.append("</BOLD>");
                    }
                    int isCheck = 0;
                    Optional<PrintModelDetailResult> oCheck = oUserInfo.get().getDetails().stream().filter(e -> e.getPrintField().equals(type.getPrintField())).findFirst();
                    if (oCheck != null && oCheck.isPresent()) {
                        isCheck = oCheck.get().getIsCheck().intValue();
                    }
                    switch (type.getPrintField()) {
                        case "user_name":
                            user_name_start = start.toString();
                            user_name_end = end.toString();
                            break;
                        case "phone":
                            phone_start = start.toString();
                            phone_end = end.toString();
                            break;
                        case "address_detail":
                            address_detail_start = start.toString();
                            address_detail_end = end.toString();
                            break;
                        case "pay_time":
                            pay_time_start = start.toString();
                            pay_time_end = end.toString();
                            break;
                        case "platform_name":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append("#").append(tbOrder.getOrderSequence()).append("-").append("墨轩云商").append(end.toString());
                            }
                            break;
                        case "shop_name":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(tbOrder.getShopName()).append(end.toString());
                            }
                            break;
                        case "order_type_extra":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(eOrderTypeExtra.stringOf(tbOrder.getOrderTypeExtra())).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_number":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderNumber()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "user_nick_name":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getUserNickName() == null ? (user == null ? "" : user.getNickName()) : tbOrder.getUserNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_phone":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopPhone() == null ? (shopData == null ? "" : shopData.getPhone()) : tbOrder.getShopPhone()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "distribution_distance_start":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDistributionDistance() == null ? (shopData == null ? "" : String.valueOf(shopData.getDistributionDistance())) : tbOrder.getDistributionDistance()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "detailed_address":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getDetailedAddress() == null ? (tbOrder == null ? "" : shopData.getDetailedAddress()) : tbOrder.getDetailedAddress()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "remark":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getRemark()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_receiving_time":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getShopReceivingTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "shop_id":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(shopData != null ? shopData.getBusinessHours() + "-" + shopData.getLockHours() : "").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "parent_user_id":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(parentUser == null ? "" : parentUser.getNickName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_money":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "auto_send_order":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getAutoSendOrder().intValue() == 0 ? "开启" : "关闭").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "errand_money":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getErrandMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pack_money":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPackMoney()).append("元").append(end.toString()).append("<BR>");
                            }
                            break;
                        case "order_code":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getOrderCode()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "pay_type":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getPayType().intValue() == 1 ? "微信支付" : (tbOrder.getPayType().intValue() == 2 ? "余额支付" : "支付宝支付")).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "create_time":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getCreateTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "address":

                            if (isCheck == 1) {
                                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                                    String addressDetail = jsonObject.getString("addressDetail");
                                    String city = jsonObject.getString("city");
                                    String district = jsonObject.getString("district");
                                    String province = jsonObject.getString("province");
                                    userStringBuilder.append(start.toString()).append(province).append(city).append(district).append(addressDetail).append(end.toString()).append("<BR>");
                                }
                            }
                            break;
                        case "user_id"://显示isVip和vipExpirationTime

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append("是否会员：").append(user == null ? "" : (user.getIsVip().intValue() == 1 ? "是" : "否")).append(end.toString()).append("<BR>");
                                userStringBuilder.append(start.toString()).append("会员有效期：").append(user == null ? "" : user.getVipExpirationTime()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "coupon_id"://拿优惠券表中的优惠券名称

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbCoupon == null ? "" : tbCoupon.getCouponName()).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "expect_delivery_time":

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(tbOrder.getExpectDeliveryTime() == null ? "即时送达" : new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(tbOrder.getExpectDeliveryTime())).append(end.toString()).append("<BR>");
                            }
                            break;
                        case "activity_title"://通过订单ID去activity_part_record表中查到activity_id后再去activity表中获取活动标题

                            if (isCheck == 1) {
                                userStringBuilder.append(start.toString()).append(type.getPrintName() + "：").append(activity == null ? "" : activity.getTitle()).append(end.toString()).append("<BR>");
                            }
                            break;
                        default:
                            break;
                    }
                }
                //endregion

                if (StringUtils.isNotEmpty(tbOrder.getAddress())) {
                    JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                    String addressDetail = jsonObject.getString("addressDetail");
                    String city = jsonObject.getString("city");
                    String district = jsonObject.getString("district");
                    String province = jsonObject.getString("province");
                    String userName = jsonObject.getString("userName");
                    String phone = jsonObject.getString("userPhone");
                    stringBuilder.append(user_name_start).append(userName).append(user_name_end).append("<BR>");
                    stringBuilder.append(phone_start).append(phone).append(phone_end).append("<BR>");
                    stringBuilder.append(address_detail_start).append(province).append(city).append(district).append(addressDetail).append(address_detail_end).append("<BR>");
                } else {
                    stringBuilder.append(phone_start).append(tbOrder.getPhone()).append(phone_end).append("<BR>");
                }

                stringBuilder.append(pay_time_start).append("订餐时间：").append(tbOrder.getPayTime()).append(pay_time_end).append("<BR>");

                stringBuilder.append(userStringBuilder);
                stringBuilder.append("<BR>");
                //String returnNo = getDigitBarCode();
                //sb.append("<BC128_C>"+returnNo+"</BC128_C>");
                stringBuilder.append("<CB><QR>").append(tbOrder.getOrderNumber()).append("</QR></CB>");
                stringBuilder.append("<CB>收单码：").append(tbOrder.getOrderId()).append("</CB>");
                stringBuilder.append("<BR>").append("<BR>").append("<BR>");
                stringBuilder.append("<CUT>");
                //endregion
            }

            String content = stringBuilder.toString();

            doRequest(sn, content, tbOrder.getStatus(), isAppend, tbOrder.getOrderId());

        } catch (Exception e) {
            e.printStackTrace();
            log.error("打印异常：" + e.getMessage(), e);
        }
        return null;
    }


    /**
     * 小票机打印订单接口
     *
     * @param sn 打印机编号
     * @return 成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    public static String returnPrint(String sn, TbOrder tbOrder) {
        try {
            StringBuilder sb = new StringBuilder();

            sb.append("<AUDIO-REFUND>");
            sb.append("<C>墨轩云商</C>");
            sb.append("<CB>");
            sb.append("#").append(tbOrder.getOrderSequence()).append("<BR>");
            sb.append("用户已取消，请勿继续配送<BR>");
            sb.append("<BR>");
            sb.append("<CUT>");

            doRequest(sn, sb.toString(), 5, null, tbOrder.getOrderId());

        } catch (Exception e) {
            e.printStackTrace();
            log.error("退款小票打印失败:{},{}" + e.getMessage(), e);
        }
        return null;
    }

    private static void doRequest(String sn, String content, Integer status, Integer isAppend, Long orderId) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build()) {
            String url = commonInfoService.findOne(325).getValue();
            String user = commonInfoService.findOne(326).getValue();
            String uKey = commonInfoService.findOne(327).getValue();
            HttpPost post = new HttpPost(url);
            List<NameValuePair> nameValuePairs = new ArrayList<>();

            String sTime = String.valueOf(System.currentTimeMillis() / 1000);

            nameValuePairs.add(new BasicNameValuePair("user", user));
            nameValuePairs.add(new BasicNameValuePair("stime", sTime));
            nameValuePairs.add(new BasicNameValuePair("sig", signature(user, uKey, sTime)));
            nameValuePairs.add(new BasicNameValuePair("apiname", "Open_printMsg"));
            nameValuePairs.add(new BasicNameValuePair("sn", sn));
            nameValuePairs.add(new BasicNameValuePair("content", content));
            nameValuePairs.add(new BasicNameValuePair("times", "1"));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
            CloseableHttpResponse response = httpClient.execute(post);
            int stateCode = response.getStatusLine().getStatusCode();

            if (stateCode == 200) {
                HttpEntity httpentity = response.getEntity();
                String result = "";
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }

                //region 添加订单打印状态
                int updateData = appOrderService.updateOrderPrint(orderId);
                if (updateData <= 0) {
                    log.error("更新订单打印状态失败，订单ID为：{}", orderId);
                }

                PrintInfoDetail pid = new PrintInfoDetail();
                pid.setOrderStatus(eOrderStatus.stringOf(status));
                pid.setOrderId(orderId);
                pid.setIsAppend(isAppend == null ? "否" : (isAppend.intValue() == 1 ? "是" : "否"));
                Result detailResult = printInfoDetailService.insertPrintInfoDetail(pid);
                if ((int) detailResult.get("code") != 0) {
                    log.error("记录打印数据失败，订单ID为：" + orderId + "；是否补打：" + isAppend);
                }
                //endregion

                log.info("打印请求成功，打印机sn:{},打印内容:{},响应结果:{}", sn, content, result);
            } else {
                log.error("打印请求失败，响应码为：{}", stateCode);
            }
        } catch (Exception e) {
            log.error("打印请求失败，失败原因：{}", e.getMessage());
        }
    }

    /**
     * 小票机打印订单接口
     *
     * @param sn 打印机编号
     * @return 成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    public static String testPrint(String sn) {
        try {
            //标签说明：
            //单标签:
            //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
            //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
            //成对标签：
            //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
            //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,""为右对齐
            //拼凑订单内容时可参考如下格式
            //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

            log.info("utils方法打印开始");

            //region 以前的代码
            String content = "<AUDIO-REFUND>";
            content += "<CB>测试打印</CB><BR>";
            content += "名称　　　　　 单价  数量 金额<BR>";
            content += "--------------------------------<BR>";
            content += "<B>饭　　　　　　 1.0    1   1.0</B><BR>";
            content += "<BOLD>炒饭　　　　　 10.0   10  10.0</BOLD><BR>";
            content += "<B><BOLD>蛋炒饭　　　　 10.0   10  100.0</B></BOLD><BR>";
            content += "<B><BOLD>蛋炒饭　　　　 10.0   10  100.0</BOLD></B><BR>";
            content += "鸡蛋炒饭　　　 100.0  1   100.0<BR>";
            content += "番茄蛋炒饭　　 1000.0 1   100.0<BR>";
            content += "西红柿蛋炒饭　 1000.0 1   100.0<BR>";
            content += "西红柿鸡蛋炒饭 100.0  10  100.0<BR>";
            content += "备注：加辣<BR>";
            content += "--------------------------------<BR>";
            content += "合计：xx.0元<BR>";
            content += "送货地点：广州市南沙区xx路xx号<BR>";
            content += "联系电话：13888888888888<BR>";
            content += "订餐时间：2016-08-08 08:08:08<BR>";
            content += "<QR>http://www.dzist.com</QR>";
            //endregion
            log.info("utils方法打印开始1");
            StringBuilder stringBuilder = new StringBuilder();
            log.info("utils方法打印开始2");
            //region 以前的代码
            /*stringBuilder.append("<BR>").append("<BR>").append("<BR>");
            stringBuilder.append("<CB>").append(tbOrder.getShopName()).append("</CB><BR>");
            if(tbOrder.getOrderType()==1){
                stringBuilder.append("<BOLD>类型：").append("到店取餐</BOLD><BR>");
                stringBuilder.append("<BOLD>取餐号：").append(tbOrder.getOrderCode()).append("</BOLD><BR>");
            }else{
                stringBuilder.append("<BOLD>类型：").append("外卖配送</BOLD><BR>");
            }
            stringBuilder.append("<BOLD>订单号：").append(tbOrder.getOrderNumber()).append("</BOLD><BR>");
            stringBuilder.append("--------------------------------<BR>");
            stringBuilder.append("名称　　　  单价　 数量　 金额　<BR>");
            stringBuilder.append("--------------------------------<BR>");
            stringBuilder.append("<BR>");
            for(OrderGoods orderGoods:orderGoodsList){
                BigDecimal sumMoney = orderGoods.getGoodsPrice().multiply(BigDecimal.valueOf(orderGoods.getGoodsNum()));
                String name;
                if(StringUtils.isNotEmpty(orderGoods.getSkuMessage())){
                    name=orderGoods.getGoodsName()+"("+orderGoods.getSkuMessage()+")";
                }else{
                    name=orderGoods.getGoodsName();
                }
                stringBuilder.append(name).append("<BR>");
                stringBuilder.append("　　　　　  ");
                stringBuilder.append(orderGoods.getGoodsPrice());
                if(orderGoods.getGoodsPrice().doubleValue()<10){
                    stringBuilder.append("　   ");
                }else if(orderGoods.getGoodsPrice().doubleValue()<100){
                    stringBuilder.append("　  ");
                }else{
                    stringBuilder.append("　 ");
                }
                stringBuilder.append(orderGoods.getGoodsNum());
                stringBuilder.append("　  ");
                stringBuilder.append(sumMoney).append("<BR>");
                stringBuilder.append("<BR>");
            }
            stringBuilder.append("--------------------------------<BR>");
            stringBuilder.append("<BOLD>备注：").append(remark).append("</BOLD><BR>");
            stringBuilder.append("--------------------------------<BR>");
            stringBuilder.append("打包费：").append(packMoney).append("元<BR>");
            stringBuilder.append("商品费：").append(goodsMoney).append("元<BR>");
            if(tbOrder.getCouponMoney()!=null){
                stringBuilder.append("优惠券：-").append(tbOrder.getCouponMoney()).append("元<BR>");
            }
            stringBuilder.append("跑腿费：").append(errandMoney).append("元<BR>");
            stringBuilder.append("合计：").append(tbOrder.getPayMoney()).append("元<BR>");
            stringBuilder.append("--------------------------------<BR>");
            if(StringUtils.isNotEmpty(tbOrder.getAddress())){
                JSONObject jsonObject = JSONObject.parseObject(tbOrder.getAddress());
                String addressDetail = jsonObject.getString("addressDetail");
                String city = jsonObject.getString("city");
                String district = jsonObject.getString("district");
                String province = jsonObject.getString("province");
                String userName = jsonObject.getString("userName");
                String phone = jsonObject.getString("userPhone");
                stringBuilder.append("姓名：").append(userName).append("<BR>");
                stringBuilder.append("联系电话：").append(phone).append("<BR>");
                stringBuilder.append("送货地点：").append(province).append(city).append(district).append(addressDetail).append("<BR>");
            }else{
                stringBuilder.append("联系电话：").append(tbOrder.getPhone()).append("<BR>");
            }
            stringBuilder.append("订餐时间：").append(tbOrder.getPayTime()).append("<BR>");*/
            //endregion

            log.info("utils方法打印开始3");
            //通过POST请求，发送打印信息到服务器
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(30000)//读取超时
                    .setConnectTimeout(30000)//连接超时
                    .build();

            log.info("utils方法打印开始4");
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultRequestConfig(requestConfig)
                    .build();
            log.info("utils方法打印开始5");
            String URL = commonInfoService.findOne(325).getValue();
            log.info("utils方法打印开始6");
            String USER = commonInfoService.findOne(326).getValue();
            log.info("utils方法打印开始7");
            String UKEY = commonInfoService.findOne(327).getValue();
            log.info("utils方法打印开始8");
            HttpPost post = new HttpPost(URL);
            log.info("utils方法打印开始9");
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            log.info("utils方法打印开始10");
            nvps.add(new BasicNameValuePair("user", USER));
            log.info("utils方法打印开始11");
            String STIME = String.valueOf(System.currentTimeMillis() / 1000);
            log.info("utils方法打印开始12");
            nvps.add(new BasicNameValuePair("stime", STIME));
            nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
            nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
            nvps.add(new BasicNameValuePair("sn", sn));
            nvps.add(new BasicNameValuePair("content", content));
            nvps.add(new BasicNameValuePair("times", "1"));//打印联数
            log.info("utils方法打印开始13");
            CloseableHttpResponse response = null;
            String result = null;
            log.info("utils方法打印开始14");
            try {
                log.info("utils方法打印开始15");
                post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
                log.info("utils方法打印开始16");
                response = httpClient.execute(post);
                log.info("utils方法打印开始17");
                int statecode = response.getStatusLine().getStatusCode();
                log.info("utils方法打印开始18");
                if (statecode == 200) {
                    log.info("utils方法打印开始19");
                    HttpEntity httpentity = response.getEntity();
                    log.info("utils方法打印开始20");
                    if (httpentity != null) {
                        log.info("utils方法打印开始21");
                        //服务器返回的JSON字符串，建议要当做日志记录起来
                        result = EntityUtils.toString(httpentity);
                        log.info("utils方法打印开始22");
                    }
                    log.info("utils方法打印开始23");
                }
            } catch (Exception e) {
                log.info("utils方法打印开始24" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    log.info("utils方法打印开始25" + e.getMessage());
                    e.printStackTrace();
                }
                try {
                    post.abort();
                } catch (Exception e) {
                    log.info("utils方法打印开始26" + e.getMessage());
                    e.printStackTrace();
                }
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.info("utils方法打印开始27" + e.getMessage());
                    e.printStackTrace();
                }
            }
            log.info("打印返回值：" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("打印异常：" + e.getMessage(), e);
        }
        return null;
    }


    /**
     * 标签机专用打印订单接口
     *
     * @param sn 打印机编号
     * @return 成功：{"msg":"ok","ret":0,"data":"xxxxxxx_xxxxxxxx_xxxxxxxx","serverExecutedTime":5}
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    private static String printLabelMsg(String sn) {

        String content;
        content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，
        content += "<TEXT x='9' y='10' font='12' w='1' h='2' r='0'>#001       五号桌      1/3</TEXT><TEXT x='80' y='80' font='12' w='2' h='2' r='0'>可乐鸡翅</TEXT><TEXT x='9' y='180' font='12' w='1' h='1' r='0'>张三先生       13800138000</TEXT>";//40mm宽度标签纸打印例子，打开注释调用标签打印接口打印

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printLabelMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));
        nvps.add(new BasicNameValuePair("content", content));
        nvps.add(new BasicNameValuePair("times", "1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    /**
     * 查询某订单是否打印成功
     *
     * @param orderid 订单id
     * @return 成功：{"msg":"ok","ret":0,"data":true,"serverExecutedTime":2}//data:true为已打印,false为未打印
     * 失败：{"msg":"错误描述","ret":非0, "data":null,"serverExecutedTime":7}
     */
    private static String queryOrderState(String orderid) {

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_queryOrderState"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("orderid", orderid));

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    /**
     * 查询指定打印机某天的订单详情
     *
     * @param sn      打印机编号
     * @param strdate 时间 "yyyy-MM-dd"
     * @return 成功：{"msg":"ok","ret":0,"data":{"print":6,"waiting":1},"serverExecutedTime":9}//print已打印，waiting为打印
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    private static String queryOrderInfoByDate(String sn, String strdate) {

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_queryOrderInfoByDate"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));
        nvps.add(new BasicNameValuePair("date", strdate));//yyyy-MM-dd格式

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    /**
     * 查询打印机的状态
     *
     * @param sn 打印机编号
     * @return 成功：{"msg":"ok","ret":0,"data":"状态","serverExecutedTime":4}
     * 失败：{"msg":"错误描述","ret":非0,"data":"null","serverExecutedTime":5}
     */
    private static String queryPrinterStatus(String sn) {

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        String URL = commonInfoService.findOne(325).getValue();
        String USER = commonInfoService.findOne(326).getValue();
        String UKEY = commonInfoService.findOne(327).getValue();
        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_queryPrinterStatus"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    //生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }


    /**
     * 飞鹅技术支持-2020-03-25
     * #########################################################################################################
     * 一，纯数字条件下：
     * 58mm打印机最大支持28位纯数字，80mm打印机最大支持46位纯数字，超出无效
     * <p>
     * 26-28位数字条形码，在数字中不可以出现2个及以上连续的0存在
     * 23-25位数字条形码，在数字中不可以出现3个及以上连续的0存在
     * 21-22位数字条形码，在数字中不可以出现4个及以上连续的0存在
     * 19-20位数字条形码，在数字中不可以出现6个及以上连续的0存在
     * 17-18位数字条形码，在数字中不可以出现8个及以上连续的0存在
     * 15-16位数字条形码，在数字中不可以出现10个及以上连续的0存在
     * 少于或等于14位数字的条形码，0的数量没有影响
     * #########################################################################################################
     * 二，非纯数字混合条件下：
     * 58mm打印机最大支持14位字符，80mm打印机最大支持23位字符，超出无效
     * <p>
     * 支持数字，大小写字母，特殊字符例如:  !@#$%^&*()-=+_
     * #########################################################################################################
     * 把条形码函数返回值，调用飞鹅云打印接口发给打印机打印
     */
    private static String getDigitBarCode(String input) {
        String chr = "";
        String laststr = "";
        byte[] codeB = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39}; // 匹配字符集B
        byte[] codeC = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
                0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31,
                0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42,
                0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
                0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63}; // 匹配字符集C
        int length = input.length();
        byte[] b = new byte[100];
        b[0] = 0x1b;
        b[1] = 0x64;
        b[2] = 0x02;
        b[3] = 0x1d;
        b[4] = 0x48;
        b[5] = 0x32; // 0x32打印条形码下的数字， 0x30不打印条形码下的数字
        b[6] = 0x1d;
        b[7] = 0x68;
        b[8] = 0x50; // 7F是最大的高度
        b[9] = 0x1d;
        b[10] = 0x77;
        b[11] = 0x02; // 2-6  条码宽度
        b[12] = 0x1d;
        b[13] = 0x6b;
        b[14] = 0x49; // code128
        b[15] = (byte) (length + 2); // 得出条形码长度
        b[16] = 0x7b;
        b[17] = 0x42;
        boolean result = input.matches("[0-9]+");//判断是否为纯数字
        if (length > 14 && result == true) {
            b[17] = 0x43;
            int j = 0;
            int key = 18;
            int ss = length / 2;// 初始化数组长度
            String temp = "";
            int iindex = 0;
            for (int i = 0; i < ss; i++) {
                temp = input.substring(j, j + 2);
                iindex = Integer.valueOf(temp);
                j = j + 2;
                if (iindex == 0) {
                    chr = "";
                    if (b[key + i - 1] == '0' && b[key + i - 2] == '0') {
                        b[key + i] = codeB[0];
                        b[key + i + 1] = codeB[0];
                        key += 1;
                    } else {
                        if (b[key + i - 1] == 'C' && b[key + i - 2] == '{') {//判断前面的为字符集C时转换字符集B
                            b[key + i - 2] = 0x7b;
                            b[key + i - 1] = 0x42;
                            b[key + i] = codeB[0];
                            b[key + i + 1] = codeB[0];
                            key += 1;
                        } else {
                            b[key + i] = 0x7b;
                            b[key + i + 1] = 0x42;
                            b[key + i + 2] = codeB[0];
                            b[key + i + 3] = codeB[0];
                            key += 3;
                        }
                    }
                } else {
                    // 判断前面的为字符集B,此时要转换字符集C
                    if (b[key + i - 1] == '0' && b[key + i - 2] == '0' && chr != "chr") {
                        b[key + i] = 0x7b;
                        b[key + i + 1] = 0x43;
                        b[key + i + 2] = codeC[iindex];
                        key += 2;
                    } else {
                        chr = "";
                        b[key + i] = codeC[iindex];
                        if (iindex == 48) chr = "chr";//判断chr(48)等于0的情况
                    }
                }
            }
            int lastKey = getLastIndex(b);
            if (length % 2 > 0) {
                int lastnum = Integer.valueOf(input.substring(input.length() - 1)); // 取得字符串的最后一个数字
                if (b[lastKey] == '0' && b[lastKey - 1] == '0') {//判断前面的为字符集B,此时不需要转换字符集
                    b[lastKey + 1] = codeB[lastnum];
                } else {
                    b[lastKey + 1] = 0x7b;
                    b[lastKey + 2] = 0x42;
                    b[lastKey + 3] = codeB[lastnum];
                }
            }
            // 得出条形码长度
            int blength = getLastIndex(b);
            int len = (blength - 15);
            b[15] = (byte) (len);
            String str = "";
            str = new String(b);
            laststr = str;

            String Last_two = input.substring(input.length() - 2, input.length());
            int Last_two_int = 0;
            Last_two_int = Integer.valueOf(Last_two);
            if (Last_two_int > 32) {
                laststr = laststr.trim().substring(1);
            }
        } else { // 1-14位数字的条形码进来这个区间
            b[15] = (byte) (length + 2);
            laststr = new String(b);
            laststr = laststr.substring(0, 18);
            laststr += input;
        }
        return laststr;
    }


    // 获取数组中最后一个不是0x0的元素的下标
    private static int getLastIndex(byte[] b) {
        if (b == null || b.length == 0) {
            return 0;
        }
        int blength = 0;
        for (int i = b.length - 1; i >= 0; i--) {
            if (b[i] != 0x0) {
                blength = i;
                break;
            }
        }
        return blength;
    }


    public static void main(String[] args) {
        String result = getDigitBarCode("!@#$%^&*()-=+_");

    }
}
