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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dji.sample.map.dao.IGroupMapper;
import com.dji.sample.map.model.entity.GroupEntity;
import com.dji.sample.map.service.IGroupElementService;
import com.dji.sample.map.service.IGroupService;
import com.dji.sdk.cloudapi.map.GetMapElementsResponse;
import com.dji.sdk.cloudapi.map.GroupTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author sean
 * @version 0.2
 * @date 2021/11/29
 */
@Slf4j
@Service
@Transactional
public class GroupServiceImpl implements IGroupService {

    @Autowired
    private IGroupMapper mapper;

    @Autowired
    private IGroupElementService groupElementService;

    private static final String PILOT_SHARE_LAYER = "默认文件夹";
    private static final String DEFAULT_LAYER = "默认标注";
    private static final String CUSTOM_FLIGHT_AREA = "自定义飞行范围";
    private static final String PICTURE_SHARE_AREA = "图片标注";

    @Override
    public List<GetMapElementsResponse> getAllGroupsByWorkspaceId(String workspaceId, String groupId, Boolean isDistributed) {
        if(StringUtils.hasText(workspaceId)) {
            createDefaultGroups(workspaceId);
        }
        return mapper.selectList(
                new LambdaQueryWrapper<GroupEntity>()
                        .eq(GroupEntity::getWorkspaceId, workspaceId)
                        .eq(StringUtils.hasText(groupId), GroupEntity::getGroupId, groupId)
                        .eq(isDistributed != null, GroupEntity::getIsDistributed, isDistributed)
                        .eq(GroupEntity::getEnabled,true))
                .stream()
                .map(this::entityConvertToDto)
                .collect(Collectors.toList());
    }

    private void createDefaultGroups(String workspaceId) {
        int count = mapper.selectCount(new LambdaQueryWrapper<GroupEntity>()
                .eq(GroupEntity::getWorkspaceId, workspaceId));
        if(count <= 0 && StringUtils.hasText(workspaceId)) {
            log.info("========创建默认文件夹=============workspaceId:" + workspaceId);
            //创建默认文件夹
            mapper.insert(GroupEntity.builder().groupId(UUID.randomUUID().toString())
                    .groupName(PILOT_SHARE_LAYER)
                    .groupType(GroupTypeEnum.SHARED.getType())
                    .workspaceId(workspaceId)
                    .createTime(System.currentTimeMillis())
                    .updateTime(System.currentTimeMillis())
                    .build());
            //创建图片标注文件夹
            mapper.insert(GroupEntity.builder().groupId(UUID.randomUUID().toString())
                    .groupName(PICTURE_SHARE_AREA)
                    .groupType(GroupTypeEnum.PICTURE.getType())
                    .workspaceId(workspaceId)
                    .createTime(System.currentTimeMillis())
                    .updateTime(System.currentTimeMillis())
                    .build());

            //创建默认标注文件夹
            mapper.insert(GroupEntity.builder().groupId(UUID.randomUUID().toString())
                    .groupName(DEFAULT_LAYER)
                    .groupType(GroupTypeEnum.DEFAULT.getType())
                    .workspaceId(workspaceId)
                    .createTime(System.currentTimeMillis())
                    .updateTime(System.currentTimeMillis())
                    .enabled(false)
                    .build());

            //创建自定义飞行范围文件夹
            mapper.insert(GroupEntity.builder().groupId(UUID.randomUUID().toString())
                    .groupName(CUSTOM_FLIGHT_AREA)
                    .groupType(GroupTypeEnum.CUSTOM.getType())
                    .workspaceId(workspaceId)
                    .createTime(System.currentTimeMillis())
                    .updateTime(System.currentTimeMillis())
                    .enabled(false)
                    .build());
        }
    }

    @Override
    public Optional<GetMapElementsResponse> getGroupByWorkspaceId(String workspaceId, GroupTypeEnum groupType) {
        return Optional.ofNullable(mapper.selectOne(
                Wrappers.lambdaQuery(GroupEntity.class)
                        .eq(GroupEntity::getWorkspaceId, workspaceId)
                        .eq(GroupEntity::getGroupType, groupType.getType())
                        .last(" limit 1")))
                .map(this::entityConvertToDto);
    }

    /**
     * Convert database entity objects into group data transfer object.
     * @param entity
     * @return
     */
    private GetMapElementsResponse entityConvertToDto(GroupEntity entity) {
        if (entity == null) {
            return null;
        }

        return new GetMapElementsResponse()
                .setId(entity.getGroupId())
                .setName(entity.getGroupName())
                .setType(GroupTypeEnum.find(entity.getGroupType()))
                .setLock(entity.getIsLock());
    }
}
