package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.manage.dao.IFleetDeviceMapper;
import com.dji.sample.manage.model.dto.FleetDeviceDTO;
import com.dji.sample.manage.model.entity.DeviceEntity;
import com.dji.sample.manage.model.entity.FleetDeviceEntity;
import com.dji.sample.manage.service.IDeviceService;
import com.dji.sample.manage.service.IFleetDeviceService;
import com.dji.sdk.cloudapi.device.DeviceEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guan
 */
@Service
@Transactional
public class FleetDeviceServiceImpl extends ServiceImpl<IFleetDeviceMapper, FleetDeviceEntity> implements IFleetDeviceService {

    @Autowired
    private IFleetDeviceMapper mapper;

    @Autowired
    private IDeviceService deviceService;

    @Override
    public void addFleetDevice(List<FleetDeviceEntity> deviceList) {

        for (FleetDeviceEntity addDevice : deviceList) {
            this.mapper.insert(addDevice);
        }
    }

    @Override
    public List<FleetDeviceDTO> searchDeviceDTOListByFleetId(String fleetId) {

        LambdaQueryWrapper<FleetDeviceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FleetDeviceEntity::getFleetId, fleetId);

        List<FleetDeviceEntity> fleetDeviceEntities = this.mapper.selectList(queryWrapper);

        List<FleetDeviceDTO> deviceDTOList = new ArrayList<>();
        for (FleetDeviceEntity fleetDeviceEntity : fleetDeviceEntities) {
            deviceDTOList.add(fleetDeviceEntityToDTO(fleetDeviceEntity));
        }
        return deviceDTOList;
    }

    public FleetDeviceDTO fleetDeviceEntityToDTO(FleetDeviceEntity entity) {

        FleetDeviceDTO fleetDeviceDTO = new FleetDeviceDTO();
        fleetDeviceDTO.setId(entity.getId());
        fleetDeviceDTO.setDeviceId(entity.getDeviceId());
        fleetDeviceDTO.setFleetId(entity.getFleetId());

        // 查询设备信息
        LambdaQueryWrapper<DeviceEntity> deviceQueryWrapper = new LambdaQueryWrapper<>();
        deviceQueryWrapper.eq(DeviceEntity::getId, fleetDeviceDTO.getDeviceId());
        DeviceEntity device = deviceService.getOne(deviceQueryWrapper);
        if (!ObjectUtils.isEmpty(device)) {
            fleetDeviceDTO.setDeviceNickname(device.getNickname());
            // 型号
            DeviceEnum deviceEnum = DeviceEnum.find(device.getDomain(), device.getDeviceType(), device.getSubType());
            fleetDeviceDTO.setDeviceEnumName(deviceEnum.name());
        }

        return fleetDeviceDTO;
    }
}
