package com.prolog.rdc.tms.app.service.business.impl;

import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.prolog.framework.core.restriction.Order;
import com.prolog.rdc.tms.app.model.dto.business.ScanQRByLoadingBillDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.google.common.collect.Maps;
import com.prolog.common.util.DateUtils;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.exception.PrologException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.product.core.framework.entity.UserEntity;
import com.prolog.product.core.framework.util.PlgFxUsrUtils;
import com.prolog.rdc.tms.app.constant.BussinessConstant;
import com.prolog.rdc.tms.app.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.app.dao.mapper.TmsAppointmentDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsAppointmentHeaderMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsLoadingBillDetailMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsLoadingBillHeaderMapper;
import com.prolog.rdc.tms.app.dao.mapper.TmsShipbillHeaderMapper;
import com.prolog.rdc.tms.app.model.dto.business.FrontPageStatisticalDTO;
import com.prolog.rdc.tms.app.model.dto.business.ScanQRDTO;
import com.prolog.rdc.tms.app.model.entity.TmsAppointmentDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsAppointmentHeaderModel;
import com.prolog.rdc.tms.app.model.entity.TmsLoadingBillDetailModel;
import com.prolog.rdc.tms.app.model.entity.TmsLoadingBillHeaderModel;
import com.prolog.rdc.tms.app.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.app.service.business.FrontPageService;

import cn.hutool.core.util.ObjectUtil;

/**
 * 首页实现层
 * <p>
 * Company: 湖北普罗格科技股份有限公司
 *
 * @author zhangsj
 * @since 2022/7/15 10:57
 */
@Service
public class FrontPageServiceImpl implements FrontPageService {

    @Autowired
    private TmsShipbillHeaderMapper tmsShipbillHeaderMapper;

    @Autowired
    private TmsAppointmentHeaderMapper tmsAppointmentHeaderMapper;

    @Autowired
    private TmsAppointmentDetailMapper tmsAppointmentDetailMapper;

    @Autowired
    private TmsLoadingBillHeaderMapper tmsLoadingBillHeaderMapper;

    @Autowired
    private TmsLoadingBillDetailMapper tmsLoadingBillDetailMapper;

    /**
     * 统计查询
     *
     * @return
     */
    @Override
    public FrontPageStatisticalDTO statisticalData() {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        // 返回数据
        FrontPageStatisticalDTO frontPageStatisticalDTO = new FrontPageStatisticalDTO();
        // 当前时间
        Date date = DateUtils.nowDate();
        // 获取30天前时间
        Date starDate = DateUtils.minu(date, 30, ChronoUnit.DAYS);
        // 添加查询条件
        Criteria criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        Restriction r1 = Restrictions.eq(TmsShipbillHeaderModel::getEnterpriseId, user.getEnterpriseId());
        // 权限控制
        Restriction r2 = null;
        Restriction r3 = null;
        Restriction r4 = null;
        Restriction r5 = null;
        Restriction r6 = null;
        Restriction r7 = null;
        Restriction r20 = null;
        Restriction r21 = null;
        Restriction r22 = null;
        Restriction r29 = null;
        // 判断账号类型
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            // 自有账号
            // 拆单状态 0未拆单
            Restriction r30 = Restrictions.eq("splitOrderStatus", DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            // 承运商拆单类型 1未拆单
            Restriction r31 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_UN);
            Restriction r32 = Restrictions.and(r30, r31);
            // 承运商拆单类型 2拆分主单
            Restriction r33 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_SPLIT_MASTER);
            // 承运商拆单类型 2中转主单
            Restriction r34 = Restrictions.eq("carrierSplitOrderType", DataDictionaryConstant.CARRIER_SPLIT_ORDER_TYPE_TRANSIT_MASTER);
            r29 = Restrictions.or(r32, r33, r34);
            // 判断是否为部门权限
            if (user.getOwnedAllDataAuthFlag().equals(BussinessConstant.USER_DEPARTMENT_AUTH_Y)) {
                r2 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
            } else {
                r2 = Restrictions.in("departmentId", user.getDepts().stream().toArray(String[]::new));
                // 其它权限
                // 货主
                r3 = Restrictions.in("cargoOwnerId", user.getConsignors().toArray());
                // 客户
                r4 = Restrictions.in("consigneeUnitId", user.getCustomers().toArray());
                // 供应商
                r5 = Restrictions.in("consigneeUnitId", user.getSuppliers().toArray());
                // 仓库
                r6 = Restrictions.in("consigneeUnitId", user.getWarehouses().toArray());
                // 客户
                r20 = Restrictions.in("shipperUnitId", user.getCustomers().toArray());
                // 供应商
                r21 = Restrictions.in("shipperUnitId", user.getSuppliers().toArray());
                // 仓库
                r22 = Restrictions.in("shipperUnitId", user.getWarehouses().toArray());

                r7 = Restrictions.or(r4, r5, r6, r20, r21, r22);
            }
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            // 承运商账号
            r2 = Restrictions.eq("carrierId", Long.valueOf(user.getLoginUserCompanyInfo().getId()));
            r29 = Restrictions.eq("carrierSplitOrderStatus", DataDictionaryConstant.CARRIER_SPLIT_ORDER_STATUS_UN);

        } else {
            throw new BizException("当前人员没有操作权限！");
        }
        Restriction rBasic = Restrictions.and(r1, r2, r3, r7, r29);
        criteria.setRestriction(rBasic);
        // 30天内所有运单数量
        Long allShipbillNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);
        // 待提交数量
        Long waitSubmitNum = 0L;
        // 待审核数量
        Long pendingReviewNum = 0L;
        // 待调度数量
        Long pendingDispatchNum = 0L;
        // 待提货数量
        Long waitPickUpNum = 0L;
        // 待送达数量
        Long waitDeliveredNum = 0L;
        // 待理货数量
        Long waitForArrangeGoodsNum = 0L;
        // 预约待审核数量
        Long planRevieNum = 0L;
        // 已完成数量
        Long completedNum = 0L;
        // 获取预约单数据
        Criteria criteriaAppointmentHeader = Criteria.forClass(TmsAppointmentHeaderModel.class);
        Restriction r10 = Restrictions.eq(TmsAppointmentHeaderModel::getStatus, DataDictionaryConstant.APPOINTMENT_STATUS_DSH);
        criteriaAppointmentHeader.setRestriction(Restrictions.and(r1, r10));
        List<TmsAppointmentHeaderModel> tmsAppointmentHeaderModels = tmsAppointmentHeaderMapper.findByCriteria(criteriaAppointmentHeader);
        // 获取预约待审核数据
        Criteria criteriaAppointmentDetail = Criteria.forClass(TmsAppointmentDetailModel.class);
        r10 = Restrictions.in(TmsAppointmentDetailModel::getAppointmentId, tmsAppointmentHeaderModels.stream().map(TmsAppointmentHeaderModel::getAppointmentId).collect(Collectors.toList()).toArray());
        Restriction r11 = Restrictions.eq(TmsAppointmentDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_APP_ING);
        criteriaAppointmentDetail.setRestriction(Restrictions.and(r1, r2, r3, r7,  r10, r11));
        planRevieNum = tmsAppointmentDetailMapper.findCountByCriteria(criteriaAppointmentDetail);
        if (user.getUserType().equals(BussinessConstant.USER_TYPE_ZY)) {
            Restriction rStatus = Restrictions.in(TmsShipbillHeaderModel::getStatus, Lists.newArrayList(DataDictionaryConstant.SHIPBILL_STATUS_YTH, DataDictionaryConstant.SHIPBILL_STATUS_CSH, DataDictionaryConstant.SHIPBILL_STATUS_DSH));
            criteria.setRestriction(Restrictions.and(rBasic, rStatus));
            waitSubmitNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

            rStatus = Restrictions.in(TmsShipbillHeaderModel::getStatus, Lists.newArrayList(DataDictionaryConstant.SHIPBILL_STATUS_YTJ, DataDictionaryConstant.SHIPBILL_STATUS_WZ, DataDictionaryConstant.SHIPBILL_STATUS_WS));
            criteria.setRestriction(Restrictions.and(rBasic, rStatus));
            pendingReviewNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

            Restriction r101 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_REVIEW);
            Restriction r102 = Restrictions.eq(TmsShipbillHeaderModel::getSplitOrderStatus, DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
            Restriction r103 = Restrictions.eq(TmsShipbillHeaderModel::getDeliveryMethodType, DataDictionaryConstant.DELIVERY_METHOD_TYPE_SEND);
            criteria.setRestriction(Restrictions.and(rBasic, r101, r102, r103));
            pendingDispatchNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);
        } else if (user.getUserType().equals(BussinessConstant.USER_TYPE_CYS)) {
            Restriction r101 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_DISPATCH_CHECK);
            Restriction r102 = Restrictions.in(TmsShipbillHeaderModel::getCarrierShipbillStatus, Lists.newArrayList(DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_RECEIVED, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_ROLLBACK, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_WAIT_RECEIVE));
            criteria.setRestriction(Restrictions.and(rBasic, r101, r102));
            waitSubmitNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

            r102 = Restrictions.eq(TmsShipbillHeaderModel::getCarrierShipbillStatus, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_COMMIT);
            criteria.setRestriction(Restrictions.and(rBasic, r101, r102));
            pendingReviewNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

            r102 = Restrictions.eq(TmsShipbillHeaderModel::getCarrierShipbillStatus, DataDictionaryConstant.CARRIER_SHIPBILL_STATUS_AUDITED);
            criteria.setRestriction(Restrictions.and(rBasic, r101, r102));
            pendingDispatchNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);
        }
        Restriction r101 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_QY);
        criteria.setRestriction(Restrictions.and(rBasic, r101));
        waitPickUpNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

        Criteria criteria2 = Criteria.forClass(TmsLoadingBillDetailModel.class);
        r101 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_SD);
        criteria2.setRestriction(Restrictions.and(rBasic, r101));
        waitDeliveredNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria2);

        r101 = Restrictions.in(TmsShipbillHeaderModel::getStatus, Lists.newArrayList(DataDictionaryConstant.SHIPBILL_STATUS_LH_START, DataDictionaryConstant.SHIPBILL_STATUS_LH_FINISH));
        Restriction r102 = Restrictions.isNotNull(TmsShipbillHeaderModel::getAppTallyStatus);
        criteria.setRestriction(Restrictions.and(rBasic, r101, r102));
        waitForArrangeGoodsNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

        r101 = Restrictions.eq(TmsShipbillHeaderModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_END);
        r102 = Restrictions.eq(TmsShipbillHeaderModel::getSplitOrderStatus, DataDictionaryConstant.SPLIT_ORDER_STATUS_UN);
        criteria.setRestriction(Restrictions.and(rBasic, r101, r102));
        completedNum = tmsShipbillHeaderMapper.findCountByCriteria(criteria);

        frontPageStatisticalDTO.setWaitSubmitNum(waitSubmitNum);
        frontPageStatisticalDTO.setPendingReviewNum(pendingReviewNum);
        frontPageStatisticalDTO.setPendingDispatchNum(pendingDispatchNum);
        frontPageStatisticalDTO.setWaitPickUpNum(waitPickUpNum);
        frontPageStatisticalDTO.setWaitDeliveredNum(waitDeliveredNum);
        frontPageStatisticalDTO.setWaitForArrangeGoodsNum(waitForArrangeGoodsNum);
        frontPageStatisticalDTO.setCompletedNum(completedNum);
        frontPageStatisticalDTO.setAllShipbillNum(allShipbillNum);
        frontPageStatisticalDTO.setPlanRevieNum(planRevieNum);
        return frontPageStatisticalDTO;
    }

    /**
     * 首页扫二维码(运单二维码版)判断是否需要走预约流程
     *
     * @return
     */
    @Override
    public ScanQRDTO scanQR(String shipbillNo) throws Exception {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");

        ScanQRDTO dto = new ScanQRDTO();

        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("shipbillNo", shipbillNo);
        List<TmsShipbillHeaderModel> tmsShipbillHeaders = tmsShipbillHeaderMapper.findByMap(queryMap, TmsShipbillHeaderModel.class);
        if (ToolKits.isNotEmpty(tmsShipbillHeaders) && tmsShipbillHeaders.size() > 0) {
            Assert.isTrue(tmsShipbillHeaders.size() == 1, "运单【" + shipbillNo + "】重复");
            TmsShipbillHeaderModel tmsShipbillHeader = tmsShipbillHeaders.get(0);

            if (ToolKits.isNotEmpty(tmsShipbillHeader.getFlowConfig()) && tmsShipbillHeader.getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT)) {
                // 需要走预约流程
                queryMap.put("shipbillId", tmsShipbillHeaders.get(0).getShipbillId());
                List<TmsAppointmentDetailModel> tmsAppointmentDetails = tmsAppointmentDetailMapper.findByMap(queryMap, TmsAppointmentDetailModel.class);
                if (ToolKits.isNotEmpty(tmsAppointmentDetails) && tmsAppointmentDetails.size() > 0 &&
                        tmsAppointmentDetails.get(0).getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT_TN_CN)) {
                    TmsAppointmentDetailModel tmsAppointmentDetail = tmsAppointmentDetails.get(0);
                    TmsAppointmentHeaderModel tmsAppointmentHeader = tmsAppointmentHeaderMapper.findById(tmsAppointmentDetail.getAppointmentId(), TmsAppointmentHeaderModel.class);
                    if (ToolKits.isNotEmpty(tmsAppointmentHeader)) {
                        dto.setBranchId(tmsAppointmentHeader.getBranchId());
                        dto.setBranchCode(tmsAppointmentHeader.getBranchCode());
                        dto.setBranchName(tmsAppointmentHeader.getBranchName());
                        dto.setDriverId(tmsAppointmentHeader.getDriverId());
                        dto.setDriverCode(tmsAppointmentHeader.getDriverCode());
                        dto.setDriverName(tmsAppointmentHeader.getDriverName());
                        dto.setBranchAddress(tmsAppointmentHeader.getBranchAddress());
                        dto.setDriverPhoneNumber(tmsAppointmentHeader.getDriverPhoneNumber());
                        dto.setVehiclePlateNumber(tmsAppointmentHeader.getVehiclePlateNumber());
                        dto.setReserveNumber(tmsAppointmentHeader.getReserveNumber());
                        dto.setFlag("1");
                        return dto;
                    } else {
                        throw new PrologException("运单【" + shipbillNo + "】对应预约单不存在");
                    }
                } else {
                    if (ObjectUtil.equal(tmsShipbillHeader.getShipperType(), DataDictionaryConstant.SHIPPER_TYPE_CK)) {
                        Boolean b = false;
                        List<Long> warehouses = user.getWarehouses();
                        if (ToolKits.isEmpty(warehouses) || warehouses.size() == 0) {
                            throw new PrologException("您无权对当前运单进行取号！");
                        }
                        for (Long branchId : warehouses) {
                            if (ObjectUtil.equal(branchId, tmsShipbillHeader.getShipperId())) {
                                b = true;
                                break;
                            }
                        }
                        if (b) {
                            dto.setBranchId(tmsShipbillHeader.getShipperId());
                            dto.setBranchCode(tmsShipbillHeader.getShipperCode());
                            dto.setBranchName(tmsShipbillHeader.getShipperName());
                            dto.setBranchAddress(tmsShipbillHeader.getShipperAddress());

                            // 查询当前运单是否存在关联的装车单
                            Map<String, Object> queryMap2 = Maps.newHashMap();
                            // lhb 20220827  start
                            Criteria criteriaLoadingBillDetail = Criteria.forClass(TmsLoadingBillDetailModel.class);
                            Restriction r1 = Restrictions.eq("shipbillId", tmsShipbillHeader.getShipbillId());
                            Restriction r2 = Restrictions.eq("enterpriseId", user.getEnterpriseId());
                            Restriction r3 = Restrictions.eq(TmsLoadingBillDetailModel::getStatus, DataDictionaryConstant.SHIPBILL_STATUS_PENDING_APP);
                            criteriaLoadingBillDetail.setRestriction(Restrictions.and(r1, r2, r3));
                            criteriaLoadingBillDetail.setOrder(Order.newInstance().desc(TmsLoadingBillDetailModel::getCreatetime));
                            List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModels = tmsLoadingBillDetailMapper.findByCriteria(criteriaLoadingBillDetail);
                            ToolKits.isParamNull(tmsLoadingBillDetailModels, "未找到对应的调度单明细");

                            if (ToolKits.isNotEmpty(tmsLoadingBillDetailModels) && tmsLoadingBillDetailModels.size() > 0) {
                                // lhb 20220827  end
                                TmsLoadingBillHeaderModel tmsLoadingBillHeader = tmsLoadingBillHeaderMapper.findById(tmsLoadingBillDetailModels.get(0).getLoadingBillId(), TmsLoadingBillHeaderModel.class);
                                if (ToolKits.isNotEmpty(tmsLoadingBillHeader)) {
                                    dto.setDriverId(tmsLoadingBillHeader.getDriverId());
                                    dto.setDriverCode(tmsLoadingBillHeader.getDriverCode());
                                    dto.setDriverName(tmsLoadingBillHeader.getDriverName());
                                    dto.setDriverPhoneNumber(tmsLoadingBillHeader.getDriverPhoneNumber());
                                    dto.setVehiclePlateNumber(tmsLoadingBillHeader.getVehiclePlateNumber());
                                }
                            }
                            dto.setFlag("2");
                            return dto;
                        } else {
                            throw new PrologException("您无权对当前运单进行取号！");
                        }
                    } else {
                        throw new PrologException("只有运单的发货方为仓库的运单才能取号！");
                    }
                }
            } else {// 无需走预约流程,跳转至运单管理界面
                dto.setFlag("3");
                return dto;
            }
        } else {
            throw new PrologException("运单号【" + shipbillNo + "】在系统中不存在");
        }
    }

    @Override
    public ScanQRByLoadingBillDTO scanQRByLoadingBill(String loadingBillNo) {
        UserEntity user = PlgFxUsrUtils.getUserEntity();
        ToolKits.isParamNull(user, "当前人员没有操作权限");
        ScanQRByLoadingBillDTO scanQRDTO = new ScanQRByLoadingBillDTO();
        scanQRDTO.setLoadingBillNo(loadingBillNo);
        scanQRDTO.setLoadingBillId(loadingBillNo);
        TmsLoadingBillHeaderModel tmsLoadingBillHeaderModel =
                tmsLoadingBillHeaderMapper.findById(loadingBillNo, TmsLoadingBillHeaderModel.class);

        Criteria criteria = Criteria.forClass(TmsLoadingBillDetailModel.class);
        Restriction r1 = Restrictions.eq(TmsLoadingBillDetailModel::getLoadingBillId, loadingBillNo);
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsLoadingBillDetailModel> tmsLoadingBillDetailModelList = tmsLoadingBillDetailMapper.findByCriteria(criteria);
        List<String> shipBillIdList = tmsLoadingBillDetailModelList.stream().map(TmsLoadingBillDetailModel::getShipbillId).collect(Collectors.toList());
        criteria = Criteria.forClass(TmsShipbillHeaderModel.class);
        r1 = Restrictions.in(TmsShipbillHeaderModel::getShipbillId, shipBillIdList.toArray());
        criteria.setRestriction(Restrictions.and(r1));
        List<TmsShipbillHeaderModel> tmsShipbillHeaderModelList = tmsShipbillHeaderMapper.findByCriteria(criteria);
        if (tmsShipbillHeaderModelList.stream().anyMatch(tmsShipbillHeaderModel -> {
            String flowConfig = StrUtil.EMPTY;
            if (BussinessConstant.USER_TYPE_ZY.equals(user.getUserType())) {
                flowConfig = tmsShipbillHeaderModel.getFlowConfig();
            } else if (BussinessConstant.USER_TYPE_CYS.equals(user.getUserType())) {
                flowConfig = tmsShipbillHeaderModel.getCarrierFlowConfig();
            }
            return flowConfig.contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT);
        })) {
            if (ObjectUtil.isNull(tmsLoadingBillHeaderModel)) {
                throw new BizException("派车单号" + loadingBillNo + "不存在");
            }
            criteria = Criteria.forClass(TmsAppointmentDetailModel.class);
            r1 = Restrictions.eq(TmsAppointmentDetailModel::getLoadingBillId, loadingBillNo);
            criteria.setRestriction(Restrictions.and(r1));
            List<TmsAppointmentDetailModel> tmsAppointmentDetailModelList = tmsAppointmentDetailMapper.findByCriteria(criteria);
            boolean hasAppoint = false;
            TmsAppointmentHeaderModel headerModel = null;
            if (CollectionUtil.isNotEmpty(tmsAppointmentDetailModelList) &&
                    tmsAppointmentDetailModelList.get(0).getFlowConfig().contains(DataDictionaryConstant.FLOW_CONFIG_APPOINTMENT_TN_CN)) {
                headerModel = tmsAppointmentHeaderMapper.findById(
                        tmsAppointmentDetailModelList.get(0).getAppointmentId(), TmsAppointmentHeaderModel.class);
                if (DataDictionaryConstant.APPOINTMENT_STATUS_QX.equals(headerModel.getStatus())) {
                    hasAppoint = false;
                } else {
                    hasAppoint = true;
                }
            }
            if (hasAppoint) {
                scanQRDTO.setBranchId(headerModel.getBranchId());
                scanQRDTO.setBranchCode(headerModel.getBranchCode());
                scanQRDTO.setBranchName(headerModel.getBranchName());
                scanQRDTO.setDriverId(headerModel.getDriverId());
                scanQRDTO.setDriverCode(headerModel.getDriverCode());
                scanQRDTO.setDriverName(headerModel.getDriverName());
                scanQRDTO.setBranchAddress(headerModel.getBranchAddress());
                scanQRDTO.setDriverPhoneNumber(headerModel.getDriverPhoneNumber());
                scanQRDTO.setVehiclePlateNumber(headerModel.getVehiclePlateNumber());
                scanQRDTO.setReserveNumber(headerModel.getReserveNumber());
                scanQRDTO.setFlag("1");
            } else {
                if (tmsLoadingBillHeaderModel.getPickupStations() != 1L) {
                    throw new BizException("派车单号" + loadingBillNo + "有多个提货站点，不支持预约！");
                }
                if (!DataDictionaryConstant.LOADING_BILL_STATUS_YSH.equals(tmsLoadingBillHeaderModel.getStatus())) {
                    throw new BizException("派车单号" + loadingBillNo + "不为审核状态，不支持预约！");
                }
                if (tmsShipbillHeaderModelList.stream().noneMatch(tmsShipbillHeaderModel ->
                        DataDictionaryConstant.SHIPPER_TYPE_CK.equals(tmsShipbillHeaderModel.getShipperType()))) {
                    throw new BizException("只有发货方为仓库的派车单支持取号！");
                }
                if (tmsShipbillHeaderModelList.stream().anyMatch(tmsShipbillHeaderModel ->
                        !user.getWarehouses().contains(tmsShipbillHeaderModel.getShipperId()))) {
                    throw new BizException("您无权对当前派车单取号！");
                }
                scanQRDTO.setDriverId(tmsLoadingBillHeaderModel.getDriverId());
                scanQRDTO.setDriverCode(tmsLoadingBillHeaderModel.getDriverCode());
                scanQRDTO.setDriverName(tmsLoadingBillHeaderModel.getDriverName());
                scanQRDTO.setDriverPhoneNumber(tmsLoadingBillHeaderModel.getDriverPhoneNumber());
                scanQRDTO.setVehiclePlateNumber(tmsLoadingBillHeaderModel.getVehiclePlateNumber());
                scanQRDTO.setShipBillNums(tmsLoadingBillHeaderModel.getShipbillNumber());
                scanQRDTO.setShipBillPackages(tmsLoadingBillHeaderModel.getActualTotalPcs());
                TmsLoadingBillDetailModel tmsLoadingBillDetailModel = tmsLoadingBillDetailModelList.get(0);
                scanQRDTO.setShipperType(tmsLoadingBillDetailModel.getShipperType());
                scanQRDTO.setShipperUnitId(tmsLoadingBillDetailModel.getShipperUnitId());
                scanQRDTO.setShipperUnitCode(tmsLoadingBillDetailModel.getShipperUnitCode());
                scanQRDTO.setShipperUnitName(tmsLoadingBillDetailModel.getShipperUnitName());
                scanQRDTO.setShipperId(tmsLoadingBillDetailModel.getShipperId());
                scanQRDTO.setShipperCode(tmsLoadingBillDetailModel.getShipperCode());
                scanQRDTO.setShipperName(tmsLoadingBillDetailModel.getShipperName());
                scanQRDTO.setShipperContact(tmsLoadingBillDetailModel.getShipperContact());
                scanQRDTO.setShipperPhoneNumber(tmsLoadingBillDetailModel.getShipperPhoneNumber());
                scanQRDTO.setShipperLandlineNumber(tmsLoadingBillDetailModel.getShipperLandlineNumber());
                scanQRDTO.setShipperEmail(tmsLoadingBillDetailModel.getShipperEmail());
                scanQRDTO.setShipperRelatedPhoneNumber(tmsLoadingBillDetailModel.getShipperRelatedPhoneNumber());
                scanQRDTO.setShipperProvince(tmsLoadingBillDetailModel.getShipperProvince());
                scanQRDTO.setShipperProvinceName(tmsLoadingBillDetailModel.getShipperProvinceName());
                scanQRDTO.setShipperCity(tmsLoadingBillDetailModel.getShipperCity());
                scanQRDTO.setShipperCityName(tmsLoadingBillDetailModel.getShipperCityName());
                scanQRDTO.setShipperDistrict(tmsLoadingBillDetailModel.getShipperDistrict());
                scanQRDTO.setShipperDistrictName(tmsLoadingBillDetailModel.getShipperDistrictName());
                scanQRDTO.setShipperAddress(tmsLoadingBillDetailModel.getShipperAddress());
                scanQRDTO.setShipperLongitude(tmsLoadingBillDetailModel.getShipperLongitude());
                scanQRDTO.setShipperLatitude(tmsLoadingBillDetailModel.getShipperLatitude());
                scanQRDTO.setEstimatedPickupStartTime(tmsLoadingBillDetailModel.getEstimatedPickupStartTime());
                scanQRDTO.setEstimatedPickupEndTime(tmsLoadingBillDetailModel.getEstimatedPickupEndTime());
                scanQRDTO.setEstimatedDeliveryStartTime(tmsLoadingBillDetailModel.getEstimatedDeliveryStartTime());
                scanQRDTO.setEstimatedDeliveryEndTime(tmsLoadingBillDetailModel.getEstimatedDeliveryEndTime());
                scanQRDTO.setFlag("2");
            }
        } else {
            scanQRDTO.setFlag("3");
        }
        return scanQRDTO;
    }

}
