发票打印模版调整

This commit is contained in:
Jack 2024-11-01 17:17:54 +08:00
parent 8552dc9722
commit f2615eb96f
6 changed files with 468 additions and 59 deletions

View File

@ -0,0 +1,17 @@
package com.suisung.mall.common.pojo.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProductSimpleInfo implements Serializable {
private String product_sn;
private String title;
private Integer num;
private String amount;
}

View File

@ -0,0 +1,14 @@
package com.suisung.mall.common.utils;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Slf4j
public class DateTimeUtils {
public static String formatDateTime(LocalDateTime localDateTime, String pattern) {
return localDateTime.format(DateTimeFormatter.ofPattern(pattern));
}
}

View File

@ -20,6 +20,12 @@ public class ShopStorePrinterController {
@Autowired @Autowired
private ShopStorePrinterService shopStorePrinterService; private ShopStorePrinterService shopStorePrinterService;
@ApiOperation(value = "测试打印模版消息", notes = "测试打印模版消息")
@RequestMapping(value = "/print/order", method = {RequestMethod.POST})
public CommonResult printOrder() {
return shopStorePrinterService.printOrderInfo();
}
@ApiOperation(value = "门店打票机分页列表查询", notes = "门店打票机分页列表查询") @ApiOperation(value = "门店打票机分页列表查询", notes = "门店打票机分页列表查询")
@RequestMapping(value = "/page", method = {RequestMethod.GET}) @RequestMapping(value = "/page", method = {RequestMethod.GET})
public CommonResult shopStorePrinterPageList(@RequestParam(name = "keyword", defaultValue = "") String keyword, public CommonResult shopStorePrinterPageList(@RequestParam(name = "keyword", defaultValue = "") String keyword,
@ -75,4 +81,10 @@ public class ShopStorePrinterController {
public CommonResult deleteShopStorePrinter(@RequestParam(name = "printer_id" , required = true) Long printer_id) { public CommonResult deleteShopStorePrinter(@RequestParam(name = "printer_id" , required = true) Long printer_id) {
return shopStorePrinterService.deleteShopStorePrinter(printer_id); return shopStorePrinterService.deleteShopStorePrinter(printer_id);
} }
@ApiOperation(value = "清空打票机打印队列", notes = "清空打票机打印队列")
@RequestMapping(value = "/clear/print/queue", method = {RequestMethod.POST})
public CommonResult clearShopPrinterQueue(@RequestParam(name = "printer_sn" , required = true) String printer_sn) {
return shopStorePrinterService.clearPrinterQueue(printer_sn);
}
} }

View File

@ -42,4 +42,17 @@ public interface ShopStorePrinterService extends IBaseService<ShopStorePrinter>
* @return * @return
*/ */
CommonResult deleteShopStorePrinter(Long printer_id); CommonResult deleteShopStorePrinter(Long printer_id);
/**
* 请空打印机打印队列
* @param printer_sn
* @return
*/
CommonResult clearPrinterQueue(String printer_sn);
/**
* 测试打印订单
* @return
*/
CommonResult printOrderInfo();
} }

View File

@ -7,20 +7,27 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suisung.mall.common.api.CommonResult; import com.suisung.mall.common.api.CommonResult;
import com.suisung.mall.common.constant.ConstantError; import com.suisung.mall.common.constant.ConstantError;
import com.suisung.mall.common.domain.UserDto;
import com.suisung.mall.common.modules.store.ShopStorePrinter; import com.suisung.mall.common.modules.store.ShopStorePrinter;
import com.suisung.mall.common.pojo.dto.ProductSimpleInfo;
import com.suisung.mall.common.pojo.vo.ShopStorePrinterVO;
import com.suisung.mall.common.utils.DateTimeUtils;
import com.suisung.mall.common.utils.TimeUtil;
import com.suisung.mall.core.web.service.impl.BaseServiceImpl; import com.suisung.mall.core.web.service.impl.BaseServiceImpl;
import com.suisung.mall.shop.store.mapper.ShopStorePrinterMapper; import com.suisung.mall.shop.store.mapper.ShopStorePrinterMapper;
import com.suisung.mall.shop.store.service.ShopStorePrinterService; import com.suisung.mall.shop.store.service.ShopStorePrinterService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suisung.mall.common.modules.store.ShopStorePrinter;
import com.suisung.mall.common.pojo.vo.ShopStorePrinterVO;
import com.suisung.mall.shop.store.utis.FeieUtil; import com.suisung.mall.shop.store.utis.FeieUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import static com.suisung.mall.common.utils.ContextUtil.getCurrentUser;
@Service @Service
public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinterMapper, ShopStorePrinter> implements ShopStorePrinterService { public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinterMapper, ShopStorePrinter> implements ShopStorePrinterService {
@ -35,33 +42,41 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
Page<ShopStorePrinterVO> page = new Page<ShopStorePrinterVO>(); Page<ShopStorePrinterVO> page = new Page<ShopStorePrinterVO>();
page.setCurrent(pageNum); page.setCurrent(pageNum);
page.setSize(pageSize); page.setSize(pageSize);
return shopStorePrinterMapper.shopStorePrinterPageList(page,keyword); return shopStorePrinterMapper.shopStorePrinterPageList(page, keyword);
} }
@Override @Override
public CommonResult addNewShopStorePrinter(ShopStorePrinter record) { public CommonResult addNewShopStorePrinter(ShopStorePrinter record) {
//TODO 判断有没有权限删除
record.setStore_id(1); //判断有没有权限
record.setCreated_by(1); UserDto user = getCurrentUser();
record.setUpdated_by(1); if (!user.isStore()) {
return CommonResult.failed("没有门店权限!");
}
Integer userId = user.getId() == null ? 0 : user.getId();
record.setStore_id(Integer.parseInt(user.getStore_id()));
record.setCreated_by(userId);
record.setUpdated_by(userId);
// 判断打票机是否已经存在 // 判断打票机是否已经存在
QueryWrapper<ShopStorePrinter> queryWrapper = new QueryWrapper<>(); QueryWrapper<ShopStorePrinter> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("store_id", record.getStore_id()); queryWrapper.eq("store_id", record.getStore_id());
queryWrapper.eq("printer_sn", record.getPrinter_sn()); queryWrapper.eq("printer_sn", record.getPrinter_sn());
ShopStorePrinter existRecord = getOne(queryWrapper); ShopStorePrinter existRecord = getOne(queryWrapper);
if (existRecord!=null && existRecord.getPrinter_id() > 0) { if (existRecord != null && existRecord.getPrinter_id() > 0) {
if (existRecord.getFlag()== ConstantError.Disable2){ if (existRecord.getFlag() == ConstantError.Disable2) {
UpdateWrapper<ShopStorePrinter> updateWrapper = new UpdateWrapper<ShopStorePrinter>(); UpdateWrapper<ShopStorePrinter> updateWrapper = new UpdateWrapper<ShopStorePrinter>();
updateWrapper.eq("printer_id", existRecord.getPrinter_id()); updateWrapper.eq("printer_id", existRecord.getPrinter_id());
updateWrapper.set("updated_by",1); updateWrapper.set("updated_by", userId);
updateWrapper.set("updated_at",new Date()); updateWrapper.set("updated_at", new Date());
// 往厂商添加打印机 // 往厂商添加打印机
// "922441475#r6ZXPvHH#核销柜台"; // "922441475#r6ZXPvHH#核销柜台";
boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", existRecord.getPrinter_sn(), existRecord.getPrinter_key(),existRecord.getPrinter_name())); boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", existRecord.getPrinter_sn(), existRecord.getPrinter_key(), existRecord.getPrinter_name()));
if(success) { if (success) {
updateWrapper.set("flag",ConstantError.Enable); updateWrapper.set("flag", ConstantError.Enable);
} }
update(updateWrapper); update(updateWrapper);
@ -74,12 +89,12 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
// 往厂商添加打印机 // 往厂商添加打印机
// "922441475#r6ZXPvHH#核销柜台"; // "922441475#r6ZXPvHH#核销柜台";
boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(),record.getPrinter_name())); boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(), record.getPrinter_name()));
if(success) { if (success) {
record.setFlag(ConstantError.Enable); record.setFlag(ConstantError.Enable);
} }
if (add(record)){ if (add(record)) {
return CommonResult.success(); return CommonResult.success();
} }
@ -89,19 +104,25 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
@Override @Override
public CommonResult updateShopStorePrinter(ShopStorePrinter record) { public CommonResult updateShopStorePrinter(ShopStorePrinter record) {
//TODO 判断有没有权限删除 // 判断有没有权限
UserDto user = getCurrentUser();
if (!user.isStore()) {
return CommonResult.failed("没有门店权限!");
}
Integer userId = user.getId() == null ? 0 : user.getId();
if (record==null|| record.getPrinter_id()<=0){ if (record == null || record.getPrinter_id() <= 0) {
return CommonResult.failed("记录不存在!"); return CommonResult.failed("记录不存在!");
} }
if(StrUtil.isBlank(record.getPrinter_sn()) || StrUtil.isBlank(record.getPrinter_key()) || StrUtil.isBlank(record.getPrinter_name())){ if (StrUtil.isBlank(record.getPrinter_sn()) || StrUtil.isBlank(record.getPrinter_key()) || StrUtil.isBlank(record.getPrinter_name())) {
return CommonResult.failed("缺少必要参数!"); return CommonResult.failed("缺少必要参数!");
} }
ShopStorePrinter existRecord = getById(record.getPrinter_id()); ShopStorePrinter existRecord = getById(record.getPrinter_id());
if (existRecord==null){ if (existRecord == null) {
return CommonResult.failed("打票机不存在!"); return CommonResult.failed("打票机不存在!");
} }
@ -110,41 +131,41 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
updateWrapper.set("printer_name", record.getPrinter_name()); updateWrapper.set("printer_name", record.getPrinter_name());
updateWrapper.set("model_id", record.getModel_id()); updateWrapper.set("model_id", record.getModel_id());
updateWrapper.set("region", record.getRegion_id()); updateWrapper.set("region", record.getRegion_id());
updateWrapper.set("paper_with",record.getPaper_with()); updateWrapper.set("paper_with", record.getPaper_with());
updateWrapper.set("website_url", record.getWebsite_url()); updateWrapper.set("website_url", record.getWebsite_url());
updateWrapper.set("status", record.getStatus()); updateWrapper.set("status", record.getStatus());
updateWrapper.set("updated_at", new Date()); updateWrapper.set("updated_at", new Date());
updateWrapper.set("updated_by",1); updateWrapper.set("updated_by", userId);
if (existRecord.getPrinter_sn().equals(record.getPrinter_sn())){ if (existRecord.getPrinter_sn().equals(record.getPrinter_sn())) {
// sn 没有变化不更新 sn // sn 没有变化不更新 sn
if (existRecord.getFlag()== ConstantError.Disable2){ if (existRecord.getFlag() == ConstantError.Disable2) {
// 往厂商添加打印机 // 往厂商添加打印机
boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(),record.getPrinter_name())); boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(), record.getPrinter_name()));
if(success) { if (success) {
updateWrapper.set("flag",ConstantError.Enable); updateWrapper.set("flag", ConstantError.Enable);
} }
} }
}else{ } else {
// 更改了 sn并且 sn 从未添加过打票机不在门店内的 // 更改了 sn并且 sn 从未添加过打票机不在门店内的
QueryWrapper<ShopStorePrinter> queryWrapper2 = new QueryWrapper<>(); QueryWrapper<ShopStorePrinter> queryWrapper2 = new QueryWrapper<>();
queryWrapper2.eq("store_id", record.getStore_id()); queryWrapper2.eq("store_id", record.getStore_id());
queryWrapper2.eq("printer_sn", record.getPrinter_sn()); queryWrapper2.eq("printer_sn", record.getPrinter_sn());
ShopStorePrinter existRecord2 = getOne(queryWrapper2); ShopStorePrinter existRecord2 = getOne(queryWrapper2);
if (existRecord2==null || existRecord2.getPrinter_id()<=0){ if (existRecord2 == null || existRecord2.getPrinter_id() <= 0) {
// 打印机从未加入到厂家到情况 // 打印机从未加入到厂家到情况
// 往厂商添加打印机 // 往厂商添加打印机
// "922441475#r6ZXPvHH#核销柜台"; // "922441475#r6ZXPvHH#核销柜台";
boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(),record.getPrinter_name())); boolean success = feieUtil.addPrinter(String.format("%s#%s#%s", record.getPrinter_sn(), record.getPrinter_key(), record.getPrinter_name()));
if(success) { if (success) {
updateWrapper.set("flag",ConstantError.Enable); updateWrapper.set("flag", ConstantError.Enable);
} }
updateWrapper.set("printer_sn", record.getPrinter_sn()); updateWrapper.set("printer_sn", record.getPrinter_sn());
} }
} }
boolean success =update(updateWrapper); boolean success = update(updateWrapper);
if (success){ if (success) {
return CommonResult.success(); return CommonResult.success();
} }
@ -155,10 +176,14 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
@Override @Override
public CommonResult deleteShopStorePrinter(Long printer_id) { public CommonResult deleteShopStorePrinter(Long printer_id) {
//TODO 判断有没有权限删除 // 判断有没有权限
UserDto user = getCurrentUser();
if (!user.isStore()) {
return CommonResult.failed("没有门店权限!");
}
ShopStorePrinter record = getById(printer_id); ShopStorePrinter record = getById(printer_id);
if (record==null || record.getPrinter_id() <= 0) { if (record == null || record.getPrinter_id() <= 0) {
return CommonResult.failed("打票机不存在,无法删除!"); return CommonResult.failed("打票机不存在,无法删除!");
} }
@ -168,12 +193,99 @@ public class ShopStorePrinterServiceImpl extends BaseServiceImpl<ShopStorePrinte
} }
boolean success = remove(printer_id); boolean success = remove(printer_id);
if(success){ if (success) {
return CommonResult.success(); return CommonResult.success();
} }
return CommonResult.failed("删除失败!"); return CommonResult.failed("删除失败!");
} }
@Override
public CommonResult clearPrinterQueue(String printer_sn) {
boolean success = feieUtil.clearPrinterQueue(printer_sn);
if (success) {
return CommonResult.success();
}
return CommonResult.failed("清空失败!");
}
@Override
public CommonResult printOrderInfo() {
String sn="922441475";
// ProductSimpleInfo order1 = new ProductSimpleInfo("6970448170051","aaaaaaaaaaaaaaaaaa",124, "12.45");
// ProductSimpleInfo order2 = new ProductSimpleInfo("6970448170052","哇哈哈纯净水",24, "26.45");
ProductSimpleInfo order1 = new ProductSimpleInfo("6970448170051","可口可乐CocaCola经典美味汽水1.25L/瓶",110, "1000.45");
ProductSimpleInfo order2 = new ProductSimpleInfo("6970448170053","排骨约350g默认砍小块",1, "150.13");
ProductSimpleInfo order3 = new ProductSimpleInfo("6970448170054","新鲜虫草花1包 约200g", 11,"687.25");
ProductSimpleInfo order4 = new ProductSimpleInfo("6970448170055","冰红茶风味饮料",1, "13.24");
List<ProductSimpleInfo> productList = new ArrayList<>();
productList.add(order1);
productList.add(order2);
productList.add(order3);
productList.add(order4);
String productsStr= feieUtil.genProductStr(productList,18,6,8);
LocalDateTime now = LocalDateTime.now();
String currentDateTime = DateTimeUtils.formatDateTime(now,"yyyy-MM-dd HH:mm:ss");
StringBuilder cont= new StringBuilder();
cont.append("<CB>小发同城</CB><BR>");
// cont.append("--------------------------------<BR>");
// cont.append("<CB>#000"+DateTimeUtils.formatDateTime(now,"ddHHmm")+"</CB><BR>");
// cont.append("<B>买家备注:不用敲门,放在门口旁边的外卖箱,打个电话告知送达就行,谢谢</B><BR>");
// cont.append("<BOLD>配送时间2024-10-25 14:00-14:30</BOLD><BR>");
// cont.append("--------------------------------<BR>");
// cont.append("订单编号ES20231026111444527685<BR>");
// cont.append("订单来源:微信小程序<BR>");
// cont.append("支付方式:微信支付<BR>");
// cont.append("配送来源:同城配送<BR>");
// cont.append("付款时间:"+currentDateTime+"<BR>");
// cont.append("--------------------------------<BR>");
// cont.append("<BOLD>商品名称 数量 <RIGHT>金额</RIGHT><BOLD><BR>");
// cont.append("<BOLD>可口可乐Coca_Cola<BR>经典美味汽水1.25L/瓶</BOLD> <RIGHT><BOLD>【x1】</BOLD> <BOLD>5.54</BOLD></RIGHT><BR>");
// cont.append("<BOLD>6970448170051</BOLD><BR>");
// cont.append("<BR>");
// cont.append("<BOLD>排骨 约350g (默认砍小块)</BOLD> <RIGHT><BOLD>【x5】</BOLD> <BOLD>35.51</BOLD></RIGHT><BR>");
// cont.append("<BOLD>69704481700541</BOLD><BR>");
// cont.append("<BR>");
// cont.append("<BOLD>新鲜虫草花 1包 约200g </BOLD> <RIGHT><BOLD>【x11】</BOLD> <BOLD>687.52</BOLD></RIGHT><BR>");
// cont.append("<BOLD>69704481700512</BOLD><BR>");
// cont.append("<BR>");
// cont.append("<BOLD>冰红茶风味饮料x2<BR>五香瓜子x1</BOLD> <RIGHT><BOLD>【x2】</BOLD> <BOLD>13.26</BOLD></RIGHT><BR>");
// cont.append("<BOLD>6970448170051</BOLD><BR>");
// 商品列表
cont.append(productsStr);
// cont.append("--------------------------------<BR>");
// cont.append("商品总件数:<BOLD>3</BOLD><BR>");
// cont.append("商品总额:<BOLD>¥18.7</BOLD><BR>");
// cont.append("押金:<BOLD>¥500</BOLD><BR>");
// cont.append("运费:<BOLD>¥5.54</BOLD><BR>");
// cont.append("会员权益:<BOLD>-¥50</BOLD><BR>");
// cont.append("秒杀:<BOLD>-¥100</BOLD><BR>");
// cont.append("实付金额:<BOLD>¥428.9元</BOLD><BR>");
// cont.append("--------------------------------<BR>");
// cont.append("<BOLD>商家备注:老顾客赠送一箱牛奶;玻璃瓶包装轻拿轻放</BOLD><BR>");
// cont.append("--------------------------------<BR>");
// cont.append("<BOLD>收货人:张三</BOLD><BR>");
// cont.append("<BOLD>收货人手机号13128778765</BOLD><BR>");
// cont.append("<BOLD>收货地址北京市朝阳区朝阳路朝阳人民小区1号楼1栋1101</BOLD><BR>");
// cont.append("--------------------------------<BR>");
// cont.append("门店:岛内价生活超市<BR>");
// cont.append("门店电话:<BOLD>13665822542</BOLD><BR>");
// cont.append("收银员:李小璐<BR>");
feieUtil.printContent(sn,cont.toString());
return CommonResult.success();
}
} }

View File

@ -2,6 +2,7 @@ package com.suisung.mall.shop.store.utis;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.suisung.mall.common.pojo.dto.ProductSimpleInfo;
import com.suisung.mall.common.pojo.res.FeiePrinterApiDataRes; import com.suisung.mall.common.pojo.res.FeiePrinterApiDataRes;
import com.suisung.mall.common.pojo.res.FeiePrinterApiRes; import com.suisung.mall.common.pojo.res.FeiePrinterApiRes;
import com.suisung.mall.common.utils.JsonUtil; import com.suisung.mall.common.utils.JsonUtil;
@ -97,7 +98,7 @@ public class FeieUtil {
public boolean printContent(String sn, String printContent) { public boolean printContent(String sn, String printContent) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>(); List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("sn", sn)); nvps.add(new BasicNameValuePair("sn", sn));
nvps.add(new BasicNameValuePair("printContent", printContent)); nvps.add(new BasicNameValuePair("content", printContent));
FeiePrinterApiRes<String> reps = sendHttpPost("Open_printMsg", nvps); FeiePrinterApiRes<String> reps = sendHttpPost("Open_printMsg", nvps);
if (reps != null && reps.getRet().equals(0)) { if (reps != null && reps.getRet().equals(0)) {
@ -108,6 +109,25 @@ public class FeieUtil {
return false; return false;
} }
/**
* 清空打印机所有的打印队列
*
* @param sn
* @return
*/
public boolean clearPrinterQueue(String sn) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("sn", sn));
FeiePrinterApiRes<String> reps = sendHttpPost("Open_delPrinterSqs", nvps);
if (reps != null && reps.getRet().equals(0)) {
return true;
}
logger.error(reps.getMsg());
return false;
}
/** /**
* 生成签名字符串 * 生成签名字符串
@ -168,27 +188,248 @@ public class FeieUtil {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
try { close(response, post, httpClient);
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 null; return null;
} }
// 以下是 util 方法
//飞鹅技术支持
//#########################################################################################################
//进行订单的多列排版demo实现商品超出字数的自动换下一行对齐处理同时保持各列进行对齐
//排版原理是统计字符串字节数补空格换行处理
//58mm的机器,一行打印16个汉字,32个字母;80mm的机器,一行打印24个汉字,48个字母
//#########################################################################################################
//orderList为数组 title_len =18 代表名称列占用字节 num_len =8 数量列 amount_len=6金额列-->这里的字节数可按自己需求自由改写
/**
* 生成商品的打印字符串
*
* @param productList 订单商品列表
* @param titleLen 产品名称字节数最大18个字节
* @param numLen 数量字节数最大6个字节
* @param amountLen 金额字节数最大8个字节
* @return
*/
public String genProductStr(List<ProductSimpleInfo> productList, int titleLen, int numLen, int amountLen) {
String resultStr = "";
resultStr += "<L>商品名称 数量 金额</L><BR>";
resultStr += "--------------------------------<BR>";
for (int i = 0; i < productList.size(); i++) {
String product_sn = productList.get(i).getProduct_sn();
String title = productList.get(i).getTitle();
String num = productList.get(i).getNum().toString();
if (productList.get(i).getNum() > 1) {
num = "x" + num;
}
String amount = productList.get(i).getAmount();
num = addSpace(num, numLen);
amount = addSpace(amount, amountLen);
String otherStr = "<L><BOLD>" + num + "</BOLD></L>" + "<L>" + amount + "</L>";
int tl = asciiByteLen(title);
int spaceNum = (tl / titleLen + 1) * titleLen - tl;
if (tl < titleLen) {
for (int k = 0; k < spaceNum; k++) {
title += " ";
}
title += otherStr;
} else if (tl == titleLen) {
title += otherStr;
} else {
List<String> list = null;
if (isEn(title)) {
// 英文
list = getStrList(title, titleLen);
} else {
// 中文
list = getStrList(title, titleLen / 2);
}
String s0 = titleAddSpace(list.get(0), titleLen);
title = s0 + otherStr + "<BR>";// 添加 单价 数量 总额
String s = "";
for (int k = 1; k < list.size(); k++) {
s += list.get(k);
}
try {
s = getStringByEnter(titleLen, s);
} catch (Exception e) {
e.printStackTrace();
}
title += "<L>" + s + "</L> ";
}
resultStr += "<L>" + title + "</L> " + "<BR>";
resultStr += "<BOLD>" + product_sn + "</BOLD><BR>";
}
return resultStr;
}
/**
* 中英文混合的标题加空格
*
* @param str
* @param len
* @return
*/
public String titleAddSpace(String str, int len) {
int k = asciiByteLen(str); // 中英文混合的标题
for (int i = 0; i < len - k; i++) {
str += " ";
}
return str;
}
/**
* 递归函数字符串超长自动换行
*
* @param length
* @param string
* @return
* @throws Exception
*/
public String getStringByEnter(int length, String string) throws Exception {
for (int i = 1; i <= string.length(); i++) {
if (asciiByteLen(string.substring(0, i)) > length) {
return string.substring(0, i - 1) + "<BR>" + getStringByEnter(length, string.substring(i - 1));
}
}
return string;
}
/**
* 给字符串前后补充空格足够size长度一般用在 数量和价格
*
* @param str
* @param size 额定字节数
* @return
*/
public String addSpace(String str, int size) {
int len = asciiByteLen(str);
if (len >= size) {
return str;
}
int cz = size - len;
if (cz % 2 == 0) {
// 偶数
for (int i = 1; i <= cz; i++) {
if (i % 2 == 0) {
str = " " + str;
} else {
str = str + " ";
}
}
} else {
// 奇数
for (int i = 1; i <= cz; i++) {
if (i % 2 == 0) {
str = str + " ";
} else {
str = " " + str;
}
}
}
return str;
}
/**
* 判断字符串是否为英文
*
* @param str
* @return
*/
public Boolean isEn(String str) {
return asciiByteLen(str) == str.length();
}
/**
* 获取字符串的字节长度中文 2 个字节英文数字 1 个字节
*
* @param str 字符串
* @return 字符串的字节长度
*/
public int asciiByteLen(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
int byteLength = 0;
for (char c : str.toCharArray()) {
if (c > 255) {
byteLength += 2;
} else {
byteLength += 1;
}
}
return byteLength;
}
public List<String> getStrList(String inputString, int length) {
int size = inputString.length() / length;
if (inputString.length() % length != 0) {
size += 1;
}
return getStrList(inputString, length, size);
}
public List<String> getStrList(String inputString, int length, int size) {
List<String> list = new ArrayList<String>();
for (int index = 0; index < size; index++) {
String childStr = subString(inputString, index * length, (index + 1) * length);
list.add(childStr);
}
return list;
}
/**
* 截取字符串
*
* @param str
* @param f
* @param t
* @return
*/
public String subString(String str, int f, int t) {
if (f > str.length())
return "";
if (t > str.length()) {
return str.substring(f);
} else {
return str.substring(f, t);
}
}
/**
* 关闭流和客户端
*
* @param response
* @param post
* @param httpClient
*/
public void close(CloseableHttpResponse response, HttpPost post, CloseableHttpClient httpClient) {
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();
}
}
} }