/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.record.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.bizappointmentrecord.entity.BizAppointmentRecord;
import vip.xiaonuo.biz.modular.bizappointmentrecord.service.BizAppointmentRecordService;
import vip.xiaonuo.biz.modular.bizorder.entity.BizOrder;
import vip.xiaonuo.biz.modular.bizorder.service.BizOrderService;
import vip.xiaonuo.biz.modular.mq.MqttSubscribeClient;
import vip.xiaonuo.biz.modular.record.param.*;
import vip.xiaonuo.biz.modular.record.result.BizRecordExportResult;
import vip.xiaonuo.biz.modular.record.result.CarResult;
import vip.xiaonuo.biz.modular.record.result.CompanyResult;
import vip.xiaonuo.biz.modular.record.result.GoodsResult;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.record.entity.BizRecord;
import vip.xiaonuo.biz.modular.record.mapper.BizRecordMapper;
import vip.xiaonuo.biz.modular.record.service.BizRecordService;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.CommonResponseUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 过磅记录Service接口实现类
 *
 * @author 徐超
 * @date 2025/01/02 16:34
 **/
@Service
public class BizRecordServiceImpl extends ServiceImpl<BizRecordMapper, BizRecord> implements BizRecordService {

    @Resource
    private BizAppointmentRecordService bizAppointmentRecordService;

    @Resource
    private BizOrderService bizOrderService;

    @Resource
    private MqttSubscribeClient mqttSubscribeClient;

    @Override
    public Page<BizRecord> page(BizRecordPageParam bizRecordPageParam) {
        QueryWrapper<BizRecord> queryWrapper = getQueryWrapper(bizRecordPageParam);
        return this.getBaseMapper().getPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    public QueryWrapper<BizRecord> getQueryWrapper(BizRecordPageParam bizRecordPageParam){
        QueryWrapper<BizRecord> queryWrapper = new QueryWrapper<BizRecord>().checkSqlInjection();
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getLicensePlate())) {
            queryWrapper.like("br.LICENSE_PLATE", bizRecordPageParam.getLicensePlate());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getStartGrossTime()) && ObjectUtil.isNotEmpty(bizRecordPageParam.getEndGrossTime())) {
            queryWrapper.between("br.GROSS_TIME", bizRecordPageParam.getStartGrossTime()+ " 00:00:00", bizRecordPageParam.getEndGrossTime()+" 23:59:59");
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getStartTareTime()) && ObjectUtil.isNotEmpty(bizRecordPageParam.getEndTareTime())) {
            queryWrapper.between("br.TARE_TIME", bizRecordPageParam.getStartTareTime()+" 00:00:00", bizRecordPageParam.getEndTareTime()+" 23:59:59");
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getDriverName())) {
            queryWrapper.like("br.DRIVER_NAME", bizRecordPageParam.getDriverName());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getDriverMobile())) {
            queryWrapper.like("br.DRIVER_MOBILE", bizRecordPageParam.getDriverMobile());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getGoodsName())) {
            queryWrapper.like("br.GOODS_NAME", bizRecordPageParam.getGoodsName());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getGoodsModel())) {
            queryWrapper.like("br.GOODS_MODEL", bizRecordPageParam.getGoodsModel());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getReceiptCompany())) {
            queryWrapper.like("br.RECEIPT_COMPANY", bizRecordPageParam.getReceiptCompany());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getShippingCompany())) {
            queryWrapper.like("br.SHIPPING_COMPANY", bizRecordPageParam.getShippingCompany());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getTransportCompany())){
            queryWrapper.like("br.TRANSPORT_COMPANY",bizRecordPageParam.getTransportCompany());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getIsFlag())){
            queryWrapper.eq("br.weighing_type","1");
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getOrderName())){
            queryWrapper.like("bo.order_name",bizRecordPageParam.getOrderName());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getOrderNumber())){
            queryWrapper.like("bo.order_number",bizRecordPageParam.getOrderNumber());
        }
        if (ObjectUtil.isNotEmpty(bizRecordPageParam.getCustomerName())){
            queryWrapper.like("bc.customer_name",bizRecordPageParam.getCustomerName());
        }
        queryWrapper.eq("br.DELETE_FLAG","NOT_DELETE");
        queryWrapper.orderByDesc("br.create_time");
        return queryWrapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizRecordAddParam bizRecordAddParam) {
        BizRecord bizRecord = BeanUtil.toBean(bizRecordAddParam, BizRecord.class);
        this.save(bizRecord);
    }

    @Transactional
    @Override
    public void push(BizRecordEditParam bizRecordEditParam) {
        if(StringUtils.equals(bizRecordEditParam.getWeighingType(),"1")){
            BizAppointmentRecord appointmentRecord = bizAppointmentRecordService.getById(bizRecordEditParam.getAppointmentId());
            //一次过磅
            BizRecord bizRecord = BeanUtil.toBean(bizRecordEditParam, BizRecord.class);
            bizRecord.setRelationId(bizRecord.getId());
            bizRecord.setId(null);
            bizRecord.setAppointmentUser(appointmentRecord.getCreateUser());
            this.save(bizRecord);

            //修改预约状态
            if(ObjectUtil.isNotNull(appointmentRecord)){
                appointmentRecord.setStatus("6");
                bizAppointmentRecordService.updateById(appointmentRecord);
            }
        }else{
            //二次过磅
            BizRecord bizRecord = this.getOne(new QueryWrapper<BizRecord>().lambda().eq(BizRecord::getRelationId,bizRecordEditParam.getId()));
            if(ObjectUtil.isNull(bizRecord)){
                throw new CommonException("未查询到过磅记录！");
            }
            bizRecordEditParam.setRelationId(bizRecordEditParam.getId());
            bizRecordEditParam.setId(bizRecord.getId());
            BeanUtil.copyProperties(bizRecordEditParam, bizRecord);
            this.updateById(bizRecord);

            //修改预约状态
            BizAppointmentRecord appointmentRecord = bizAppointmentRecordService.getById(bizRecord.getAppointmentId());
            if(ObjectUtil.isNotNull(appointmentRecord)){
                appointmentRecord.setStatus("8");
                bizAppointmentRecordService.updateById(appointmentRecord);
            }

            //修改订单重量
            BizOrder bizOrder = bizOrderService.getById(bizRecord.getOrderId());
            if(ObjectUtil.isNotNull(bizOrder)){
                bizOrder.setNetWeight(bizOrder.getNetWeight().add(bizRecord.getNetWeight()));
                bizOrderService.updateById(bizOrder);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizRecordEditParam bizRecordEditParam) {
        BizRecord bizRecord = this.getOne(new QueryWrapper<BizRecord>().lambda().eq(BizRecord::getRelationId,bizRecordEditParam.getId()));
        if(ObjectUtil.isNull(bizRecord)){
            throw new CommonException("未查询到过磅记录！");
        }
        BeanUtil.copyProperties(bizRecordEditParam, bizRecord);
        this.updateById(bizRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizRecordIdParam> bizRecordIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizRecordIdParamList, BizRecordIdParam::getId));
    }

    @Override
    public BizRecord detail(BizRecordIdParam bizRecordIdParam) {
        return this.queryEntity(bizRecordIdParam.getId());
    }

    @Override
    public BizRecord queryEntity(String id) {
        BizRecord bizRecord = this.getById(id);
        if (ObjectUtil.isEmpty(bizRecord)) {
            throw new CommonException("过磅记录不存在，id值为：{}", id);
        }
        return bizRecord;
    }


    @Override
    public void export(BizRecordPageParam exportParam, HttpServletResponse response) throws IOException {
        File tempFile = null;
        try {
            QueryWrapper<BizRecord> queryWrapper = getQueryWrapper(exportParam);
            String fileName = "过磅记录导出.xlsx";
            //List<BizRecord> recordList = this.baseMapper.selectList(queryWrapper);
            List<BizRecord> recordList = this.getBaseMapper().getPage(queryWrapper);
            if (ObjectUtil.isEmpty(recordList)) {
                throw new CommonException("无数据可导出");
            }
            List<BizRecordExportResult> bizRecordExportResultList = recordList.stream()
                    .map(bizRecord -> {
                        BizRecordExportResult bizRecordExportResult = new BizRecordExportResult();
                        BeanUtil.copyProperties(bizRecord, bizRecordExportResult);
                        bizRecordExportResult.setGrossWeight(bizRecordExportResult.getGrossWeight().stripTrailingZeros());
                        bizRecordExportResult.setTareWeight(bizRecordExportResult.getTareWeight().stripTrailingZeros());
                        bizRecordExportResult.setNetWeight(bizRecordExportResult.getNetWeight().stripTrailingZeros());
                        return bizRecordExportResult;
                    }).collect(Collectors.toList());
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);

            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 16);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 水平垂直居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
            contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
            // 内容背景白色
            contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
            WriteFont contentWriteFont = new WriteFont();

            // 内容字体大小
            contentWriteFont.setFontHeightInPoints((short) 13);
            contentWriteCellStyle.setWriteFont(contentWriteFont);

            //设置边框样式，细实线
            contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
            contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
            contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
            contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);

            // 水平垂直居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle,
                    contentWriteCellStyle);

            // 写excel
            EasyExcel.write(tempFile.getPath(), BizRecordExportResult.class)
                    // 自定义样式
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    // 自动列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    // 机构分组合并单元格
                    //.registerWriteHandler(new CommonExcelCustomMergeStrategy(list.stream().map(BizUserExportResult::getGroupName)
                    //        .collect(Collectors.toList()), 0))
                    // 设置第一行字体
                    .registerWriteHandler(new CellWriteHandler() {
                        @Override
                        public void afterCellDispose(CellWriteHandlerContext context) {
                            WriteCellData<?> cellData = context.getFirstCellData();
                            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                            Integer rowIndex = context.getRowIndex();
                            if (rowIndex == 0) {
                                WriteFont headWriteFont = new WriteFont();
                                headWriteFont.setFontName("宋体");
                                headWriteFont.setBold(true);
                                headWriteFont.setFontHeightInPoints((short) 16);
                                writeCellStyle.setWriteFont(headWriteFont);
                            }
                        }
                    })
                    // 设置表头行高
                    .registerWriteHandler(new AbstractRowHeightStyleStrategy() {
                        @Override
                        protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
                            if (relativeRowIndex == 0) {
                                // 表头第一行
                                row.setHeightInPoints(34);
                            } else {
                                // 表头其他行
                                row.setHeightInPoints(30);
                            }
                        }

                        @Override
                        protected void setContentColumnHeight(Row row, int relativeRowIndex) {
                            // 内容行
                            row.setHeightInPoints(20);
                        }
                    })
                    .sheet("过磅记录导出")
                    .doWrite(bizRecordExportResultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 过磅记录导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        } finally {
            FileUtil.del(tempFile);
        }
    }

    @Override
    public List<Map<String, Object>> sevenDaysList(SevenDaysCountParam sevenDaysCountParam) {
        List<Map<String, Object>> list = new ArrayList<>();
        if (ObjectUtil.isEmpty(sevenDaysCountParam.getStartDay())) {
            // 默认查询当前日期近七日
            sevenDaysCountParam.setStartDay(DateUtil.format(DateUtil.offsetDay(DateUtil.date(), -6), DatePattern.NORM_DATE_PATTERN));
            sevenDaysCountParam.setEndDay(DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN));
        }
        // 查询7天总净重数据
        list.addAll(baseMapper.sevenDaysTotalNetWeight(sevenDaysCountParam));
        // 查询七天总皮重数据
        list.addAll(baseMapper.sevenDaysTotalTareWeight(sevenDaysCountParam));
        // 查询七天总毛重数据
        list.addAll(baseMapper.sevenDaysTotalGrossWeight(sevenDaysCountParam));
        // 查询七天总车子数据
        list.addAll(baseMapper.sevenDaysTotalCar(sevenDaysCountParam));
        return list;
    }

    @Override
    public Map<String, Object> sevenDaysCountWeight(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.sevenDaysCountWeight(sevenDaysCountParam);
    }

    @Override
    public List<CompanyResult> receiptCompanyCountList(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.receiptCompanyCountList(sevenDaysCountParam);
    }

    @Override
    public void receiptCompanyExport(SevenDaysCountParam sevenDaysCountParam, HttpServletResponse response) throws IOException {
        List<CompanyResult> companyResults = baseMapper.receiptCompanyCountList(sevenDaysCountParam);
        List<CompanyResult> resultList = companyResults.stream()
                .map(bizRecord -> {
                    CompanyResult companyResult = new CompanyResult();
                    BeanUtil.copyProperties(bizRecord, companyResult);
                    companyResult.setTotalGrossWeight(companyResult.getTotalGrossWeight().stripTrailingZeros());
                    companyResult.setTotalTareWeight(companyResult.getTotalTareWeight().stripTrailingZeros());
                    companyResult.setTotalNetWeight(companyResult.getTotalNetWeight().stripTrailingZeros());
                    return companyResult;
                }).toList();
        File tempFile = null;
        String fileName = "收货单位统计.xlsx";
        try {
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            EasyExcel.write(tempFile.getPath(), CompanyResult.class).sheet("收货单位统计").doWrite(resultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 收货单位统计导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        }
    }

    @Override
    public List<CompanyResult> shippingCompanyCountList(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.shippingCompanyCountList(sevenDaysCountParam);
    }

    @Override
    public void shippingCompanyExport(SevenDaysCountParam sevenDaysCountParam, HttpServletResponse response) throws IOException {
        List<CompanyResult> companyResults = baseMapper.shippingCompanyCountList(sevenDaysCountParam);
        List<CompanyResult> resultList = companyResults.stream()
                .map(bizRecord -> {
                    CompanyResult companyResult = new CompanyResult();
                    BeanUtil.copyProperties(bizRecord, companyResult);
                    companyResult.setTotalGrossWeight(companyResult.getTotalGrossWeight().stripTrailingZeros());
                    companyResult.setTotalTareWeight(companyResult.getTotalTareWeight().stripTrailingZeros());
                    companyResult.setTotalNetWeight(companyResult.getTotalNetWeight().stripTrailingZeros());
                    return companyResult;
                }).toList();
        File tempFile = null;
        String fileName = "发货单位统计.xlsx";
        try {
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            EasyExcel.write(tempFile.getPath(), CompanyResult.class).sheet("发货单位统计").doWrite(resultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 发货单位统计导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        }
    }

    @Override
    public List<CompanyResult> transportCompanyCountList(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.transportCompanyCountList(sevenDaysCountParam);
    }

    @Override
    public void transportCompanyExport(SevenDaysCountParam sevenDaysCountParam, HttpServletResponse response) throws IOException {
        List<CompanyResult> companyResults = baseMapper.transportCompanyCountList(sevenDaysCountParam);
        List<CompanyResult> resultList = companyResults.stream()
                .map(bizRecord -> {
                    CompanyResult companyResult = new CompanyResult();
                    BeanUtil.copyProperties(bizRecord, companyResult);
                    companyResult.setTotalGrossWeight(companyResult.getTotalGrossWeight().stripTrailingZeros());
                    companyResult.setTotalTareWeight(companyResult.getTotalTareWeight().stripTrailingZeros());
                    companyResult.setTotalNetWeight(companyResult.getTotalNetWeight().stripTrailingZeros());
                    return companyResult;
                }).toList();
        File tempFile = null;
        String fileName = "运输单位统计.xlsx";
        try {
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            EasyExcel.write(tempFile.getPath(), CompanyResult.class).sheet("运输单位统计").doWrite(resultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 运输单位统计导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        }
    }

    @Override
    public List<GoodsResult> goodsCountList(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.goodsCountList(sevenDaysCountParam);
    }

    @Override
    public void goodsCountExport(SevenDaysCountParam sevenDaysCountParam, HttpServletResponse response) throws IOException {
        List<GoodsResult> goodsResults = baseMapper.goodsCountList(sevenDaysCountParam);
        List<GoodsResult> resultList = goodsResults.stream()
                .map(bizRecord -> {
                    GoodsResult goodsResult = new GoodsResult();
                    BeanUtil.copyProperties(bizRecord, goodsResult);
                    goodsResult.setTotalGrossWeight(goodsResult.getTotalGrossWeight().stripTrailingZeros());
                    goodsResult.setTotalTareWeight(goodsResult.getTotalTareWeight().stripTrailingZeros());
                    goodsResult.setTotalNetWeight(goodsResult.getTotalNetWeight().stripTrailingZeros());
                    return goodsResult;
                }).toList();
        File tempFile = null;
        String fileName = "货品统计.xlsx";
        try {
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            EasyExcel.write(tempFile.getPath(), GoodsResult.class).sheet("货品统计").doWrite(resultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 货品统计导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        }
    }

    @Override
    public List<CarResult> carCountList(SevenDaysCountParam sevenDaysCountParam) {
        return baseMapper.carCountList(sevenDaysCountParam);
    }

    @Override
    public void carCountExport(SevenDaysCountParam sevenDaysCountParam, HttpServletResponse response) throws IOException {
        List<CarResult> carResults = baseMapper.carCountList(sevenDaysCountParam);
        List<CarResult> resultList = carResults.stream()
                .map(bizRecord -> {
                    CarResult carResult = new CarResult();
                    BeanUtil.copyProperties(bizRecord, carResult);
                    carResult.setTotalGrossWeight(carResult.getTotalGrossWeight().stripTrailingZeros());
                    carResult.setTotalTareWeight(carResult.getTotalTareWeight().stripTrailingZeros());
                    carResult.setTotalNetWeight(carResult.getTotalNetWeight().stripTrailingZeros());
                    return carResult;
                }).toList();
        File tempFile = null;
        String fileName = "车牌统计.xlsx";
        try {
            // 创建临时文件
            tempFile = FileUtil.file(FileUtil.getTmpDir() + FileUtil.FILE_SEPARATOR + fileName);
            EasyExcel.write(tempFile.getPath(), CarResult.class).sheet("车牌统计").doWrite(resultList);
            CommonDownloadUtil.download(tempFile, response);
        } catch (Exception e) {
            log.error(">>> 车牌统计导出异常：", e);
            CommonResponseUtil.renderError(response, e.getMessage());
        }
    }

    @Transactional
    @Override
    public void confirmRecord(BizRecordIdParam bizRecordIdParam) {
        //设置确认人
        BizRecord bizRecord = this.queryEntity(bizRecordIdParam.getId());
        bizRecord.setConfirmUser(StpLoginUserUtil.getLoginUser().getName());
        this.updateById(bizRecord);

        //预约记录修改成完成装货
        BizAppointmentRecord appointmentRecord = bizAppointmentRecordService.getById(bizRecord.getAppointmentId());
        if(ObjectUtil.isNotNull(appointmentRecord)){
            appointmentRecord.setStatus("7");
            bizAppointmentRecordService.updateById(appointmentRecord);
        }
    }

    @Transactional
    @Override
    public void updateDriverSign(BizRecordEditParam bizRecordEditParam) {
        BizRecord bizRecord = this.queryEntity(bizRecordEditParam.getId());
        if(ObjectUtil.isEmpty(bizRecordEditParam.getDriverSign())){
            throw new CommonException("司机签名不能为空！");
        }
        String driverSign = bizRecordEditParam.getDriverSign();
        if(bizRecordEditParam.getDriverSign().contains(StrUtil.COMMA)) {
            driverSign = StrUtil.split(driverSign, StrUtil.COMMA).get(1);
        }
        String base64 = ImgUtil.toBase64DataUri(ImgUtil.scale(ImgUtil.toImage(driverSign),
                100, 50, null), ImgUtil.IMAGE_TYPE_PNG);

        bizRecord.setDriverSign(base64);
        this.updateById(bizRecord);

        //修改预约记录状态
        BizAppointmentRecord appointmentRecord = bizAppointmentRecordService.getById(bizRecord.getAppointmentId());
        if(ObjectUtil.isNotNull(appointmentRecord)){
            //司机签名后修改为可入场状态
            appointmentRecord.setStatus("9");
            bizAppointmentRecordService.updateById(appointmentRecord);
        }

        //mqtt发送过磅记录id给地磅端，告诉地磅端可打印磅单，抬道闸
        mqttSubscribeClient.publishMessage("hnzydb", bizRecord.getRelationId());

    }
}
