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


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dji.sample.wayline.dao.IWaylinePointMapper;
import com.dji.sample.wayline.model.dto.WaylinePointDTO;
import com.dji.sample.wayline.model.entity.WaylinePointEntity;
import com.dji.sample.wayline.service.IWaylinePointService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huiqing.jiang
 * @version 1.1
 * @date 2024/9/20
 */
@Service
@Transactional
@Slf4j
public class WaylinePointServiceImpl implements IWaylinePointService {

    @Autowired
    private IWaylinePointMapper mapper;


    @Override
    public void insertPoint(List<WaylinePointDTO> list, String waylineId) {
        for (WaylinePointDTO dto : list) {
            WaylinePointEntity entity = dtoToEntity(dto);
            entity.setWaylineId(waylineId);
            mapper.insert(entity);
        }
    }

    @Override
    public void delPoint(String waylineId) {
        QueryWrapper<WaylinePointEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(WaylinePointEntity::getWaylineId ,waylineId);
        mapper.delete(wrapper);
    }

    @Override
    public List<WaylinePointDTO> getPointByWaylineId(String waylineId) {
        List<WaylinePointDTO> resultList = new ArrayList<>();
        QueryWrapper<WaylinePointEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(WaylinePointEntity::getWaylineId ,waylineId)
                .orderByAsc(WaylinePointEntity::getCreateTime);
        List<WaylinePointEntity> list = mapper.selectList(wrapper);
        resultList = list.stream().map(this::entityToDto)
                .collect(Collectors.toList());
        return resultList;
    }

    private WaylinePointEntity dtoToEntity(WaylinePointDTO dto){
        WaylinePointEntity entity = new WaylinePointEntity();
        entity.setPointIndex(dto.getPointIndex());
        entity.setLatitude(dto.getLatitude());
        entity.setFolderId(dto.getFolderId());
        entity.setLongitude(dto.getLongitude());
        return entity;
    }

    private WaylinePointDTO entityToDto(WaylinePointEntity entity){
        WaylinePointDTO dto = new WaylinePointDTO();
        dto.setPointIndex(entity.getPointIndex());
        dto.setLatitude(entity.getLatitude());
        dto.setFolderId(entity.getFolderId());
        dto.setLongitude(entity.getLongitude());
        dto.setCreateTime(entity.getCreateTime());
        return dto;
    }
}
