package com.xindazhou.platform.service.service.maintenance;

import com.xindazhou.platform.controller.admin.service.maintenance.vo.MaintenanceOrderPageReqVO;
import com.xindazhou.platform.controller.admin.service.maintenance.vo.MaintenanceOrderRespVO;
import com.xindazhou.platform.controller.admin.service.maintenance.vo.MaintenanceOrderSaveReqVO;
import com.xindazhou.platform.controller.admin.service.maintenance.vo.MaintenanceOrderStatusUpdateReqVO;
import com.xindazhou.platform.convert.service.maintenance.MaintenanceOrderConvert;
import com.xindazhou.platform.dal.service.dataobject.maintenance.MaintenanceOrderDO;
import com.xindazhou.platform.dal.service.mysql.maintenance.MaintenanceOrderMapper;
import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xindazhou.user.api.user.MemberUserApi;
import com.xindazhou.user.api.user.dto.MemberUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * 维保订单 Service 实现类
 *
 * @author xindazhou
 */
@Service("platformMaintenanceOrderServiceImpl")
@Validated
@Slf4j
public class MaintenanceOrderServiceImpl implements MaintenanceOrderService {

    @Resource
    private MaintenanceOrderMapper maintenanceOrderMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createMaintenanceOrder(MaintenanceOrderSaveReqVO createReqVO) {
        // 插入
        MaintenanceOrderDO order = MaintenanceOrderConvert.INSTANCE.convert(createReqVO);
        order.setOrderId(UUID.randomUUID().toString().replace("-", "")); // 生成唯一订单编号
        order.setOrderNo("MO" + System.currentTimeMillis()); // 生成订单号
        order.setStatus(0); // 默认待处理
        maintenanceOrderMapper.insert(order);
        return order.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMaintenanceOrder(MaintenanceOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateMaintenanceOrderExists(updateReqVO.getId());

        // 更新
        MaintenanceOrderDO updateObj = MaintenanceOrderConvert.INSTANCE.convert(updateReqVO);
        maintenanceOrderMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMaintenanceOrder(Long id) {
        // 校验存在
        validateMaintenanceOrderExists(id);
        // 删除
        maintenanceOrderMapper.deleteById(id);
    }

    @Override
    public MaintenanceOrderRespVO getMaintenanceOrder(Long id) {
        MaintenanceOrderDO order = validateMaintenanceOrderExists(id);
        MaintenanceOrderRespVO respVO = MaintenanceOrderConvert.INSTANCE.convert(order);

        // 填充车辆信息（这里简化，实际需要通过RPC调用车辆服务）
        // fillVehicleInfo(respVO, order.getVehicleId());

        // 填充用户信息
        fillUserInfo(respVO, order.getUserId());

        return respVO;
    }

    @Override
    public PageResult<MaintenanceOrderRespVO> getMaintenanceOrderPage(MaintenanceOrderPageReqVO pageReqVO) {
        // 处理关键字搜索（订单号/车牌号）
        LambdaQueryWrapperX<MaintenanceOrderDO> queryWrapper = new LambdaQueryWrapperX<MaintenanceOrderDO>()
                .likeIfPresent(MaintenanceOrderDO::getOrderNo, pageReqVO.getKeyword())
                .eqIfPresent(MaintenanceOrderDO::getStatus, pageReqVO.getStatus())
                .betweenIfPresent(MaintenanceOrderDO::getCreateTime, pageReqVO.getStartTime(), pageReqVO.getEndTime())
                .orderByDesc(MaintenanceOrderDO::getId);

        PageResult<MaintenanceOrderDO> pageResult = maintenanceOrderMapper.selectPage(pageReqVO, queryWrapper);

        // 转换为VO
        List<MaintenanceOrderRespVO> respList = MaintenanceOrderConvert.INSTANCE.convertList(pageResult.getList());

        // 批量填充用户信息
        fillUserInfoList(respList);

        // 批量填充车辆信息（这里简化，实际需要通过RPC调用车辆服务）
        // fillVehicleInfoList(respList);

        return new PageResult<>(respList, pageResult.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMaintenanceOrderStatus(Long id, MaintenanceOrderStatusUpdateReqVO statusUpdateReqVO) {
        // 校验存在
        MaintenanceOrderDO order = validateMaintenanceOrderExists(id);

        // 更新状态
        MaintenanceOrderDO updateObj = new MaintenanceOrderDO();
        updateObj.setId(id);
        updateObj.setStatus(statusUpdateReqVO.getStatus());
        if (statusUpdateReqVO.getRemark() != null) {
            updateObj.setRemark(statusUpdateReqVO.getRemark());
        }
        maintenanceOrderMapper.updateById(updateObj);
    }

    private MaintenanceOrderDO validateMaintenanceOrderExists(Long id) {
        MaintenanceOrderDO order = maintenanceOrderMapper.selectById(id);
        if (order == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "维保订单不存在");
        }
        return order;
    }

    /**
     * 填充单个订单的用户信息
     */
    private void fillUserInfo(MaintenanceOrderRespVO respVO, Long userId) {
        if (userId == null) {
            return;
        }
        try {
            MemberUserRespDTO user = memberUserApi.getUser(userId).getCheckedData();
            if (user != null) {
                MaintenanceOrderRespVO.UserInfo userInfo = new MaintenanceOrderRespVO.UserInfo();
                userInfo.setName(user.getNickname());
                userInfo.setMobile(user.getMobile());
                respVO.setUserInfo(userInfo);
            }
        } catch (Exception e) {
            log.warn("获取用户信息失败", e);
        }
    }

    /**
     * 批量填充订单列表的用户信息
     */
    private void fillUserInfoList(List<MaintenanceOrderRespVO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        Set<Long> userIds = list.stream()
                .map(MaintenanceOrderRespVO::getUserId)
                .filter(userId -> userId != null)
                .collect(Collectors.toSet());
        if (userIds.isEmpty()) {
            return;
        }
        try {
            Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
            list.forEach(order -> {
                MemberUserRespDTO user = userMap.get(order.getUserId());
                if (user != null) {
                    MaintenanceOrderRespVO.UserInfo userInfo = new MaintenanceOrderRespVO.UserInfo();
                    userInfo.setName(user.getNickname());
                    userInfo.setMobile(user.getMobile());
                    order.setUserInfo(userInfo);
                }
            });
        } catch (Exception e) {
            log.warn("批量获取用户信息失败", e);
        }
    }

}

