package cn.iocoder.yudao.module.inspection.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.common.service.InspectionNoticeService;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.appBase.controller.admin.InspectionSocket;
import cn.iocoder.yudao.module.config.entity.ReminderMessage;
import cn.iocoder.yudao.module.config.service.RedisDelayedQueueService;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.mapper.InspectionMeetCarOrderMapper;
import cn.iocoder.yudao.module.inspection.service.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZoneId;

import static cn.iocoder.yudao.module.constant.InspectionConstants.INSPECTION_WEBSOCKET_MESSAGE_CONTENT_CUSTOMER_ARRIVE;
import static cn.iocoder.yudao.module.inspection.service.impl.InspectionAppointmentServiceImpl.getArrivalTime;

/**
 * @Description: 接车订单
 * @Author: 86187
 * @Date: 2025/04/11 11:06
 * @Version: 1.0
 */
@Service
@RequiredArgsConstructor
public class InspectionMeetCarOrderServiceImpl extends ServiceImpl<InspectionMeetCarOrderMapper, InspectionMeetCarOrder> implements InspectionMeetCarOrderService {

    private final InspectionSocket inspectionSocket;

    private final IInspectionAppointmentService inspectionAppointmentService;

    private final IInspectionPickCarService inspectionPickCarService;

    private final InspectionStepInfoService inspectionStepInfoService;

    private final InspectionGoodsSkuService skuService;

    private final IShopInspectionGoodsService goodsService;

    private final RedisDelayedQueueService redisDelayedQueueService;

    private final InspectionNoticeService noticeService;

    private final InspectionBusinessMeetAddressRecordService meetAddressRecordService;

    /**
     * 添加接车订单
     *
     * @param order 接车订单
     */
    @Override
    @Transactional
    public void add(InspectionMeetCarOrder order) {
        boolean ifSendMessage = true;
        // 设置接车员id
        if (order.getMeetManId() == null) {
            order.setMeetManId(SecurityFrameworkUtils.getLoginUserId());
            ifSendMessage = false;
        }
        if (ObjectUtil.isNotEmpty(order.getSkuId())) {
            InspectionGoodsSku sku = skuService.getById(order.getSkuId());
            ShopInspectionGoods goods = goodsService.getById(sku.getGoodsId());

            order.setGoodsId(Long.parseLong(goods.getId().toString()));
            order.setGoodsTitle(goods.getTitle());

            order.setSkuName(sku.getSkuName());
        }
        save(order);

        //指派的接车人
        if (ifSendMessage) {
            // 修改预约表的接车订单id字段
            inspectionAppointmentService.update(Wrappers.<InspectionAppointment>lambdaUpdate()
                    .eq(InspectionAppointment::getId, order.getAppointmentId())
                    .set(InspectionAppointment::getMeetOrderId, order.getId()));

            // 获取预约表的信息
            InspectionAppointment appointment = inspectionAppointmentService.getById(order.getAppointmentId());
            if (ObjectUtil.isNotEmpty(appointment)) {
                // 判断是否有上门取车
                if (appointment.getIsPickCar().equals("1")) {
                    InspectionPickCar pickCar = inspectionPickCarService.getById(appointment.getPickCarId());
                    //获取详细地址和经纬度修改接车订单表
                    update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                            .eq(InspectionMeetCarOrder::getId, order.getId())
                            .set(InspectionMeetCarOrder::getMeetAddress, pickCar.getAdressDetail())
                            .set(InspectionMeetCarOrder::getLatitude, pickCar.getLatitude())
                            .set(InspectionMeetCarOrder::getLongitude, pickCar.getLongitude())
                            .set(InspectionMeetCarOrder::getAppointmentDay, pickCar.getAppointmentDay())
                            .set(InspectionMeetCarOrder::getAppointmentTime, pickCar.getAppointmentTime()));

                    inspectionSocket.sendMessage("接工单", order.getMeetManId().toString());
                } else {
                    update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                            .eq(InspectionMeetCarOrder::getId, order.getId())
                            .set(InspectionMeetCarOrder::getAppointmentDay, appointment.getAppointmentDay()));

                    // 设置消息提醒
                    ReminderMessage message = new ReminderMessage(appointment.getId(), order.getMeetManId(), INSPECTION_WEBSOCKET_MESSAGE_CONTENT_CUSTOMER_ARRIVE);

                    long triggerTimeMillis = getArrivalTime(appointment.getAppointmentDay(), appointment.getAppointmentPeriod()).minusMinutes(10).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                    redisDelayedQueueService.addToQueue(message, triggerTimeMillis);
                }

                // 发送站内信
                String msg = "";
                if (ObjectUtil.isNotEmpty(appointment.getCarNo())) {
                    msg = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_ASSIGN_STAFF_MEET_CAR, appointment.getAppointmentDay(), appointment.getCarNo() == null ? "" : appointment.getCarNo(), appointment.getAppointmentPeriod());
                } else {
                    msg = String.format(InspectionConstants.INSPECTION_NOTICE_TEMPLATE_ASSIGN_STAFF_MEET_CAR_NO_CAR_NO, appointment.getAppointmentDay(), appointment.getAppointmentPeriod());
                }
                noticeService.sentMessage(order.getMeetManId(), msg);
            }
        }

        if (StrUtil.isNotEmpty(order.getContent()) || StrUtil.isNotEmpty(order.getImages())) {
            String title = "接车拍照";
            if (order.getMeetType() == 0) {
                title = "接车拍照";
            } else if (order.getMeetType() == 1) {
                title = "上门接车";
            }
            // 在步骤表里添加一条记录
            InspectionStepInfo inspectionStepInfo = new InspectionStepInfo();
            inspectionStepInfo.setInspectionInfoId(order.getId());
            //设置开始时间
            inspectionStepInfo.setCreateTime(DateUtil.date());
            inspectionStepInfo.setCreator(Integer.parseInt(SecurityFrameworkUtils.getLoginUserId() + ""));
            inspectionStepInfo.setTitle(title);
            inspectionStepInfo.setContent(order.getContent());
            inspectionStepInfo.setImages(order.getImages());
            inspectionStepInfo.setStepNum(1);
            inspectionStepInfo.setUpdater(Integer.parseInt(SecurityFrameworkUtils.getLoginUserId() + ""));
            inspectionStepInfo.setUpdateTime(DateUtil.date());
            inspectionStepInfoService.save(inspectionStepInfo);

            //修改订单表为已接车
            update(Wrappers.<InspectionMeetCarOrder>lambdaUpdate()
                    .eq(InspectionMeetCarOrder::getId, order.getId())
                    .set(InspectionMeetCarOrder::getIsMeet, 1));
        }

        // 判断上门取车地址是否为空 如果不为空添加到记录中
        if (ObjectUtil.isNotEmpty(order.getMeetAddress())) {
            InspectionBusinessMeetAddressRecord meetAddressRecord = new InspectionBusinessMeetAddressRecord();
            meetAddressRecord.setUserId(SecurityFrameworkUtils.getLoginUserId());
            meetAddressRecord.setAddress(order.getMeetAddress());
            meetAddressRecordService.save(meetAddressRecord);
        }
    }
}
