package com.cpxt.biz.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cpxt.biz.domain.*;
import com.cpxt.biz.domain.vo.BizOrderVo;
import com.cpxt.biz.domain.vo.BizOrderVoCustomer;
import com.cpxt.biz.mapper.*;
import com.cpxt.common.core.domain.entity.SysUser;
import com.cpxt.common.exception.ServiceException;
import com.cpxt.common.utils.Helper;
import com.cpxt.common.utils.PositionUtil;
import com.cpxt.common.utils.SecurityUtils;
import com.cpxt.common.utils.StringUtils;
import com.cpxt.system.mapper.SysUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cpxt.biz.service.IBizOrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 订单Service业务层处理
 *
 * @author YIN
 * @date 2024-12-16
 */
@Service
public class BizOrderServiceImpl implements IBizOrderService {

    private static final Logger log = LoggerFactory.getLogger(BizOrderServiceImpl.class);

    @Autowired
    protected Validator validator;

    @Autowired
    private BizOrderMapper bizOrderMapper;

    @Autowired
    private BizOrderSubMapper bizOrderSubMapper;

    @Autowired
    private BizCustomerMapper bizCustomerMapper;

    @Autowired
    private BizCustomerRouteMapper bizCustomerRouteMapper;

    @Autowired
    private BizCustomerWarehouseMapper bizCustomerWarehouseMapper;

    @Autowired
    private BizCustomerShopMapper bizCustomerShopMapper;

    @Autowired
    private BizCarMapper bizCarMapper;

    @Autowired
    private BizDriverMapper bizDriverMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public BizOrder selectBizOrderById(Long id) {
        return bizOrderMapper.selectById(id);
    }

    /**
     * 查询订单列表（分页）
     *
     * @param bizOrder 订单
     * @return 订单
     */
    @Override
    public Page<BizOrder> selectBizOrderPage(BizOrder bizOrder, int pageNum, int pageSize) {
        LambdaQueryWrapper<BizOrder> queryWrapper = buildQueryWrapper(bizOrder);
        return bizOrderMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

    /**
     * 查询订单列表（主驾司机或者副驾司机是当前用户 - 分页）
     *
     * @return 订单
     */
    @Override
    public Page<BizOrder> selectBizOrderPageByDriver(String orderStatus ,int pageNum, int pageSize) {
        BizDriver bizDriver = bizDriverMapper.selectByUserId(SecurityUtils.getUserId());
        LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizOrder::getStatus,1);
        queryWrapper.eq(BizOrder::getOrderStatus,orderStatus);
        queryWrapper.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().like(BizOrder::getCopilotId,bizDriver.getId()));
        queryWrapper.orderByDesc(BizOrder::getCreateTime);
        return bizOrderMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

    /**
     * 查询订单列表
     *
     * @param bizOrder 订单
     * @return 订单
     */
    @Override
    public List<BizOrder> selectBizOrderList(BizOrder bizOrder) {
        LambdaQueryWrapper<BizOrder> queryWrapper = buildQueryWrapper(bizOrder);
        return bizOrderMapper.selectList(queryWrapper);
    }

    private LambdaQueryWrapper<BizOrder> buildQueryWrapper(BizOrder bizOrder) {
        Long userId = SecurityUtils.getUserId();
        SysUser user = sysUserMapper.selectUserById(userId);
        BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(user.getUserName());

        LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
        if (user.getUserType().equals("2") && bizCustomer != null){
            queryWrapper.eq(BizOrder::getCustomerId,bizCustomer.getId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getOrderSn())) {
            queryWrapper.like(BizOrder::getOrderSn, bizOrder.getOrderSn());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getOrderStatus())) {
            queryWrapper.eq(BizOrder::getOrderStatus, bizOrder.getOrderStatus());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getOrderType())) {
            queryWrapper.eq(BizOrder::getOrderType, bizOrder.getOrderType());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCustomerId())) {
            queryWrapper.eq(BizOrder::getCustomerId, bizOrder.getCustomerId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCustomerName())) {
            queryWrapper.like(BizOrder::getCustomerName, bizOrder.getCustomerName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getRouteId())) {
            queryWrapper.eq(BizOrder::getRouteId, bizOrder.getRouteId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getRouteName())) {
            queryWrapper.like(BizOrder::getRouteName, bizOrder.getRouteName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getWarehouseId())) {
            queryWrapper.eq(BizOrder::getWarehouseId, bizOrder.getWarehouseId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getWarehouseName())) {
            queryWrapper.like(BizOrder::getWarehouseName, bizOrder.getWarehouseName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getShopId())) {
            queryWrapper.eq(BizOrder::getShopId, bizOrder.getShopId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getShopName())) {
            queryWrapper.like(BizOrder::getShopName, bizOrder.getShopName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCarId())) {
            queryWrapper.eq(BizOrder::getCarId, bizOrder.getCarId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCarNo())) {
            queryWrapper.like(BizOrder::getCarNo, bizOrder.getCarNo());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getDriverId())) {
            queryWrapper.eq(BizOrder::getDriverId, bizOrder.getDriverId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getDriverName())) {
            queryWrapper.like(BizOrder::getDriverName, bizOrder.getDriverName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCopilotId())) {
            queryWrapper.eq(BizOrder::getCopilotId, bizOrder.getCopilotId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCopilotName())) {
            queryWrapper.like(BizOrder::getCopilotName, bizOrder.getCopilotName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getSenderName())) {
            queryWrapper.and(wq -> wq.like(BizOrder::getSenderName, bizOrder.getSenderName()).or().like(BizOrder::getSenderPhone,bizOrder.getSenderName()).or().like(BizOrder::getSenderAddress,bizOrder.getSenderName()).or().like(BizOrder::getSenderLinkman,bizOrder.getSenderName()));
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverName())) {
            queryWrapper.and(wq -> wq.like(BizOrder::getReceiverName, bizOrder.getReceiverName()).or().like(BizOrder::getReceiverPhone,bizOrder.getReceiverName()).or().like(BizOrder::getReceiverAddress,bizOrder.getReceiverName()).or().like(BizOrder::getReceiverLinkman,bizOrder.getReceiverName()));
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverLinkman())) {
            queryWrapper.like(BizOrder::getReceiverLinkman, bizOrder.getReceiverLinkman());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverPhone())) {
            queryWrapper.like(BizOrder::getReceiverPhone, bizOrder.getReceiverPhone());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverAddress())) {
            queryWrapper.like(BizOrder::getReceiverAddress, bizOrder.getReceiverAddress());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverLng())) {
            queryWrapper.eq(BizOrder::getReceiverLng, bizOrder.getReceiverLng());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverLat())) {
            queryWrapper.eq(BizOrder::getReceiverLat, bizOrder.getReceiverLat());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getReceiverCompany())) {
            queryWrapper.like(BizOrder::getReceiverCompany, bizOrder.getReceiverCompany());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getGoodsType())) {
            queryWrapper.eq(BizOrder::getGoodsType, bizOrder.getGoodsType());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getGoodsName())) {
            queryWrapper.like(BizOrder::getGoodsName, bizOrder.getGoodsName());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getWeight())) {
            queryWrapper.eq(BizOrder::getWeight, bizOrder.getWeight());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getVolume())) {
            queryWrapper.eq(BizOrder::getVolume, bizOrder.getVolume());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getLength())) {
            queryWrapper.eq(BizOrder::getLength, bizOrder.getLength());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getWidth())) {
            queryWrapper.eq(BizOrder::getWidth, bizOrder.getWidth());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getHeight())) {
            queryWrapper.eq(BizOrder::getHeight, bizOrder.getHeight());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getTotalQuantity())) {
            queryWrapper.eq(BizOrder::getTotalQuantity, bizOrder.getTotalQuantity());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getInsured())) {
            queryWrapper.eq(BizOrder::getInsured, bizOrder.getInsured());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getInsuredMoney())) {
            queryWrapper.eq(BizOrder::getInsuredMoney, bizOrder.getInsuredMoney());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getInsuredFee())) {
            queryWrapper.eq(BizOrder::getInsuredFee, bizOrder.getInsuredFee());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getOrderFee())) {
            queryWrapper.eq(BizOrder::getOrderFee, bizOrder.getOrderFee());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getIsCancel())) {
            queryWrapper.eq(BizOrder::getIsCancel, bizOrder.getIsCancel());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCancelReason())) {
            queryWrapper.like(BizOrder::getCancelReason, bizOrder.getCancelReason());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getCancelTime())) {
            queryWrapper.like(BizOrder::getCancelTime, bizOrder.getCancelTime());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getPayType())) {
            queryWrapper.eq(BizOrder::getPayType, bizOrder.getPayType());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getPayMode())) {
            queryWrapper.eq(BizOrder::getPayMode, bizOrder.getPayMode());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getPayId())) {
            queryWrapper.eq(BizOrder::getPayId, bizOrder.getPayId());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getPayStatus())) {
            queryWrapper.eq(BizOrder::getPayStatus, bizOrder.getPayStatus());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getPayTime())) {
            queryWrapper.like(BizOrder::getPayTime, bizOrder.getPayTime());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getStatus())) {
            queryWrapper.eq(BizOrder::getStatus, bizOrder.getStatus());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getStartTime())) {
            queryWrapper.like(BizOrder::getStartTime, bizOrder.getStartTime());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getArriveTime())) {
            queryWrapper.like(BizOrder::getArriveTime, bizOrder.getArriveTime());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getArriveRemark())) {
            queryWrapper.like(BizOrder::getArriveRemark, bizOrder.getArriveRemark());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getArriveLng())) {
            queryWrapper.eq(BizOrder::getArriveLng, bizOrder.getArriveLng());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getArriveLat())) {
            queryWrapper.eq(BizOrder::getArriveLat, bizOrder.getArriveLat());
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getBeginTime())){
            String beginTime = bizOrder.getBeginTime() + " 00:00:00";
            queryWrapper.ge(BizOrder::getCreateTime,beginTime);
        }
        if (ObjectUtil.isNotEmpty(bizOrder.getEndTime())){
            String endTime = bizOrder.getEndTime() + " 23:59:59";
            queryWrapper.le(BizOrder::getCreateTime,endTime);
        }
        queryWrapper.orderByDesc(BizOrder::getCreateTime);
        queryWrapper.eq(BizOrder::getStatus, 1);
        return queryWrapper;
    }

    /**
     * 新增订单
     *
     * @param bizOrder 订单
     * @return 结果
     */
    @Override
    public int insertBizOrder(BizOrder bizOrder) {
        Long customerId = bizOrder.getCustomerId(); // 客户id
        if (ObjectUtil.isEmpty(customerId)) {
            String username = SecurityUtils.getUsername();
            BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(username);
            customerId = bizCustomer.getId();
        }
        Long routeId = bizOrder.getRouteId(); // 路线id
        Long warehouseId = bizOrder.getWarehouseId(); // 仓库id
        Long shopId = bizOrder.getShopId(); // 店铺id
        Long carId = bizOrder.getCarId(); // 配送车辆id
        Long driverId = bizOrder.getDriverId(); // 配送司机id
        Long copilotId = bizOrder.getCopilotId(); // 副驾司机id
        BigDecimal length = bizOrder.getLength();
        BigDecimal width = bizOrder.getWidth();
        BigDecimal height = bizOrder.getHeight();
        if (ObjectUtil.isNotEmpty(length) && ObjectUtil.isNotEmpty(width) && ObjectUtil.isNotEmpty(height)){
            bizOrder.setVolume(length.multiply(width).multiply(height));
        }

        setBizOrderSn(bizOrder); // 填充订单编号

        bizOrder.setCustomerName(bizCustomerMapper.selectById(customerId).getName());
        if (ObjectUtil.isNotEmpty(routeId)) bizOrder.setRouteName(bizCustomerRouteMapper.selectById(routeId).getName());
        if (ObjectUtil.isNotEmpty(warehouseId))
            bizOrder.setWarehouseName(bizCustomerWarehouseMapper.selectById(warehouseId).getName());
        if (ObjectUtil.isNotEmpty(shopId)) bizOrder.setShopName(bizCustomerShopMapper.selectById(shopId).getName());
        if (ObjectUtil.isNotEmpty(carId)) bizOrder.setCarNo(bizCarMapper.selectById(carId).getCarNo());
        if (ObjectUtil.isNotEmpty(driverId)) bizOrder.setDriverName(bizDriverMapper.selectById(driverId).getName());
        if (ObjectUtil.isNotEmpty(copilotId)) bizOrder.setCopilotName(bizDriverMapper.selectById(copilotId).getName());

        // 计算直线距离
        if (ObjectUtil.isNotEmpty(bizOrder.getSenderLng()) && ObjectUtil.isNotEmpty(bizOrder.getSenderLat()) && ObjectUtil.isNotEmpty(bizOrder.getReceiverLng()) && ObjectUtil.isNotEmpty(bizOrder.getReceiverLat())){
            double lineDistance = PositionUtil.getDistance1(bizOrder.getSenderLng().doubleValue(), bizOrder.getSenderLat().doubleValue(), bizOrder.getReceiverLng().doubleValue(), bizOrder.getReceiverLat().doubleValue());
            bizOrder.setLineDistance(lineDistance);
        }
        return bizOrderMapper.insert(bizOrder);
    }

    /**
     * 新增订单子单
     *
     * @param map 子单信息
     * @return 结果
     */
    @Override
    @Transactional
    public void insertBizOrderSub(Map map) {
        String orderSn = (String) map.get("orderSn");
        List<Map> subList = (List<Map>) map.get("sublist");
        for (Map map1 : subList) {
            if (map1.get("orderSn").equals(orderSn)){
                BizOrderSub bizOrderSub = new BizOrderSub();
                bizOrderSub.setOrderSn(orderSn);
                bizOrderSub.setSubOrderSn((String) map1.get("subOrderSn"));
                if (ObjectUtil.isNotEmpty(map1.get("weight"))) bizOrderSub.setWeight(BigDecimal.valueOf(Helper.FDouble( map1.get("weight"))));
                if (ObjectUtil.isNotEmpty(map1.get("length"))) bizOrderSub.setLength(BigDecimal.valueOf(Helper.FDouble( map1.get("length"))));
                if (ObjectUtil.isNotEmpty(map1.get("width"))) bizOrderSub.setWidth(BigDecimal.valueOf(Helper.FDouble( map1.get("width"))));
                if (ObjectUtil.isNotEmpty(map1.get("height"))) bizOrderSub.setHeight(BigDecimal.valueOf(Helper.FDouble( map1.get("height"))));
                if (ObjectUtil.isNotEmpty(map1.get("length")) && ObjectUtil.isNotEmpty(map1.get("width")) && ObjectUtil.isNotEmpty(map1.get("height"))){
                    bizOrderSub.setVolume(BigDecimal.valueOf(Helper.FDouble( map1.get("length"))).multiply(BigDecimal.valueOf(Helper.FDouble( map1.get("width")))).multiply(BigDecimal.valueOf(Helper.FDouble( map1.get("height")))));
                }
                bizOrderSub.setGoodsType((String) map1.get("goodsType"));
                bizOrderSub.setGoodsName((String) map1.get("goodsName"));
                if (ObjectUtil.isNotEmpty(map1.get("orderFee"))) bizOrderSub.setOrderFee(BigDecimal.valueOf(Helper.FDouble( map1.get("orderFee"))));
                bizOrderSub.setRemark((String) map1.get("remark"));
                bizOrderSubMapper.insert(bizOrderSub);
                // 同步更新订单表的运单状态
                BizOrder bizOrder = bizOrderMapper.selectByOrderSn(orderSn);
                bizOrder.setSubStatus(1);
                bizOrderMapper.updateById(bizOrder);
            }
        }
    }

    /**
     * 修改订单
     *
     * @param bizOrder 订单
     * @return 结果
     */
    @Override
    public int updateBizOrder(BizOrder bizOrder) {
        BizOrder order = bizOrderMapper.selectById(bizOrder.getId());
        if (bizOrder.getIsCancel() == 1 && order.getCancelTime() == null){
            bizOrder.setCancelTime(new Date());
        }
        return bizOrderMapper.updateById(bizOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteBizOrderByIds(Long[] ids) {
        UpdateWrapper<BizOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", (Object[]) ids);
        updateWrapper.set("status", "2"); //状态改为删除
        return bizOrderMapper.update(null, updateWrapper);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteBizOrderById(Long id) {
        UpdateWrapper<BizOrder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("status", "2"); //状态改为删除
        return bizOrderMapper.update(null, updateWrapper);
    }

    /**
     * 导入订单数据（调度员）
     *
     * @param orderList     订单数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importOrder(List<BizOrderVo> orderList, boolean updateSupport) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0) {
            throw new ServiceException("导入订单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BizOrderVo vo : orderList) {
            BizOrder bizOrder = new BizOrder();
            BeanUtils.copyProperties(vo,bizOrder);
            // 设置订单属性
            setBizOrder(bizOrder);
            try {
                bizOrderMapper.insert(bizOrder);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、订单 ").append(bizOrder.getOrderSn()).append(" 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单 " + bizOrder.getOrderSn() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导入订单数据（客户）
     *
     * @param orderList     订单数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importOrderCustomer(List<BizOrderVoCustomer> orderList, boolean updateSupport) {
        if (StringUtils.isNull(orderList) || orderList.size() == 0) {
            throw new ServiceException("导入订单数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BizOrderVoCustomer voCustomer : orderList) {
            BizOrder bizOrder = new BizOrder();
            BeanUtils.copyProperties(voCustomer,bizOrder);
            // 设置订单属性
            setBizOrderCustomer(bizOrder);
            try {
                bizOrderMapper.insert(bizOrder);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、订单 ").append(bizOrder.getOrderSn()).append(" 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订单 " + bizOrder.getOrderSn() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    // 设置订单相关属性（调度员导入）
    private void setBizOrder(BizOrder bizOrder) {
        setBizOrderSn(bizOrder);

        String customerName = bizOrder.getCustomerName(); // 客户名称
        String routeName = bizOrder.getRouteName(); // 路线名称
        String warehouseName = bizOrder.getWarehouseName(); // 仓库名称
        String shopName = bizOrder.getShopName(); // 店铺名称
        String carNo = bizOrder.getCarNo(); // 配送车牌号
        String driverName = bizOrder.getDriverName(); // 配送司机名称
        String copilotName = bizOrder.getCopilotName(); // 副驾司机名称
        String goodsType = bizOrder.getGoodsType(); // 物品类型
        String goodsName = bizOrder.getGoodsName(); // 物品名称
        BigDecimal weight = bizOrder.getWeight(); // 重量
        BigDecimal length = bizOrder.getLength(); // 长
        BigDecimal width = bizOrder.getWidth(); // 宽
        BigDecimal height = bizOrder.getHeight(); // 高
        String remark = bizOrder.getRemark(); // 备注

        BizCustomer bizCustomer = bizCustomerMapper.selectByName(customerName);
        Long customerId = bizCustomer.getId();
        bizOrder.setCustomerId(customerId);

        LambdaQueryWrapper<BizCustomerRoute> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizCustomerRoute::getCustomerId,customerId);
        queryWrapper.eq(BizCustomerRoute::getName,routeName);
        queryWrapper.eq(BizCustomerRoute::getStatus,"1");
        BizCustomerRoute bizCustomerRoute = bizCustomerRouteMapper.selectOne(queryWrapper);
        bizOrder.setRouteId(bizCustomerRoute.getId());

        LambdaQueryWrapper<BizCustomerWarehouse> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(BizCustomerWarehouse::getCustomerId,customerId);
        queryWrapper1.eq(BizCustomerWarehouse::getName,warehouseName);
        queryWrapper1.eq(BizCustomerWarehouse::getStatus,1);
        BizCustomerWarehouse bizCustomerWarehouse = bizCustomerWarehouseMapper.selectOne(queryWrapper1);
        bizOrder.setWarehouseId(bizCustomerWarehouse.getId());
        // 发件人信息就是仓库信息
        bizOrder.setSenderName(bizCustomerWarehouse.getName());
        bizOrder.setSenderLinkman(bizCustomerWarehouse.getLinkman());
        bizOrder.setSenderPhone(bizCustomerWarehouse.getLinkphone());
        bizOrder.setSenderAddress(bizCustomerWarehouse.getAddress());
        bizOrder.setSenderLng(bizCustomerWarehouse.getLng());
        bizOrder.setSenderLat(bizCustomerWarehouse.getLat());

        LambdaQueryWrapper<BizCustomerShop> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(BizCustomerShop::getCustomerId,customerId);
        queryWrapper2.eq(BizCustomerShop::getName,shopName);
        queryWrapper2.eq(BizCustomerShop::getStatus,1);
        BizCustomerShop bizCustomerShop = bizCustomerShopMapper.selectOne(queryWrapper2);
        bizOrder.setShopId(bizCustomerShop.getId());
        // 收件人信息就是店铺信息
        bizOrder.setReceiverName(bizCustomerShop.getName());
        bizOrder.setReceiverLinkman(bizCustomerShop.getLinkman());
        bizOrder.setReceiverPhone(bizCustomerShop.getLinkphone());
        bizOrder.setReceiverAddress(bizCustomerShop.getAddress());
        bizOrder.setReceiverLng(bizCustomerShop.getLng());
        bizOrder.setReceiverLat(bizCustomerShop.getLat());

        if (ObjectUtil.isNotEmpty(carNo)){
            LambdaQueryWrapper<BizCar> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.eq(BizCar::getCarNo,carNo);
            queryWrapper3.eq(BizCar::getStatus,1);
            BizCar bizCar = bizCarMapper.selectOne(queryWrapper3);
            bizOrder.setCarId(bizCar.getId());
        }
        if (ObjectUtil.isNotEmpty(driverName)){
            LambdaQueryWrapper<BizDriver> queryWrapper4= new LambdaQueryWrapper<>();
            queryWrapper4.eq(BizDriver::getName,driverName);
            queryWrapper4.eq(BizDriver::getStatus,1);
            BizDriver bizDriver = bizDriverMapper.selectOne(queryWrapper4);
            bizOrder.setDriverId(bizDriver.getId());
        }
        if (ObjectUtil.isNotEmpty(copilotName)){
            LambdaQueryWrapper<BizDriver> queryWrapper5= new LambdaQueryWrapper<>();
            queryWrapper5.eq(BizDriver::getName,copilotName);
            queryWrapper5.eq(BizDriver::getStatus,1);
            BizDriver copilot = bizDriverMapper.selectOne(queryWrapper5);
            bizOrder.setCopilotId(copilot.getId());
        }

        bizOrder.setGoodsType(goodsType);
        bizOrder.setGoodsName(goodsName);
        bizOrder.setWeight(weight);
        bizOrder.setLength(length);
        bizOrder.setWidth(width);
        bizOrder.setHeight(height);
        if (ObjectUtil.isNotEmpty(length) && ObjectUtil.isNotEmpty(width) && ObjectUtil.isNotEmpty(height)){
            bizOrder.setVolume(length.multiply(width).multiply(height));
        }
        bizOrder.setRemark(remark);
    }

    // 设置订单相关属性（客户导入）
    private void setBizOrderCustomer(BizOrder bizOrder) {
        setBizOrderSn(bizOrder);

        String routeName = bizOrder.getRouteName(); // 路线名称
        String warehouseName = bizOrder.getWarehouseName(); // 仓库名称
        String shopName = bizOrder.getShopName(); // 店铺名称
        String goodsType = bizOrder.getGoodsType(); // 物品类型
        String goodsName = bizOrder.getGoodsName(); // 物品名称
        BigDecimal weight = bizOrder.getWeight(); // 重量
        BigDecimal length = bizOrder.getLength(); // 长
        BigDecimal width = bizOrder.getWidth(); // 宽
        BigDecimal height = bizOrder.getHeight(); // 高
        String remark = bizOrder.getRemark(); // 备注

        BizCustomer bizCustomer = bizCustomerMapper.selectByLinkPhone(SecurityUtils.getUsername());
        Long customerId = bizCustomer.getId();
        bizOrder.setCustomerId(customerId);
        bizOrder.setCustomerName(bizCustomer.getName());

        LambdaQueryWrapper<BizCustomerRoute> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizCustomerRoute::getCustomerId,customerId);
        queryWrapper.eq(BizCustomerRoute::getName,routeName);
        queryWrapper.eq(BizCustomerRoute::getStatus,"1");
        BizCustomerRoute bizCustomerRoute = bizCustomerRouteMapper.selectOne(queryWrapper);
        bizOrder.setRouteId(bizCustomerRoute.getId());

        LambdaQueryWrapper<BizCustomerWarehouse> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(BizCustomerWarehouse::getCustomerId,customerId);
        queryWrapper1.eq(BizCustomerWarehouse::getName,warehouseName);
        queryWrapper1.eq(BizCustomerWarehouse::getStatus,1);
        BizCustomerWarehouse bizCustomerWarehouse = bizCustomerWarehouseMapper.selectOne(queryWrapper1);
        bizOrder.setWarehouseId(bizCustomerWarehouse.getId());
        // 发件人信息就是仓库信息
        bizOrder.setSenderName(bizCustomerWarehouse.getName());
        bizOrder.setSenderLinkman(bizCustomerWarehouse.getLinkman());
        bizOrder.setSenderPhone(bizCustomerWarehouse.getLinkphone());
        bizOrder.setSenderAddress(bizCustomerWarehouse.getAddress());
        bizOrder.setSenderLng(bizCustomerWarehouse.getLng());
        bizOrder.setSenderLat(bizCustomerWarehouse.getLat());

        LambdaQueryWrapper<BizCustomerShop> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(BizCustomerShop::getCustomerId,customerId);
        queryWrapper2.eq(BizCustomerShop::getName,shopName);
        queryWrapper2.eq(BizCustomerShop::getStatus,1);
        BizCustomerShop bizCustomerShop = bizCustomerShopMapper.selectOne(queryWrapper2);
        bizOrder.setShopId(bizCustomerShop.getId());
        // 收件人信息就是店铺信息
        bizOrder.setReceiverName(bizCustomerShop.getName());
        bizOrder.setReceiverLinkman(bizCustomerShop.getLinkman());
        bizOrder.setReceiverPhone(bizCustomerShop.getLinkphone());
        bizOrder.setReceiverAddress(bizCustomerShop.getAddress());
        bizOrder.setReceiverLng(bizCustomerShop.getLng());
        bizOrder.setReceiverLat(bizCustomerShop.getLat());

        bizOrder.setGoodsType(goodsType);
        bizOrder.setGoodsName(goodsName);
        bizOrder.setWeight(weight);
        bizOrder.setLength(length);
        bizOrder.setWidth(width);
        bizOrder.setHeight(height);
        if (ObjectUtil.isNotEmpty(length) && ObjectUtil.isNotEmpty(width) && ObjectUtil.isNotEmpty(height)){
            bizOrder.setVolume(length.multiply(width).multiply(height));
        }
        bizOrder.setRemark(remark);
    }

    // 订单号生成规则
    private void setBizOrderSn(BizOrder bizOrder) {
        String format = DateUtil.format(new Date(), "yyyyMMdd"); // 20241220
        String orderSn;
        BizOrder order = bizOrderMapper.selectLastestOrder();
        if (order == null || !order.getOrderSn().substring(1, 9).equals(format)){
            orderSn = "Y" + format + "1001";
        }else {
            String sn = order.getOrderSn();
            String substring = sn.substring(9); // 1001
            long aLong = Long.parseLong(substring);
            aLong += 1L;
            orderSn = "Y" + format + aLong;
        }
        bizOrder.setOrderSn(orderSn);
    }


    @Override
    public int goDelivery(Map map){
        BizDriver bizDriver = bizDriverMapper.selectByUserId(SecurityUtils.getUserId());
        Long orderId = Helper.FLong(map.get("id"));
        Long driverId = Helper.FLong(map.get("driverId"));
        BizOrder order = bizOrderMapper.selectById(orderId);
        Long warehouseId = order.getWarehouseId();

        LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizOrder::getStatus,1);
        queryWrapper.eq(BizOrder::getOrderStatus, 1);
        queryWrapper.eq(BizOrder::getWarehouseId, warehouseId);
        queryWrapper.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        int num = 0;
        List<BizOrder> list = bizOrderMapper.selectList(queryWrapper);
        for (BizOrder item : list) {
            BizOrder uorder = new BizOrder();
            uorder.setId(item.getId());
            uorder.setOrderSn(item.getOrderSn());
            uorder.setOrderStatus("2");
            uorder.setStartTime(new Date());
            num += bizOrderMapper.updateById(uorder);
        }
        return num;
    }
    @Override
    public int arrived(Map map){
        Long orderId = Helper.FLong(map.get("id"));
        String img = Helper.NStr(map.get("img"));
        String remark = Helper.NStr(map.get("remark"));
        double lat = Helper.FDouble(map.get("lat"));
        double lng = Helper.FDouble(map.get("lng"));

        BizDriver bizDriver = bizDriverMapper.selectByUserId(SecurityUtils.getUserId());
        BizOrder order = bizOrderMapper.selectById(orderId);
        order.setArriveLat(new BigDecimal(lat));
        order.setArriveLng(new BigDecimal(lng));
        order.setArriveImg(img);
        order.setArriveRemark(remark);
        order.setArriveTime(new Date());
        order.setOrderStatus("3");
        return bizOrderMapper.updateById(order);
    }

    @Override
    public Map<String, Long> getOrderStaticsByDriver() {
        String today = DateUtil.format(new Date(),"yyyy-MM-dd");
        Long userId = SecurityUtils.getUserId();
        BizDriver bizDriver = bizDriverMapper.selectByUserId(userId);
        LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizOrder::getOrderStatus,"1");
        queryWrapper.eq(BizOrder::getStatus,1);
        queryWrapper.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long dqj = bizOrderMapper.selectCount(queryWrapper);
        LambdaQueryWrapper<BizOrder> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(BizOrder::getOrderStatus,"2");
        queryWrapper2.eq(BizOrder::getStatus,1);
        queryWrapper2.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long psz = bizOrderMapper.selectCount(queryWrapper2);
        LambdaQueryWrapper<BizOrder> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(BizOrder::getOrderStatus,"3");
        queryWrapper3.eq(BizOrder::getStatus,1);
        queryWrapper3.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long ywc = bizOrderMapper.selectCount(queryWrapper3);
        LambdaQueryWrapper<BizOrder> queryWrapper4 = new LambdaQueryWrapper<>();
        queryWrapper4.eq(BizOrder::getOrderStatus,"1");
        queryWrapper4.eq(BizOrder::getStatus,1);
        queryWrapper4.like(BizOrder::getCreateTime,today);
        queryWrapper4.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long dqjToday = bizOrderMapper.selectCount(queryWrapper4);
        LambdaQueryWrapper<BizOrder> queryWrapper5 = new LambdaQueryWrapper<>();
        queryWrapper5.eq(BizOrder::getOrderStatus,"2");
        queryWrapper5.eq(BizOrder::getStatus,1);
        queryWrapper5.like(BizOrder::getUpdateTime,today);
        queryWrapper5.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long pszToday = bizOrderMapper.selectCount(queryWrapper5);
        LambdaQueryWrapper<BizOrder> queryWrapper6 = new LambdaQueryWrapper<>();
        queryWrapper6.eq(BizOrder::getOrderStatus,"3");
        queryWrapper6.eq(BizOrder::getStatus,1);
        queryWrapper6.like(BizOrder::getUpdateTime,today);
        queryWrapper6.and(wq -> wq.eq(BizOrder::getDriverId,bizDriver.getId()).or().eq(BizOrder::getCopilotId,bizDriver.getId()));
        Long ywcToday = bizOrderMapper.selectCount(queryWrapper6);
        Map<String,Long> map = new HashMap<>();
        map.put("dqj",dqj);
        map.put("psz",psz);
        map.put("ywc",ywc);
        map.put("dqjToday",dqjToday);
        map.put("pszToday",pszToday);
        map.put("ywcToday",ywcToday);
        return map;
    }
}
