package com.bohuikeji.delivery.backstage.controller.api.order;

import cn.hutool.json.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bohuikeji.delivery.backstage.constants.KeyConst;
import com.bohuikeji.delivery.backstage.entity.*;
import com.bohuikeji.delivery.backstage.entity.third.OrderDetailDO;
import com.bohuikeji.delivery.backstage.entity.vo.CourierAddressVo;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.delivery.backstage.service.third.ThirdUtils;
import com.bohuikeji.frame.module.admin.annotation.InitLog;
import com.bohuikeji.frame.module.admin.base.ApiController;
import com.bohuikeji.frame.module.admin.component.RedisUtil;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.easypdf.my.TextUtils;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.entity.back.DataPage;
import com.bohuikeji.frame.module.admin.entity.sys.SysConfig;
import com.bohuikeji.frame.module.admin.entity.vo.AddressVo;
import com.bohuikeji.frame.module.admin.service.ISysConfigService;
import com.bohuikeji.frame.module.admin.utils.FileUtil;
import com.bohuikeji.frame.module.admin.utils.MinioUtil;
import com.bohuikeji.frame.module.admin.utils.PrintUtils;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * 订单
 * @author 10552
 */
@Slf4j
@Api(tags = {"订单相关接口"})
@RestController
@RequestMapping("/api/order")
public class OrderApi extends ApiController {

    @Autowired
    ITOrderService orderService;
    @Autowired
    ITCourierService courierService;
    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ITLogisticsService logisticsService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    ITLocationService locationService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ITCustomerBigService customerBigService;
    @Autowired
    ITCustomerService customerService;
    @Autowired
    ITDiscountOrderService orderDiscountService;
    @Autowired
    ThirdUtils thirdUtils;
    @Autowired
    ITOrderArrearsService orderArrearsService;


    /**
     * 分页查询全部订单列表
     * 根据状态查询全部订单
     * @return
     */
    @ApiOperation("派送员:（分页查询全部订单列表/根据状态查询订单）")
    @GetMapping("/courier/order")
    @ApiOperationSupport(ignoreParameters = {"id","records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderStatus",value="订单状态（待接单、待取件、待派送、派送中、已完成）",dataType="String[]", paramType = "query",required=true),
            @ApiImplicitParam(name="orderStatus",value="查询订单区abcode(区县级)",dataType="String", paramType = "query",example = "150102",defaultValue = "150102"),
            @ApiImplicitParam(name="location",value="当前派送员经纬度",dataType="String", paramType = "query",example = "111.665544,40.858289",defaultValue = "111.665544,40.858289")})
    public APIEntity courierOrderAll(@RequestAttribute("JwtUserId") Integer id,DataPage page, String orderStatus,String abcode,String location,String cid){
        if (StringUtils.isBlank(orderStatus)){
            return APIEntity.fail("客户端参数为空！");
        }
        if(courierService.getCourierStatus(id)){
            return APIEntity.fail();
        }
        QueryWrapper<TOrder> queryWrapper=new QueryWrapper();
        queryWrapper.ne("is_test",1);
        queryWrapper.notLike("order_num","D%");
        if(StringUtils.isNotBlank(abcode)){
            queryWrapper.eq("json_extract(mailing_address,'$.adcode')",abcode);
        }
        AddressVo address = null;
        switch (orderStatus){
            case "待接单":
                queryWrapper.eq("order_status","待接单");
                queryWrapper.eq("is_third",false);
                //TCourier courier=courierService.getById(id);
                //更新派送员CID
                if (StringUtils.isNotBlank(cid)) {
                    courierService.update(new UpdateWrapper<TCourier>().set("cid", cid).eq("courier_id", id));
                }
                if(id != 59){
                    if(StringUtils.isNotBlank(location)){
                        address = courierService.getAddress(location,id);
                        if (StringUtils.isNotBlank(address.getCity())) {
                            queryWrapper.eq("json_extract(mailing_address,'$.city')",address.getCity());
                        }else{
                            queryWrapper.eq("json_extract(mailing_address,'$.province')",address.getProvince());
                        }
                    }else {
                        return APIEntity.fail("您的定位未开启，请开启定位。");
                    }
                }
                //批量订单兼职不可见,普通订单查询10秒之前的
                //queryWrapper = orderService.getTF(queryWrapper,courier);
                break;
            case "待取件":
                page.setDesc("acceptance_time");
                queryWrapper.eq("courier_id",id).eq("order_status","待取件").or().eq("order_status","取件中").eq("courier_id",id).or().eq("order_status","待支付").eq("courier_id",id);break;
            case "待派送":
                page.setDesc("acceptance_time");
                queryWrapper.eq("courier_id",id).eq("order_status","待派送").or().eq("order_status","派送中").eq("courier_id",id);break;
            case "派送中":
                page.setDesc("acceptance_time");
                queryWrapper.eq("courier_id",id).eq("order_status","运输中");break;
            case "已完成":
                page.setDesc("order_end_time");
                queryWrapper.eq("courier_id",id).eq("order_status","已完成");break;
            case "异常":
                page.setDesc("order_id");
                queryWrapper.eq("courier_id",id).eq("order_status","异常");break;
            default:
                log.error("客户端参数错误，无法识别的参数值：[{}]",orderStatus);
                return APIEntity.fail("无法识别参数[orderStatus="+orderStatus+"]");
        }
        IPage resPage=orderService.page(page,queryWrapper);
        AddressVo finalAddress = address;
        resPage.getRecords().forEach(orderObj->{
            TOrder order=((TOrder)orderObj);
            if("待接单".equals(order.getOrderStatus())){
                order.setDist(orderService.getDistanceByOrder(order, finalAddress));
            }
            List<Object> customerIds  = customerBigService.listObjs(new QueryWrapper<TCustomerBig>().select("customer_id").eq("courier_id",id));
            for(Object playerId : customerIds){
                TCustomer tCustomer = customerService.getById(Integer.valueOf(playerId.toString()));
                if(tCustomer != null && order.getPlayerId().equals(playerId)){
                    order.setExpert("专");
                }
            }
        });
        resPage.getRecords().sort(Comparator.comparing(TOrder::getDist));
        courierService.updateTime(id);
        return APIEntity.success(resPage);
    }
    /**
     * 分页查询全部订单列表
     * 根据状态查询订单
     * @return
     */
    @ApiOperation("客户:(分页查询全部订单列表/根据状态查询订单)")
    @GetMapping("/getOrderAll")
    @ApiOperationSupport(ignoreParameters = {"id","records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderStatus",value="订单状态(全部,进行中,已完成,待评价)",dataType="String", paramType = "query")})
    public APIEntity getOrderAll(@RequestAttribute("JwtUserId") Integer id,DataPage page,String orderStatus){
        if (StringUtils.isBlank(orderStatus)){
            return APIEntity.fail("客户端参数为空！");
        }
        String type = null;
        page.setDesc("order_id");
        QueryWrapper<TOrder> queryWrapper=new QueryWrapper<TOrder>().eq("player_id",id);
        switch (orderStatus){
            case "全部":
                ;break;
            case "进行中":
                queryWrapper.in("order_status","待接单","待取件","取件中","待派送","派送中","待支付","改派中");break;
            case "已完成":
                queryWrapper.eq("order_status","已完成").eq("evaluate_status","待评价");break;
            case "已评价":
                queryWrapper.eq("order_status","已完成").eq("evaluate_status","已评价");break;
            default:
                log.error("客户端参数错误，无法识别的参数值：[{}]",orderStatus);
                return APIEntity.fail("无法识别参数[orderStatus="+orderStatus+"]");
        }
        page = (DataPage) orderService.page(page,queryWrapper);
        JSONArray orderCour = new JSONArray();
        List<TOrder> tOrders = page.getRecords();
        for(TOrder tOrder :tOrders){
            TCourier tCourier = courierService.getById(tOrder.getCourierId());
           /* if (tCourier==null){
                orderCour.add(tOrder);
                continue;}*/
            if(tCourier != null && tCourier.getCourierId()!=11392){
                CourierAddressVo courierAddressVo=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS+tCourier.getCourierId(), CourierAddressVo.class);
                if (courierAddressVo!=null){
                    tOrder.setLongitude(courierAddressVo.getAddress().getLng());
                    tOrder.setLatitude(courierAddressVo.getAddress().getLat());
                    log.info("获取接单配送员的试试经纬度(自己的)：经度：{}，纬度：{}",tOrder.getLongitude(),tOrder.getLatitude());
                }
            }else {
                tOrder.setLongitude(null);
                tOrder.setLatitude(null);
            }
            if (tOrder.getThird() && !"待接单".equals(tOrder.getOrderStatus())){
                OrderDetailDO detail=thirdUtils.orderDetail(tOrder);
                //log.info("获取接单配送员的试试经纬度(第三方的信息)订单号：{}，骑手：{}",tOrder.getOrderNum(),detail.getCourierName());
                if (detail != null && tCourier != null && StringUtils.isNotBlank(detail.getCourierName()) && tOrder.getCourierId()!=null){
                    tCourier.setCourierName(detail.getCourierName());
                    tCourier.setCourierPhone(detail.getCourierPhone());
                    if(thirdUtils.courierInfo(tOrder).getLastLocation()!=null){
                        tOrder.setLongitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLng());
                        tOrder.setLatitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLat());
                    }else {
                        tOrder.setLongitude(null);
                        tOrder.setLatitude(null);
                    }
                }
            }
            if(orderArrearsService.list(new QueryWrapper<TOrderArrears>().eq("player_user",tOrder.getPlayerId()).eq("order_num",tOrder.getOrderNum()).eq("arrears_status","欠费")).size()>0){
                tOrder.setArrearsType("欠费");
            }
            tOrder.setCourier(tCourier);
            orderCour.add(tOrder);
        }
        page.setRecords(orderCour);
        return APIEntity.success(page);
    }
    /**
     * 分页查询全部订单列表
     * @return
     */
    @ApiOperation("分页查询全部订单列表")
    @GetMapping("/order/list")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderStatus",value="订单状态",dataType="String", paramType = "query")})
    public APIEntity orderListAll(DataPage page,String orderStatus){
        if (!StringUtils.isNotEmpty(orderStatus)){
            return APIEntity.success(orderService.page(page,new QueryWrapper<TOrder>()));
        }
        return APIEntity.success(orderService.page(page,new QueryWrapper<TOrder>().eq("order_status",orderStatus)));
    }

    /**
     * 根据订单id查询订单详情
     * @return
     */
    @ApiOperation("根据订单id查询订单详情(配送大厅->点击查看订单详情接口)")
    @GetMapping("/getorder")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount","id"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query")})
    public APIEntity<TOrder> getorder(@RequestAttribute("JwtUserId") Integer id, Integer orderId){
        log.error("#####################################是骑手端查询码########################################");
        TOrder tOrder = orderService.getById(orderId);
        if(tOrder==null){
            return APIEntity.fail("未找到该订单信息！");
        }
        if(!"待接单".equals(tOrder.getOrderStatus())){
            if("已取消".equals(tOrder.getOrderStatus())){
                return APIEntity.fail("该订单已经取消了！");
            }
            //不是该订单的派送员不可查看正在进性中的订单
            if(!id.equals(tOrder.getCourierId())){
                return APIEntity.fail("该订单已被抢走了！");
            }
        }
        //设置当前订单骑手信息返回给前端，用于判断当前查看订单详情的骑手是不是该订单的骑手，如果不是则客户端加密客户手机号
        TCourier tCourier = courierService.getById(tOrder.getCourierId());
        if (tOrder.getThird()){
            OrderDetailDO detail= thirdUtils.orderDetail(tOrder);
            tCourier.setCourierName(detail.getCourierName());
            tCourier.setCourierPhone(detail.getCourierPhone());
        }
        tOrder.setCourier(tCourier);
        return APIEntity.success(tOrder);
    }

    /**
     * 扫码查询订单详情
     * @return
     */
    @ApiOperation("扫码查询订单详情")
    @GetMapping("/getDetails")
    //配置忽略参数
    @ApiOperationSupport(ignoreParameters = {"records","total","searchCount"})
    @ApiImplicitParams({
            @ApiImplicitParam(name="logisticsNum",value="物流编号",dataType="String", paramType = "query")})
    public APIEntity<TOrder> getDetails(String logisticsNum){
        TLogistics tLogistics = logisticsService.getOne(new QueryWrapper<TLogistics>().eq("logistics_num",logisticsNum),false);
        TOrder tOrder;
        if(tLogistics==null){
            tOrder=orderService.getOne(new QueryWrapper<TOrder>().eq("order_num",logisticsNum),false);
        }
        else{
            tOrder = orderService.getById(tLogistics.getOrderId());
        }
        if(tOrder==null){
            return APIEntity.fail("未查询到相关订单信息！");
        }
        return APIEntity.success(tOrder);
    }

    /**
     * 根据订单号查询订单详情
     * @return
     */
    @ApiOperation("根据订单号查询订单详情")
    @GetMapping("/getOrderDetails")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orderId",value="订单id",dataType="Integer", paramType = "query")})
    public APIEntity<TOrder> getOrderDetails(Integer orderId){
        log.error("#####################################是客户端查询码2222########################################");
        TOrder tOrder = orderService.getById(orderId);
        if (tOrder==null){
            return APIEntity.fail("未找到订单信息，可能该订单已被删除！");
        }
        TCourier tCourier = courierService.getById(tOrder.getCourierId());
        if(tCourier != null && tCourier.getCourierId()!=11392){
            CourierAddressVo courierAddressVo=redisUtil.get(KeyConst.REDIS_COURIER_ADDRESS+tCourier.getCourierId(), CourierAddressVo.class);
            if (courierAddressVo!=null){
                tOrder.setLongitude(courierAddressVo.getAddress().getLng());
                tOrder.setLatitude(courierAddressVo.getAddress().getLat());
                log.info("获取接单配送员的试试经纬度(自己的)：经度：{}，纬度：{}",tOrder.getLongitude(),tOrder.getLatitude());
            }
        }else {
            tOrder.setLongitude(null);
            tOrder.setLatitude(null);
        }
        if (tOrder.getThird() && !"待接单".equals(tOrder.getOrderStatus())){
            OrderDetailDO detail=thirdUtils.orderDetail(tOrder);
            log.info("获取接单配送员的试试经纬度(第三方的信息)：{}",detail);
            if (detail != null && tCourier != null && StringUtils.isNotBlank(detail.getCourierName()) && tOrder.getCourierId()!=null){
                tCourier.setCourierName(detail.getCourierName());
                tCourier.setCourierPhone(detail.getCourierPhone());
                if(!"KD".equals(tOrder.getThirdName()) &&  thirdUtils.courierInfo(tOrder).getLastLocation()!=null){
                    tOrder.setLongitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLng());
                    tOrder.setLatitude(thirdUtils.courierInfo(tOrder).getLastLocation().getLat());
                }else {
                    tOrder.setLongitude(null);
                    tOrder.setLatitude(null);
                }
            }
        }
        tOrder.setCourier(tCourier);
        return APIEntity.success(tOrder);
    }

    /**
     * 消息队列测试
     * @param msg
     * @return
     */
    @ApiOperation("消息队列测试接口")
    @GetMapping("/rabbit/test/msg")
    public APIEntity testMessage(String queueName,String msg){
        rabbitTemplate.convertAndSend(queueName,"",msg);
        return APIEntity.success();
    }

    /**
     * 计算派送员当前区域订单与派送员的距离
     * @param queryWrapper 当前区域的所有订单
     * @param address 派送员位置的经纬度
     * @return
     */
    /*public QueryWrapper  getDistanceByOrder(QueryWrapper<TOrder> queryWrapper,AddressVo address){
        List<TOrder> orders =orderService.list(queryWrapper);
        ArrayList arrayList = new ArrayList();
        for(TOrder order : orders){
            //long dist =  MapUtils.getDistanceKm(order.getMailingAddress(),address);//高德计算距离的接口
            double dist =  DistanceUtils.getDistance(order.getMailingAddress().getLng(),order.getMailingAddress().getLat(),address.getLng(),address.getLat());//根据经纬度计算两点之间距离
            //System.out.println(order.getOrderNum()+":"+dist);
                if(dist<=3 && order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(3)) ==true){
                    arrayList.add(order.getOrderNum());
                }
                if(dist<=5 &&order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(3)) ==false
                        && order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(5)) ==true){
                    arrayList.add(order.getOrderNum());
                }
                if(dist<=10 && order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(3)) ==false
                        && order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(5)) == false
                        && order.getOrderCreateTime().isAfter(LocalDateTime.now().minusMinutes(9))==true){
                    arrayList.add(order.getOrderNum());
                }
        }
        if(arrayList.size()==0){
            return queryWrapper;
        }
        queryWrapper.in("order_num",arrayList);
        return queryWrapper;
    }*/

    /**
     * 订单单据
     *
     * @param orderId
     * @return
     */
    @InitLog(value = "订单单据",action = "打印")
    @GetMapping("/order/info/print")
    public APIEntity printBatchOrder(@RequestAttribute("JwtUserId") Integer id,Integer orderId) throws Exception {
        log.info("生成电子票据的订单id：{}",orderId);
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",id));
        if(order == null){
            return APIEntity.fail("订单不存在！");
        }
        if(!"已完成".equals(order.getOrderStatus())){
            return APIEntity.fail("订单未完成，无法生产单据！");
        }
        if(StringUtils.isNotBlank(order.getOrderBillUrl())){
            return APIEntity.success(order.getOrderBillUrl());
        }
        ImageCombiner combiner = new ImageCombiner("https://oss.bhynm.com/delivery/upload/2023/2/2/167530118159836.jpg", OutputFormat.JPG);
        combiner.addTextElement(order.getThirdNum()==null?order.getOrderNum():order.getThirdNum(),15,260, 189).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getMailingName() + "  " + order.getMailingPhone(),15, 150, 280).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getMailingAddress().getAddress() + order.getMailingAddress().getDetail(),15, 150, 310).setFont(new Font("微软雅黑", Font.PLAIN, 20)).setAutoBreakLine(500, 2, 30);
        combiner.addTextElement(order.getReceiptName() + "  " + order.getReceiptPhone(),15, 150, 440).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getReceiptAddress().getAddress() + order.getReceiptAddress().getDetail(),15, 150, 470).setFont(new Font("微软雅黑", Font.PLAIN, 20)).setAutoBreakLine(500, 2, 30);
        combiner.addTextElement(order.getOrderRemarks(),15, 150, 610).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getCargoName(),15, 70, 700).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getCargoWeight() + "公斤",15, 75, 730).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderFactPrice()+"元",15, 380, 690).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getAcceptanceTime().toString(),16, 190, 879).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderEndTime().toString(),16, 190, 932).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderNum(),16, 190, 984).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        //执行图片合并
        combiner.combine();
        //可以获取流（并上传oss等）
        InputStream is = combiner.getCombinedImageStream();
        String templateUrl = MinioUtil.uploadFileB(is,".jpg");
        log.info("优惠卷信息33:{}",templateUrl);
        orderService.updateById(order.setOrderBillUrl(templateUrl));
        return APIEntity.success(templateUrl);
    }

    /*@InitLog(value = "订单单据",action = "打印")
    @GetMapping("/order/info/print")
    public APIEntity printBatchOrder(@RequestAttribute("JwtUserId") Integer id,Integer orderId) throws IOException {
        log.info("生成电子票据的订单id：{}",orderId);
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",id));
        if(order == null){
            return APIEntity.fail("订单不存在！");
        }
        if(!"已完成".equals(order.getOrderStatus())){
            return APIEntity.fail("订单未完成，无法生产单据！");
        }
        if(StringUtils.isNotBlank(order.getOrderBillUrl())){
            return APIEntity.success(order.getOrderBillUrl());
        }
        InputStream is = null;
        ByteArrayOutputStream out = null;
        //创建并载入打印文档
        PDDocument pdf = new PDDocument();
        PDFont font = PDType0Font.load(
                pdf,
                FileUtil.download("https://oss.tcjskd.com/delivery/upload/fonts/Deng.ttf"));
        //定义打印单页，后面使用模板绘制重复使用
        PDPage page;
        //订单打印单页页面流，同样后面使用模板重复使用
        PDPageContentStream contents;
        PDDocument tmpDoc = PDDocument.load(FileUtil.download("https://oss.tcjskd.com/delivery/upload/fonts/tcjsorder.pdf"));
        page = tmpDoc.getPage(0);
        contents = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.APPEND, true, true);
        //绘制物流单号(当前为订单号)
        TextUtils.drawRow(contents, font, 15, 190, 739, order.getThirdNum()==null?order.getOrderNum():order.getThirdNum());
        //绘制寄件人信息
        TextUtils.drawRow(contents, font, 15, 120, 680, order.getMailingName() + "  " + order.getMailingPhone());
        //寄件人地址
        TextUtils.drawRows(contents, font, 15, 120, 660, 21, order.getMailingAddress().getAddress() + order.getMailingAddress().getDetail());
        //绘制收件人信息
        TextUtils.drawRow(contents, font, 15, 120, 560, order.getReceiptName() + "  " + order.getReceiptPhone());
        //绘制收件人地址
        TextUtils.drawRows(contents, font, 15, 120, 540, 21, order.getReceiptAddress().getAddress() + order.getReceiptAddress().getDetail());
        //绘制备注
        TextUtils.drawRows(contents, font, 15, 120, 430,  21,order.getOrderRemarks());
        //绘制获取类型
        TextUtils.drawRows(contents, font, 15, 65, 360, 10, order.getCargoName());
        //绘制重量
        TextUtils.drawRow(contents, font, 15, 70, 330, order.getCargoWeight() + "公斤");
        //绘制支付方式
        TextUtils.drawRow(contents, font, 15, 270, 365, order.getOrderFactPrice()+"元");
        //绘制寄件时间
        TextUtils.drawRow(contents, font, 15, 130, 225, order.getAcceptanceTime().toString());
        //绘制完成时间
        TextUtils.drawRow(contents, font, 15, 130, 185, order.getOrderEndTime().toString());
        //绘制订单编号
        TextUtils.drawRow(contents, font, 15, 130, 147, order.getOrderNum());
        pdf.addPage(page);
        contents.close();
        out = new ByteArrayOutputStream();
        pdf.save(out);
        pdf.close();
        byte[] data = out.toByteArray();
        is = new ByteArrayInputStream(data);
        String url = MinioUtil.uploadFile(is,".pdf");
        orderService.updateById(order.setOrderBillUrl(url));
        return APIEntity.success(order.getOrderBillUrl());
    }*/

    /**
     * 订单单据
     *https://oss.bhynm.com/delivery/upload/2023/2/2/167530118159836.jpg
     * @param orderId
     * @return
     */
    @ApiOperation("###############################")
    @GetMapping("/order/info/print/test")
    public APIEntity printBatchOrderTest(Integer id,Integer orderId) throws Exception {
        log.info("生成电子票据的订单id：{}",orderId);
        TOrder order = orderService.getOne(new QueryWrapper<TOrder>().eq("order_id",orderId).eq("player_id",id));
        if(order == null){
            return APIEntity.fail("订单不存在！");
        }
        if(!"已完成".equals(order.getOrderStatus())){
            return APIEntity.fail("订单未完成，无法生产单据！");
        }
        if(StringUtils.isNotBlank(order.getOrderBillUrl())){
            return APIEntity.success(order.getOrderBillUrl());
        }
        ImageCombiner combiner = new ImageCombiner("https://oss.bhynm.com/delivery/upload/2023/2/2/167530118159836.jpg", OutputFormat.JPG);
        combiner.addTextElement(order.getThirdNum()==null?order.getOrderNum():order.getThirdNum(),15,260, 189).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getMailingName() + "  " + order.getMailingPhone(),15, 150, 280).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getMailingAddress().getAddress() + order.getMailingAddress().getDetail(),15, 150, 310).setFont(new Font("微软雅黑", Font.PLAIN, 20)).setAutoBreakLine(500, 2, 30);
        combiner.addTextElement(order.getReceiptName() + "  " + order.getReceiptPhone(),15, 150, 440).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getReceiptAddress().getAddress() + order.getReceiptAddress().getDetail(),15, 150, 470).setFont(new Font("微软雅黑", Font.PLAIN, 20)).setAutoBreakLine(500, 2, 30);
        combiner.addTextElement(order.getOrderRemarks(),15, 150, 610).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getCargoName(),15, 70, 700).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getCargoWeight() + "公斤",15, 75, 730).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderFactPrice()+"元",15, 380, 690).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getAcceptanceTime().toString(),16, 190, 879).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderEndTime().toString(),16, 190, 932).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        combiner.addTextElement(order.getOrderNum(),16, 190, 984).setFont(new Font("微软雅黑", Font.PLAIN, 20));
        //执行图片合并
        combiner.combine();
        //可以获取流（并上传oss等）
        InputStream is = combiner.getCombinedImageStream();
        String templateUrl = MinioUtil.uploadFileB(is,".jpg");
        log.info("优惠卷信息33:[{}]",templateUrl);
        return APIEntity.success(templateUrl);
    }

}
