package com.bonus.material.order.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.bonus.common.biz.config.ListPagingUtil;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.ServletUtils;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.basic.mapper.BmMessageMapper;
import com.bonus.material.common.annotation.PreventRepeatSubmit;
import com.bonus.material.contract.domain.BmContract;
import com.bonus.material.contract.service.BmContractService;
import com.bonus.material.lease.domain.DeptDto;
import com.bonus.material.lease.mapper.LeaseRepairRecordMapper;
import com.bonus.material.order.domain.OrderDetailDto;
import com.bonus.material.order.domain.OrderInfoDto;
import com.bonus.material.order.domain.ProDto;
import com.bonus.material.order.mapper.OrderMapper;
import com.bonus.material.order.service.OrderService;
import com.bonus.system.api.RemoteFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @Author：liang.chao
 * @Date：2024/11/26 - 10:04
 */

@Api(value = "订单模块", tags = {"订单模块"})
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private LeaseRepairRecordMapper leaseRepairRecordMapper;

    @Resource
    private BmContractService bmContractService;

    @Resource
    private RemoteFileService sysFileService;

    @Resource
    private BmMessageMapper bmMessageMapper;

    // 中文大写数字
    private static final String[] CHINESE_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    // 位数单位
    private static final String[] UNITS = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万"};
    // 小数部分单位
    private static final String[] DECIMAL_UNITS = {"角", "分"};

    /**
     * 提交预约车到订单
     */
    @ApiOperation(value = "提交预约车到订单")
    @PostMapping("/submitBookCar")
    @PreventRepeatSubmit
    public AjaxResult submitBookCar(@RequestBody ProDto proDto) {
        Integer i = orderService.submitOrderInfo(proDto);
        if (i > 0) {
            return success("下单成功");
        } else {
            return error("下单失败");
        }
    }

    /**
     * 获取订单详情
     */
    @ApiOperation(value = "获取订单详情")
    @GetMapping("/getOrderDetails")
    public AjaxResult getOrderDetails(OrderInfoDto orderInfoDto) throws Exception {
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        List<OrderInfoDto> list = orderService.getOrderDetails(orderInfoDto);
        return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
    }

    /**
     * 获取单个订单详情
     */
    @ApiOperation(value = "获取单个订单详情")
    @GetMapping("/getOrderDetailsById")
    public AjaxResult getOrderDetailsById(OrderDetailDto dto) throws Exception {
        if (dto.getOrderId() != null) {
            OrderInfoDto orderInfoDto = orderService.getOrderDetailsById(dto);
            return success(orderInfoDto);
        } else {
            return error("参数错误");
        }
    }

    @ApiOperation(value = "获取单个订单详情")
    @GetMapping("/getOrderStatusCount")
    public AjaxResult getOrderStatusCount(OrderDetailDto dto) throws Exception {
        List<OrderInfoDto> list = orderService.getOrderStatusCount(dto);
        return success(list);
    }

    /**
     * 获取单个订单取件码
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "获取单个订单取件码")
    @GetMapping("/getOrderCode")
    public AjaxResult getOrderCode(OrderDetailDto dto) {
        int code = orderService.getOrderCode(dto);
        return success(code);
    }

    /**
     * 订单状态流转修改
     */
    @ApiOperation(value = "订单状态流转修改")
    @PreventRepeatSubmit
    @PostMapping("/updateOrderStatus")
    public AjaxResult updateOrderStatus(@RequestBody OrderDetailDto orderInfoDto) {
        if (orderInfoDto.getOrderId() == null || StringUtils.isBlank(orderInfoDto.getOrderStatus())) {
            return error("参数错误");
        }
        Integer i = orderService.updateOrderStatus(orderInfoDto);
        if (i > 0) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 发起减免
     */
    @ApiOperation(value = "发起减免")
    @PostMapping("/costRelief")
    public AjaxResult costRelief(@RequestBody OrderInfoDto orderInfoDto) {
        Integer i = orderService.inputCostRelief(orderInfoDto);
        if (i > 0) {
            return success("发起减免成功");
        } else {
            return error("发起减免失败");
        }
    }

    /**
     * 发起减免
     */
    @ApiOperation(value = "减免改价")
    @PostMapping("/changeReliefPrice")
    public AjaxResult changeReliefPrice(@RequestBody OrderInfoDto orderInfoDto) {
        Integer i = orderService.changeReliefPrice(orderInfoDto);
        if (i > 0) {
            return success("减免改价成功");
        } else {
            return error("减免改价失败");
        }
    }

    @ApiOperation(value = "租赁协议(查看)-word方式")
    @GetMapping("/leaseAgreement")
    public AjaxResult leaseAgreement(String orderId, Map<String, String> replacements) throws IOException, ParseException {
        OrderInfoDto orderInfoDto = orderService.getAgreementByOrderId(orderId);
        List<OrderDetailDto> orderDetailsByOrderId = orderMapper.selectOrderDetailsByOrderId(orderId);
        BmContract bmContract = new BmContract();
        bmContract.setStatus(1);
        bmContract.setOwnerCom(orderInfoDto.getCompanyId().longValue());
        List<BmContract> list = bmContractService.getContractUrl(bmContract);
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("请先上传合同");
        }
        if (list.get(0).getBmFileInfoList().isEmpty()) {
            return AjaxResult.error("请先上传合同附件");
        }
        String wordUrl = list.get(0).getBmFileInfoList().get(0).getFileUrl();
        String contractCode = list.get(0).getContractCode();
        InputStream inputStream = new URL(wordUrl).openStream();

        XWPFDocument document = new XWPFDocument(inputStream);
        String dateStr = orderInfoDto.getOrderTime().toString();
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = inputFormat.parse(dateStr);
        String formattedDate = outputFormat.format(date);
        Date date1 = inputFormat.parse(orderInfoDto.getStartTime().toString());
        String startTime = outputFormat.format(date1);
        Date date2 = inputFormat.parse(orderInfoDto.getEndTime().toString());
        String endTime = outputFormat.format(date2);
        //订单日期
        replacements.put("${createTime}", formattedDate);

        //合同编号
        replacements.put("${contractCode}", contractCode);

        //设备名
        replacements.put("${deviceNames}", orderInfoDto.getDeviceNames());

        //开始时间
        replacements.put("${startTime}", startTime);

        //结束时间
        replacements.put("${{endTime}}", endTime);

        //装备所属公司
        replacements.put("${sellerCompanyName}", orderInfoDto.getCzcompanyName());

        //承租方所属公司
        replacements.put("${buyerCompanyName}", orderInfoDto.getCompanyName());

        //订单金额大写
        replacements.put("${costBig}", convert(Double.valueOf(orderInfoDto.getCost().toString())));

        //订单金额
        replacements.put("${cost}", orderInfoDto.getCost().toString());

        //不含税金额
        BigDecimal noTaxCost = orderInfoDto.getCost().multiply(BigDecimal.valueOf(0.87)).setScale(2, RoundingMode.HALF_UP);
        replacements.put("${noTaxCost}", noTaxCost.toString());

        //不含税金额大写
        replacements.put("${noTaxCostBig}", convert(Double.valueOf(noTaxCost.toString())));

        //税额
        BigDecimal taxCost = orderInfoDto.getCost().subtract(noTaxCost);
        replacements.put("${taxCost}", taxCost.toString());

        //出租方电话
        replacements.put("${sellerCompanyPhone}", orderInfoDto.getPersonPhone());

        //承租方电话
        replacements.put("${buyerCompanyPhone}", orderInfoDto.getPhoneNumber());
        //订单详情
//        StringBuilder orderDetail = new StringBuilder();
   /*     for (OrderDetailDto orderDetailDto : orderDetailsByOrderId) {
            Date rentBeginTime = inputFormat.parse(orderDetailDto.getRentBeginTime().toString());
            String beginTime = outputFormat.format(rentBeginTime);
            Date rentEndTime = inputFormat.parse(orderDetailDto.getRentEndTime().toString());
            String endTime = outputFormat.format(rentEndTime);
            // 添加每一行的内容
            orderDetail.append("\n");
            orderDetail.append("机具名称：").append(orderDetailDto.getDeviceName()).append("\n")
                    .append("租期：").append(beginTime).append(" 至 ").append(endTime).append("\n")
                    .append("天数：").append(orderDetailDto.getDays()).append("天").append("\n")
                    .append("租金：").append(orderDetailDto.getDayLeasePrice()).append("元/天").append("\n")
                    .append("数量：").append(orderDetailDto.getNum()).append("个").append("\n");
        }*/
        // 填充订单详情到表格
        fillOrderTable(document, orderDetailsByOrderId, orderInfoDto.getCost().toString());

        // 将拼接的字符串放入替换的map中
//        replacements.put("${orderTable}", orderDetail.toString());

        for (IBodyElement element : document.getBodyElements()) {
            if (element instanceof XWPFParagraph) {
                XWPFParagraph paragraph = (XWPFParagraph) element;
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        for (Map.Entry<String, String> entry : replacements.entrySet()) {
                            String entryValue = entry.getValue();
                            if (entryValue == null) {
                                continue;
                            }
                            text = text.replace(entry.getKey(), entryValue);
                        }
                        run.setText(text, 0);
                    }
                }
            }
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        byte[] wordBytes = outputStream.toByteArray();

        MultipartFile file = new MockMultipartFile("contract", "contract.docx", MediaType.APPLICATION_OCTET_STREAM_VALUE, wordBytes);
        return sysFileService.upload(file);
    }

    @ApiOperation(value = "购物车协议(查看)-word方式")
    @PostMapping("/bookCarAgreement")
    public AjaxResult bookCarAgreement(@RequestBody OrderInfoDto orderInfoDto) throws ParseException, IOException {
        if (orderInfoDto != null) {
            BmContract bmContract = new BmContract();
            bmContract.setStatus(1);
            bmContract.setOwnerCom(orderInfoDto.getCompanyId().longValue());

            List<DeptDto> deptDtoList = bmMessageMapper.getdeptIds();
            if (CollectionUtils.isEmpty(deptDtoList)) {
                return AjaxResult.error("数据库中部门数据为空");
            } else {
                Long loginDeptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
                for (DeptDto dto : deptDtoList) {
                    if (Objects.equals(loginDeptId, dto.getDeptId())) {
                        System.out.println("当前登录用户公司名称：" + dto.getCompanyName());
                        orderInfoDto.setCompanyName(dto.getCompanyName());
                    }
                }
            }

            List<BmContract> list = bmContractService.getContractUrl(bmContract);
            if (CollectionUtils.isEmpty(list)) {
                return AjaxResult.error("请先上传合同");
            }
            String wordUrl = list.get(0).getBmFileInfoList().get(0).getFileUrl();
            String contractCode = list.get(0).getContractCode();
            InputStream inputStream = new URL(wordUrl).openStream();
            XWPFDocument document = new XWPFDocument(inputStream);
            SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = inputFormat.parse(String.valueOf(orderInfoDto.getDetailsList().get(0).getRentBeginTime()));
            String startTime = outputFormat.format(date1);
            Date date2 = inputFormat.parse(String.valueOf(orderInfoDto.getDetailsList().get(0).getRentEndTime()));
            String endTime = outputFormat.format(date2);
            Map<String, String> replacements = new HashMap<>();
            //订单日期
            replacements.put("${createTime}", DateUtils.getDate());

            //合同编号
            replacements.put("${contractCode}", contractCode);

            // 获取设备名
            StringBuilder deviceNames = new StringBuilder();
            List<OrderDetailDto> detailsList = orderInfoDto.getDetailsList();

            // 遍历detailsList，获取设备名，并添加到deviceNames中
            if (CollectionUtil.isNotEmpty(detailsList)) {
                detailsList.stream()
                        .filter(orderDetailDto -> orderDetailDto != null && orderDetailDto.getDeviceName() != null)
                        .map(OrderDetailDto::getDeviceName)
                        .forEach(deviceName -> deviceNames.append(deviceName).append(","));
            }


            replacements.put("${deviceNames}", deviceNames.toString());

            //开始时间
            replacements.put("${startTime}", startTime);

            //结束时间
            replacements.put("${{endTime}}", endTime);

            //装备所属公司
            replacements.put("${sellerCompanyName}", orderInfoDto.getCzcompanyName());

            //承租方所属公司
            replacements.put("${buyerCompanyName}", orderInfoDto.getCompanyName());

            //订单金额大写
            replacements.put("${costBig}", convert(Double.valueOf(orderInfoDto.getCost().toString())));

            //订单金额
            replacements.put("${cost}", orderInfoDto.getCost().toString());

            //不含税金额
            BigDecimal noTaxCost = orderInfoDto.getCost().multiply(BigDecimal.valueOf(0.87)).setScale(2, RoundingMode.HALF_UP);
            replacements.put("${noTaxCost}", noTaxCost.toString());

            //不含税金额大写
            replacements.put("${noTaxCostBig}", convert(Double.valueOf(noTaxCost.toString())));

            //税额
            BigDecimal taxCost = orderInfoDto.getCost().subtract(noTaxCost);
            replacements.put("${taxCost}", taxCost.toString());

            //出租方电话
            replacements.put("${sellerCompanyPhone}", orderInfoDto.getPersonPhone());

            //承租方电话
            replacements.put("${buyerCompanyPhone}", orderInfoDto.getPhoneNumber());
           /* StringBuilder orderDetail = new StringBuilder();
            List<OrderDetailDto> detailsList = orderInfoDto.getDetailsList();
            for (OrderDetailDto orderDetailDto : detailsList) {
                if (Objects.isNull(orderDetailDto.getRentBeginTime()) || Objects.isNull(orderDetailDto.getRentEndTime())) {
                    return AjaxResult.error("请先选择租期");
                }
                Date rentBeginTime = inputFormat.parse(orderDetailDto.getRentBeginTime().toString());
                String beginTime = outputFormat.format(rentBeginTime);
                Date rentEndTime = inputFormat.parse(orderDetailDto.getRentEndTime().toString());
                String endTime = outputFormat.format(rentEndTime);
                // 添加每一行的内容
                orderDetail.append("\n");
                orderDetail.append("机具名称：").append(orderDetailDto.getDeviceName()).append("\n")
                        .append("租期：").append(beginTime).append(" 至 ").append(endTime).append("\n")
                        .append("天数：").append(orderDetailDto.getDays()).append("天").append("\n")
                        .append("租金：").append(orderDetailDto.getDayLeasePrice()).append("元/天").append("\n")
                        .append("数量：").append(orderDetailDto.getNum()).append("个").append("\n");
            }
            replacements.put("${orderTable}", orderDetail.toString());*/
            // 填充订单详情到表格
            fillOrderTable(document, orderInfoDto.getDetailsList(), orderInfoDto.getCost().toString());
            for (IBodyElement element : document.getBodyElements()) {
                if (element instanceof XWPFParagraph) {
                    XWPFParagraph paragraph = (XWPFParagraph) element;
                    for (XWPFRun run : paragraph.getRuns()) {
                        String text = run.getText(0);
                        if (text != null) {
                            for (Map.Entry<String, String> entry : replacements.entrySet()) {
                                // 检查 entry.getValue() 是否为 null
                                if (entry.getValue() != null) {
                                    text = text.replace(entry.getKey(), entry.getValue());
                                }
                            }
                            run.setText(text, 0);
                        }
                    }
                }
            }

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            document.write(outputStream);
            byte[] wordBytes = outputStream.toByteArray();

            MultipartFile file = new MockMultipartFile("bookCar", "bookCar.docx", MediaType.APPLICATION_OCTET_STREAM_VALUE, wordBytes);
            return sysFileService.upload(file);
        } else {
            return AjaxResult.error("参数错误");
        }
    }


    /**
     * 将数字转换为中文大写金额
     *
     * @param number 输入的数字（必须是正数且最多保留两位小数）
     * @return 中文大写金额
     */
    public static String convert(double number) {
        if (number < 0) {
            throw new IllegalArgumentException("只支持正数转换！");
        }

        // 转换为 BigDecimal 并保留两位小数
        BigDecimal decimal = new BigDecimal(number).setScale(2, BigDecimal.ROUND_HALF_UP);
        String numStr = decimal.toPlainString();

        // 分离整数部分和小数部分
        String[] parts = numStr.split("\\.");
        String integerPart = parts[0]; // 整数部分
        String decimalPart = parts.length > 1 ? parts[1] : "00"; // 小数部分，默认补足两位

        // 处理整数部分
        StringBuilder chineseInteger = new StringBuilder();
        boolean hasNonZero = false; // 标记是否有非零数字
        for (int i = 0; i < integerPart.length(); i++) {
            char digitChar = integerPart.charAt(i);
            int digit = Character.getNumericValue(digitChar);
            int unitIndex = integerPart.length() - i - 1;

            // 转换数字为中文大写
            if (digit != 0) {
                hasNonZero = true;
                chineseInteger.append(CHINESE_NUMBERS[digit]);
                chineseInteger.append(UNITS[unitIndex]);
            } else if (hasNonZero || (unitIndex > 0 && UNITS[unitIndex].equals("万") || UNITS[unitIndex].equals("亿"))) {
                // 如果前面有非零数字或遇到“万”、“亿”，保留“零”
                chineseInteger.append(CHINESE_NUMBERS[digit]);
                hasNonZero = false;
            }
        }

        // 去掉多余的“零”
        String processedInteger = removeExtraZeros(chineseInteger.toString());

        // 添加“元”字
        if (processedInteger.isEmpty()) {
            processedInteger = "零";
        }
        processedInteger += "元";

        // 处理小数部分
        StringBuilder chineseDecimal = new StringBuilder();
        for (int i = 0; i < decimalPart.length(); i++) {
            if (i >= DECIMAL_UNITS.length) {
                break; // 超过两位小数的部分忽略
            }
            int digit = Character.getNumericValue(decimalPart.charAt(i));
            if (digit != 0) {
                chineseDecimal.append(CHINESE_NUMBERS[digit]);
                chineseDecimal.append(DECIMAL_UNITS[i]);
            } else if (i == 0 && !chineseDecimal.toString().contains("角")) {
                chineseDecimal.append(CHINESE_NUMBERS[digit]); // 补充“零”字
            }
        }

        // 如果小数部分全为零，则补充“整”字
        if (decimalPart.equals("00")) {
            return processedInteger + "整";
        } else {
            return processedInteger + chineseDecimal.toString();
        }
    }

    /**
     * 去掉多余的“零”
     *
     * @param str 输入字符串
     * @return 去掉多余“零”的字符串
     */
    private static String removeExtraZeros(String str) {
        String result = str.replaceAll("(?<=\\B)零(?=\\B)", ""); // 去掉连续的“零”
        result = result.replaceAll("亿万", "亿"); // 去掉“亿万”中的“万”
        result = result.replaceAll("零+$", ""); // 去掉末尾的“零”
        return result;
    }

    private static void fillOrderTable(XWPFDocument document, List<OrderDetailDto> orderDetails, String cost) {
        XWPFTable table = null;
        int headerRowIndex = 0; // 表头行索引
        int footerRowIndex = 0; // 合计行索引
        int cellCount = 0;
        try {
            // 获取第一个表格（假设模板中只有一个表格）
            table = document.getTables().get(1);

            // 保留第一行（表头）和最后一行（合计行），仅在中间插入数据行
            headerRowIndex = 0;
            footerRowIndex = table.getRows().size();

            // 删除中间的所有行（如果有的话）
            for (int i = table.getRows().size() - 2; i > headerRowIndex; i--) {
                table.removeRow(i);
            }
            // 获取表头行的单元格数量
            cellCount = table.getRow(headerRowIndex).getTableCells().size();

            // 遍历订单详情并动态插入数据行
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (IndexOutOfBoundsException e) {
            throw new RuntimeException("模板表处理异常，请检查合同信息");
        }
        int num = orderDetails.size();
        for (OrderDetailDto detail : orderDetails) {
            XWPFTableRow newRow = table.insertNewTableRow(headerRowIndex + 1);

            // 确保新行有足够数量的单元格
            while (newRow.getTableCells().size() < cellCount) {
                newRow.createCell();
            }
            int cellIndex = 0;
            // 序号
            newRow.getCell(cellIndex++).setText(String.valueOf(num));
            num--;

            // 机具名称
            newRow.getCell(cellIndex++).setText(detail.getDeviceName());
            String typeName = detail.getTypeName();
            // 规格型号
            newRow.getCell(cellIndex++).setText(typeName);
            // 单位
            newRow.getCell(cellIndex++).setText(detail.getUnitName());
            // 数量
            newRow.getCell(cellIndex++).setText(detail.getNum() + "个");

            // 租金
            newRow.getCell(cellIndex++).setText(detail.getDayLeasePrice() + "元/天");
            // 税率
            newRow.getCell(cellIndex++).setText("%13");

            // 天数
            newRow.getCell(cellIndex++).setText(detail.getDays() + "天");

            // 预估租赁费用
            newRow.getCell(cellIndex++).setText(detail.getCosts() + "元");

            // 备注
            newRow.getCell(cellIndex).setText("");
            // 填充最后一行（合计行）
            XWPFTableRow footerRow = table.getRow(footerRowIndex);
            int footerCellIndex = 0;

            // 跳过无关列
            footerCellIndex += 1;

            // 合计金额
            footerRow.getCell(footerCellIndex).setText(cost + "元");


//                // 租期开始时间
//                newRow.getCell(cellIndex++).setText(outputFormat.format(detail.getRentBeginTime()));
//
//                // 租期结束时间
//                newRow.getCell(cellIndex).setText(outputFormat.format(detail.getRentEndTime()));

        }
    }


   /* @ApiOperation(value = "租赁协议(查看)-富文本方式")
    @GetMapping("/leaseAgreement")
    public AjaxResult getleaseAgreement(String orderId, Map<String, String> replacements) throws ParseException {
        OrderInfoDto orderInfoDto = orderService.getAgreementByOrderId(orderId);
        List<OrderDetailDto> orderDetailsByOrderId = orderMapper.selectOrderDetailsByOderId(orderId);
        String dateStr = orderInfoDto.getOrderTime().toString();
        SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = inputFormat.parse(dateStr);
        String formattedDate = outputFormat.format(date);

        //订单日期
        replacements.put("orderTime", formattedDate);
        //装备所属公司
        replacements.put("czCompanyName", orderInfoDto.getCzcompanyName());
        //承租方所属公司
        replacements.put("companyName", orderInfoDto.getCompanyName());
        //订单金额
        replacements.put("cost", orderInfoDto.getCost().toString());
        //订单详情
        String orderDetail = "";
        for (OrderDetailDto orderDetailDto : orderDetailsByOrderId) {
            Date rentBeginTime = inputFormat.parse(orderDetailDto.getRentBeginTime().toString());
            String beginTime = outputFormat.format(rentBeginTime);
            Date rentEndTime = inputFormat.parse(orderDetailDto.getRentEndTime().toString());
            String endTime = outputFormat.format(rentEndTime);
            orderDetail += "<p><br>机具名称：" + orderDetailDto.getDeviceName() + "<br>租期：" + beginTime + "至" + endTime + "<br>天数：" + orderDetailDto.getDays() + "天 <br>租金：" + orderDetailDto.getDayLeasePrice() + "元/天<br>数量：" + orderDetailDto.getNum() + "</p>";
        }
        replacements.put("orderTable", orderDetail);

        BmContract bmContract = new BmContract();
        bmContract.setCompanyId(orderInfoDto.getCompanyId());
        bmContract = bmContractService.getContract(bmContract);
        if (bmContract == null || StringUtils.isBlank(bmContract.getContent())) {
            bmContract = new BmContract();
            bmContract.setContent(bmContractService.lisTemplate(bmContract).get(0).getContent());
        }
        StrSubstitutor sub = new StrSubstitutor(replacements);
        String result = sub.replace(bmContract.getContent());
        return AjaxResult.success(result);
    }*/

 /*   @ApiOperation(value = "购物车协议(查看)-富文本方式")
    @PostMapping("/bookCarAgreement")
    public AjaxResult getbookCarAgreement(@RequestBody OrderInfoDto orderInfoDto) throws ParseException {
        if (orderInfoDto != null) {
            SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Map<String, String> replacements = new HashMap<>();
            //装备所属公司
            replacements.put("czCompanyName", orderInfoDto.getCzcompanyName());
            //承租方所属公司
            replacements.put("companyName", orderInfoDto.getCompanyName());
            //订单金额
            replacements.put("cost", orderInfoDto.getCost().toString());
            //订单详情
            String orderDetail = "";
            List<OrderDetailDto> detailsList = orderInfoDto.getDetailsList();
            for (OrderDetailDto orderDetailDto : detailsList) {
                if (Objects.isNull(orderDetailDto.getRentBeginTime()) || Objects.isNull(orderDetailDto.getRentEndTime())){
                    return AjaxResult.error("请选择租赁日期");
                }
                Date rentBeginTime = inputFormat.parse(orderDetailDto.getRentBeginTime().toString());
                String beginTime = outputFormat.format(rentBeginTime);
                Date rentEndTime = inputFormat.parse(orderDetailDto.getRentEndTime().toString());
                String endTime = outputFormat.format(rentEndTime);
                orderDetail += "<p><br>机具名称：" + orderDetailDto.getDeviceName() + "<br>租期：" + beginTime + "至" + endTime + "<br>天数：" + orderDetailDto.getDays() + "天 <br>租金：" + orderDetailDto.getDayLeasePrice() + "元/天<br>数量：" + orderDetailDto.getNum() + "</p>";
            }
            replacements.put("orderTable", orderDetail);

            BmContract bmContract = new BmContract();
            bmContract = bmContractService.getContract(bmContract);
            if (bmContract == null || StringUtils.isBlank(bmContract.getContent())) {
                bmContract = new BmContract();
                bmContract.setContent(bmContractService.lisTemplate(bmContract).get(0).getContent());
            }
            StrSubstitutor sub = new StrSubstitutor(replacements);
            String result = sub.replace(bmContract.getContent());
            return AjaxResult.success(result);
        } else {
            return AjaxResult.error("参数错误");
        }
    }*/
}
