package com.yc.ship.module.trade.service.orderjzdetail;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDispatchBatchReqVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDispatchPageReqVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDispatchRecordRespVO;
import com.yc.ship.module.trade.controller.admin.orderjzdetail.vo.OrderJzDispatchSaveReqVO;
import com.yc.ship.module.trade.dal.dataobject.orderjzdetail.OrderJzDetailDO;
import com.yc.ship.module.trade.dal.dataobject.orderjzdispatch.OrderJzDispatchDO;
import com.yc.ship.module.trade.dal.mysql.orderjzdetail.OrderJzDetailMapper;
import com.yc.ship.module.trade.dal.mysql.orderjzdispatch.OrderJzDispatchMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.time.LocalDateTime;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.trade.enums.ErrorCodeConstants.ORDER_JZ_DISPATCH_NOT_EXISTS;

/**
 * 订单分车 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class OrderJzDispatchServiceImpl implements OrderJzDispatchService {

    @Resource
    private OrderJzDispatchMapper orderJzDispatchMapper;

    @Resource
    private OrderJzDetailMapper orderJzDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrderJzDispatch(@Valid OrderJzDispatchSaveReqVO createReqVO) {
        OrderJzDispatchDO orderJzDispatch = OrderJzDispatchDO.builder()
                .dispatchTime(LocalDateTime.now())
                .voyageId(createReqVO.getVoyageId())
                .dispatchNo(createReqVO.getDispatchNo())
                .groupNo(createReqVO.getGroupNo())
                .busNumber(createReqVO.getBusNumber())
                .driverName(createReqVO.getDriverName())
                .driverPhone(createReqVO.getDriverPhone())
                .receiverName(createReqVO.getReceiverName())
                .receiverPhone(createReqVO.getReceiverPhone())
                .sourceType(1)
                .passengerCount(createReqVO.getPassengerCount())
                .remark(createReqVO.getRemark())
                .build();
        orderJzDispatchMapper.insert(orderJzDispatch);

        // 更新接站人员信息的分车ID
        OrderJzDetailDO orderJzDetail = orderJzDetailMapper.selectById(createReqVO.getOrderId());
        if (orderJzDetail != null) {
            orderJzDetail.setDispatchId(orderJzDispatch.getId());
            orderJzDetailMapper.updateById(orderJzDetail);
        }

        return orderJzDispatch.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSaveOrderJzDispatch(@Valid OrderJzDispatchBatchReqVO batchReqVO) {
        OrderJzDispatchBatchReqVO.DispatchInfo info = batchReqVO.getDispatchInfo();
        String dispatchNo = info.getDispatchNo();
        String groupNo = info.getGroupNo();
        Long voyageId = info.getVoyageId();
        Integer sourceType = info.getSourceType(); // 1.接站 2.赠送接站

        // 根据条件查找已有的分车记录：分车号+分车组团号+航次ID，或分车号+航次ID
        LambdaQueryWrapper<OrderJzDispatchDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderJzDispatchDO::getDispatchNo, dispatchNo)
                .eq(OrderJzDispatchDO::getVoyageId, voyageId)
        .eq(OrderJzDispatchDO::getSourceType, sourceType);
        if (StrUtil.isNotBlank(groupNo)) {
            queryWrapper.eq(OrderJzDispatchDO::getGroupNo, groupNo);
        }
        List<OrderJzDispatchDO> existingList = orderJzDispatchMapper.selectList(queryWrapper);

        Long dispatchId;
        if (existingList != null && !existingList.isEmpty()) {
            // 已存在分车记录，更新并复用
            OrderJzDispatchDO existing = existingList.get(0);
            OrderJzDispatchDO updateObj = OrderJzDispatchDO.builder()
                    .id(existing.getId())
                    .busNumber(info.getBusNumber())
                    .driverName(info.getDriverName())
                    .driverPhone(info.getDriverPhone())
                    .receiverName(info.getReceiverName())
                    .receiverPhone(info.getReceiverPhone())
                    .passengerCount(existing.getPassengerCount() + batchReqVO.getOrderItems().size())
                    .remark(info.getRemark())
                    .build();
            orderJzDispatchMapper.updateById(updateObj);
            dispatchId = existing.getId();
        } else {
            // 不存在，新建分车记录
            OrderJzDispatchDO orderJzDispatch = OrderJzDispatchDO.builder()
                    .dispatchTime(LocalDateTime.now())
                    .voyageId(voyageId)
                    .dispatchNo(dispatchNo)
                    .groupNo(groupNo)
                    .busNumber(info.getBusNumber())
                    .driverName(info.getDriverName())
                    .driverPhone(info.getDriverPhone())
                    .receiverName(info.getReceiverName())
                    .receiverPhone(info.getReceiverPhone())
                    .sourceType(ObjectUtil.isEmpty(info.getSourceType()) ? 1 : info.getSourceType())
                    .passengerCount(batchReqVO.getOrderItems().size())
                    .remark(info.getRemark())
                    .build();
            orderJzDispatchMapper.insert(orderJzDispatch);
            dispatchId = orderJzDispatch.getId();
        }

        // 校验并更新接站人员的分车ID
        StringBuilder alreadyDispatchedNames = new StringBuilder();
        for (OrderJzDispatchBatchReqVO.OrderItem item : batchReqVO.getOrderItems()) {
            OrderJzDetailDO detail = orderJzDetailMapper.selectById(item.getId());
            if (detail != null) {
                // 校验是否已分车（dispatchId不为空且不为0表示已分车）
                if (detail.getDispatchId() != null && detail.getDispatchId() != 0L) {
                    if (alreadyDispatchedNames.length() > 0) {
                        alreadyDispatchedNames.append("、");
                    }
                    alreadyDispatchedNames.append(detail.getName());
                }
            }
        }
        if (alreadyDispatchedNames.length() > 0) {
            throw new RuntimeException("以下游客已分车，不能重复分车：" + alreadyDispatchedNames.toString());
        }

        // 更新接站人员的分车ID
        for (OrderJzDispatchBatchReqVO.OrderItem item : batchReqVO.getOrderItems()) {
            OrderJzDetailDO detail = orderJzDetailMapper.selectById(item.getId());
            if (detail != null) {
                detail.setDispatchId(dispatchId);
                orderJzDetailMapper.updateById(detail);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderJzDispatch(@Valid OrderJzDispatchSaveReqVO updateReqVO) {
        // 校验存在
        validateOrderJzDispatchExists(updateReqVO.getId());
        // 更新
        OrderJzDispatchDO updateObj = OrderJzDispatchDO.builder()
                .id(updateReqVO.getId())
                .dispatchTime(LocalDateTime.now())
                .voyageId(updateReqVO.getVoyageId())
                .dispatchNo(updateReqVO.getDispatchNo())
                .groupNo(updateReqVO.getGroupNo())
                .busNumber(updateReqVO.getBusNumber())
                .driverName(updateReqVO.getDriverName())
                .driverPhone(updateReqVO.getDriverPhone())
                .receiverName(updateReqVO.getReceiverName())
                .receiverPhone(updateReqVO.getReceiverPhone())
                .sourceType(1)
                .passengerCount(updateReqVO.getPassengerCount())
                .remark(updateReqVO.getRemark())
                .build();
        orderJzDispatchMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOrderJzDispatch(Long id) {
        // 参数 id 现在表示接站人员ID（OrderJzDetailDO.id）
        // 根据接站人员ID获取接站人员信息
        OrderJzDetailDO orderJzDetail = orderJzDetailMapper.selectById(id);
        if (orderJzDetail == null) {
            // 接站人员不存在，抛出异常
            throw exception(ORDER_JZ_DISPATCH_NOT_EXISTS);
        }

        // 获取分车ID
        Long dispatchId = orderJzDetail.getDispatchId();
        if (dispatchId != null) {

            OrderJzDispatchDO orderJzDis = orderJzDispatchMapper.selectById(dispatchId);

            Integer passengerCount = ObjectUtils.isEmpty(orderJzDis) ? 0 : orderJzDis.getPassengerCount();
            if (passengerCount != null && passengerCount > 1) {
                // 大于一人 更新分车记录表
                orderJzDispatchMapper.updateById(OrderJzDispatchDO.builder()
                        .id(dispatchId)
                        .passengerCount(passengerCount - 1)
                        .build());
            } else {
                // 删除分车记录
                orderJzDispatchMapper.physicalDeleteById(dispatchId);
            }

            // 将接站人员信息的 dispatch_id 设置为 null
            orderJzDetail.setDispatchId(0L);
            orderJzDetailMapper.updateById(orderJzDetail);
        }
        // 如果 dispatchId 为 0，说明该接站人员没有分车记录，无需处理
    }

    private void validateOrderJzDispatchExists(Long id) {
        if (orderJzDispatchMapper.selectById(id) == null) {
            throw exception(ORDER_JZ_DISPATCH_NOT_EXISTS);
        }
    }

    @Override
    public OrderJzDispatchDO getOrderJzDispatch(Long id) {
        return orderJzDispatchMapper.selectById(id);
    }

    @Override
    public PageResult<OrderJzDispatchRecordRespVO> getDispatchRecordPage(OrderJzDispatchPageReqVO pageReqVO) {
        int offset = (pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize();
        List<OrderJzDispatchRecordRespVO> list = orderJzDispatchMapper.selectDispatchRecordPage(
                pageReqVO, offset, pageReqVO.getPageSize());
        Long total = orderJzDispatchMapper.selectDispatchRecordCount(pageReqVO);
        return new PageResult<>(list, total);
    }

    @Override
    public List<OrderJzDispatchRecordRespVO> getDispatchRecordExportList(OrderJzDispatchPageReqVO pageReqVO) {
        return orderJzDispatchMapper.selectDispatchRecordPage(pageReqVO, 0, Integer.MAX_VALUE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDispatchRecord(@Valid OrderJzDispatchSaveReqVO updateReqVO) {
        // 构建更新条件
        LambdaUpdateWrapper<OrderJzDispatchDO> updateWrapper = new LambdaUpdateWrapper<>();

        // 如果有分车组团号，通过分车号、分车组团号、航次、id条件更新
       // if (StrUtil.isNotBlank(updateReqVO.getGroupNo())) {
            updateWrapper.eq(OrderJzDispatchDO::getDispatchNo, updateReqVO.getDispatchNo())
                    .eq(OrderJzDispatchDO::getGroupNo, updateReqVO.getGroupNo())
                    .eq(OrderJzDispatchDO::getVoyageId, updateReqVO.getVoyageId())
            .eq(OrderJzDispatchDO::getSourceType, updateReqVO.getSourceType());
            /*.eq(OrderJzDispatchDO::getId, updateReqVO.getId());*/
        //} else {
            // 如果没有分车组团号，通过分车号、id两个条件更新
            // updateWrapper.eq(OrderJzDispatchDO::getDispatchNo, updateReqVO.getDispatchNo())
             //       .eq(OrderJzDispatchDO::getId, updateReqVO.getId());
       // }

        // 构建更新对象
        OrderJzDispatchDO updateObj = OrderJzDispatchDO.builder()
                .busNumber(updateReqVO.getBusNumber())
                .driverName(updateReqVO.getDriverName())
                .driverPhone(updateReqVO.getDriverPhone())
                .receiverName(updateReqVO.getReceiverName())
                .receiverPhone(updateReqVO.getReceiverPhone())
                .remark(updateReqVO.getRemark())
                .build();

        // 执行更新
        orderJzDispatchMapper.update(updateObj, updateWrapper);
    }

    @Override
    public String checkDispatchDuplicate(OrderJzDispatchBatchReqVO.DispatchInfo dispatchInfo) {
        String dispatchNo = dispatchInfo.getDispatchNo();
        String groupNo = dispatchInfo.getGroupNo();
        Long voyageId = dispatchInfo.getVoyageId();

        if (StrUtil.isBlank(dispatchNo)) {
            return "分车号不能为空";
        }

        if (StrUtil.isBlank(groupNo)) {
            return "分车组团号不能为空";
        }



       /* // 根据条件查找已有的分车记录
        LambdaQueryWrapper<OrderJzDispatchDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderJzDispatchDO::getDispatchNo, dispatchNo)
                .eq(OrderJzDispatchDO::getVoyageId, voyageId);
        if (StrUtil.isNotBlank(groupNo)) {
            queryWrapper.eq(OrderJzDispatchDO::getGroupNo, groupNo);
        }
        List<OrderJzDispatchDO> existingList = orderJzDispatchMapper.selectList(queryWrapper);

        if (existingList == null || existingList.isEmpty()) {
            return null; // 无重复
        }

            String condition = StrUtil.isNotBlank(groupNo)
                    ? "分车号「" + dispatchNo + "」+分车组团号「" + groupNo + "」"
                    : "分车号「" + dispatchNo + "」";
            return "该" + condition + "已存在分车组团号记录";*/
        return null; // 无重复
    }


}
