package com.aircraft.modules.aircraft.service.impl;

import com.aircraft.domain.dto.AttachmentMaterialDTO;
import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.aircraft.domain.AircraftDevice;
import com.aircraft.modules.aircraft.domain.dto.AircraftDevicePageDTO;
import com.aircraft.modules.aircraft.domain.vo.AircraftDevicePageVO;
import com.aircraft.modules.aircraft.mapper.AircraftDeviceMapper;
import com.aircraft.modules.aircraft.service.AircraftDeviceService;
import com.aircraft.modules.system.domain.AttachmentMaterial;
import com.aircraft.modules.system.service.IAttachmentMaterialService;
import com.aircraft.utils.SecurityUtils;
import com.aircraft.utils.enums.UserTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sdk.mqtt.MqttGatewayPublish;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 飞行器设备表 服务实现类
 * </p>
 *
 * @author cli
 * @since 2025-07-11
 */
@Service
@RequiredArgsConstructor
public class AircraftDeviceServiceImpl extends ServiceImpl<AircraftDeviceMapper, AircraftDevice> implements AircraftDeviceService {

    private final IAttachmentMaterialService attachmentMaterialService;

    //todo 枚举？
    private final String BUSINESS_TYPE = "aircraft_device";


    private final MqttGatewayPublish mqttGatewayPublish;



    @Override
    public IPage<AircraftDevicePageVO> page(AircraftDevicePageDTO dto, Page page) {
        //飞行端用户只能看到自己名下
        if (UserTypeEnum.EMPLOYEES.equals(SecurityUtils.getCurrentUserType())) {
            dto.setEmployeesId(SecurityUtils.getCurrentUserId());
        }
        return baseMapper.page(dto, page);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(AircraftDevice aircraftDevice) {
        aircraftDevice.setId(null);
        //检查型号是否重复
        checkModelRepeat(aircraftDevice);
        save(aircraftDevice);
        //保存设备图片
        List<AttachmentMaterial> deviceImages = aircraftDevice.getDeviceImages()
                .stream()
                .map(deviceImage -> {
                    AttachmentMaterial attachmentMaterial = new AttachmentMaterial();
                    BeanUtils.copyProperties(deviceImage, attachmentMaterial);
                    attachmentMaterial.setId(null);
                    attachmentMaterial.setBusinessId(aircraftDevice.getId());
                    attachmentMaterial.setBusinessType(BUSINESS_TYPE);
                    return attachmentMaterial;
                }).toList();
        attachmentMaterialService.saveBatch(deviceImages);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AircraftDevice aircraftDevice) {
        checkModelRepeat(aircraftDevice);
        updateById(aircraftDevice);
        //保存设备图片
        List<AttachmentMaterial> deviceImages = aircraftDevice.getDeviceImages()
                .stream()
                .map(deviceImage -> {
                    AttachmentMaterial attachmentMaterial = new AttachmentMaterial();
                    BeanUtils.copyProperties(deviceImage, attachmentMaterial);
                    attachmentMaterial.setBusinessId(aircraftDevice.getId());
                    attachmentMaterial.setBusinessType(BUSINESS_TYPE);
                    return attachmentMaterial;
                }).toList();
        List<Long> ids = deviceImages.stream().map(AttachmentMaterial::getId).toList();
        if (CollectionUtils.isNotEmpty(ids)) {
            //删除不在本次提交范围的图片
            attachmentMaterialService.remove(Wrappers.<AttachmentMaterial>lambdaQuery()
                    .eq(AttachmentMaterial::getBusinessType, BUSINESS_TYPE)
                    .eq(AttachmentMaterial::getBusinessId, aircraftDevice.getId())
                    .notIn(AttachmentMaterial::getId, ids));
            //保存本次提交的图片
            attachmentMaterialService.saveOrUpdateBatch(deviceImages);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        removeById(id);
        attachmentMaterialService.remove(Wrappers.<AttachmentMaterial>lambdaQuery()
                .eq(AttachmentMaterial::getBusinessType, BUSINESS_TYPE)
                .eq(AttachmentMaterial::getBusinessId, id));
    }

    @Override
    public AircraftDevice findById(Long id) {
        AircraftDevice aircraftDevice = getById(id);
        if (null != aircraftDevice) {
            List<AttachmentMaterialDTO> deviceImages = attachmentMaterialService
                    .lambdaQuery()
                    .eq(AttachmentMaterial::getBusinessType, BUSINESS_TYPE)
                    .eq(AttachmentMaterial::getBusinessId, id)
                    .list()
                    .stream()
                    .map(attachmentMaterial -> {
                        AttachmentMaterialDTO localAttachmentMaterialDTO = new AttachmentMaterialDTO();
                        BeanUtils.copyProperties(attachmentMaterial, localAttachmentMaterialDTO);
                        return localAttachmentMaterialDTO;
                    }).toList();
            aircraftDevice.setDeviceImages(deviceImages);
        }
        return aircraftDevice;
    }


    /**
     * 检查型号是否重复
     */
    private void checkModelRepeat(AircraftDevice aircraftDevice) {
        LambdaQueryWrapper<AircraftDevice> queryWrapper = new LambdaQueryWrapper<>();
        if (null != aircraftDevice.getId()) {
            queryWrapper.ne(AircraftDevice::getId, aircraftDevice.getId());
        }
        queryWrapper.eq(AircraftDevice::getBrand, aircraftDevice.getBrand())
                .eq(AircraftDevice::getModel, aircraftDevice.getModel());
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new BadRequestException("设备型号重复");
        }
    }
}
