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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.manage.dao.IWorkspaceMapper;
import com.dji.sample.manage.model.dto.WorkspaceDTO;
import com.dji.sample.manage.model.entity.UserEntity;
import com.dji.sample.manage.model.entity.WorkspaceEntity;
import com.dji.sample.manage.model.param.searchParam.WorkspaceSearchParam;
import com.dji.sample.manage.service.IUserService;
import com.dji.sample.manage.service.IWorkspaceService;
import com.dji.sdk.common.Pagination;
import com.dji.sdk.common.PaginationData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

@Service
@Transactional
public class WorkspaceServiceImpl extends ServiceImpl<IWorkspaceMapper, WorkspaceEntity> implements IWorkspaceService {

    @Autowired
    private IWorkspaceMapper mapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    @Lazy
    private IUserService userService;


    @Override
    public Optional<WorkspaceDTO> getWorkspaceByWorkspaceId(String workspaceId) {
        return Optional.ofNullable(entityConvertToDto(
                mapper.selectOne(
                        new LambdaQueryWrapper<WorkspaceEntity>()
                                .eq(WorkspaceEntity::getWorkspaceId, workspaceId))));
    }

    @Override
    public Optional<WorkspaceDTO> getWorkspaceNameByBindCode(String bindCode) {
        return Optional.ofNullable(entityConvertToDto(
                mapper.selectOne(new LambdaQueryWrapper<WorkspaceEntity>().eq(WorkspaceEntity::getBindCode, bindCode))));
    }

    @Override
    public PaginationData<WorkspaceDTO> getWorkspacePage(WorkspaceSearchParam param, Long page, Long pageSize) {

        LambdaQueryWrapper<WorkspaceEntity> workspaceQueryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(param.getRoleWorkspaceId())) {
            workspaceQueryWrapper.eq(WorkspaceEntity::getWorkspaceId, param.getRoleWorkspaceId());
        }

        if (StringUtils.hasText(param.getWorkspaceId())) {
            workspaceQueryWrapper.eq(WorkspaceEntity::getWorkspaceId, param.getWorkspaceId());
        }

        // 增加查询内容
        if (StringUtils.hasText(param.getWorkspaceName())) {
            workspaceQueryWrapper.like(WorkspaceEntity::getWorkspaceName, param.getWorkspaceName());
        }
        if (StringUtils.hasText(param.getWorkspaceDesc())) {
            workspaceQueryWrapper.like(WorkspaceEntity::getWorkspaceDesc, param.getWorkspaceDesc());
        }
        if (StringUtils.hasText(param.getPlatformName())) {
            workspaceQueryWrapper.like(WorkspaceEntity::getPlatformName, param.getPlatformName());
        }
        if (StringUtils.hasText(param.getBindCode())) {
            workspaceQueryWrapper.eq(WorkspaceEntity::getBindCode, param.getBindCode());
        }



        Page<WorkspaceEntity> pagination = this.page(new Page<>(page, pageSize), workspaceQueryWrapper);
        List<WorkspaceDTO> workspaceDTOList = pagination.getRecords().stream()
                .map(this::entityConvertToDto)
                //.peek(fleet -> {})
                .collect(Collectors.toList());
        return new PaginationData<>(workspaceDTOList, new Pagination(pagination.getCurrent(), pagination.getSize(), pagination.getTotal()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public WorkspaceDTO addWorkspace(WorkspaceDTO workspaceDTO) {

        WorkspaceEntity addWorkspace = new WorkspaceEntity();

        // 绑定码 不能重复
        String bindCode = workspaceDTO.getBindCode();
        if (!StringUtils.hasText(bindCode)) {
            throw new RuntimeException("bindCode can't be null");
        }
        // 查询
        LambdaQueryWrapper<WorkspaceEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkspaceEntity::getBindCode, bindCode);
        List<WorkspaceEntity> bingCodeList = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(bingCodeList)) {
            throw new RuntimeException("bindCode is already exit");
        }

        addWorkspace.setWorkspaceId(UUID.randomUUID().toString());
        addWorkspace.setWorkspaceName(workspaceDTO.getWorkspaceName());
        addWorkspace.setWorkspaceDesc(workspaceDTO.getWorkspaceDesc());
        addWorkspace.setPlatformName(workspaceDTO.getPlatformName());
        addWorkspace.setBindCode(workspaceDTO.getBindCode());

        // 新增workspace管理员
        UserEntity workspaceAdmin = new UserEntity();
        workspaceAdmin.setWorkspaceId(addWorkspace.getWorkspaceId());
        workspaceAdmin.setOrgId(addWorkspace.getOrgId());
        workspaceAdmin.setUsername(workspaceDTO.getAdminUserName());
        workspaceAdmin.setPassword(workspaceDTO.getAdminUserPassword());
        UserEntity saveAdmin = userService.addWorkspaceAdminUser(workspaceAdmin);

        addWorkspace.setAdminUserId(saveAdmin.getUserId());
        boolean addWorksapceRes = this.save(addWorkspace);

        WorkspaceDTO entityConvertToDto = entityConvertToDto(addWorkspace);
        return entityConvertToDto;
    }

    @Override
    public boolean editWorkspace(WorkspaceDTO workspaceDTO) {

        if (workspaceDTO.getId() == null && !StringUtils.hasText(workspaceDTO.getWorkspaceId())) {
            throw new RuntimeException("id and workspaceId is null");
        }

        WorkspaceEntity editWorkspace = new WorkspaceEntity();

        LambdaQueryWrapper<WorkspaceEntity> queryDbWrapper = new LambdaQueryWrapper<>();
        if (workspaceDTO.getId() != null) {
            queryDbWrapper.eq(WorkspaceEntity::getId, workspaceDTO.getId());
        } else {
            queryDbWrapper.eq(WorkspaceEntity::getWorkspaceId, workspaceDTO.getWorkspaceId());
        }
        WorkspaceEntity dbWorkspace = this.getOne(queryDbWrapper);

        LambdaUpdateWrapper<WorkspaceEntity> updateWrapper = new LambdaUpdateWrapper<>();
        if (workspaceDTO.getId() != null) {
            updateWrapper.eq(WorkspaceEntity::getId, workspaceDTO.getId());
        } else {
            updateWrapper.eq(WorkspaceEntity::getWorkspaceId, workspaceDTO.getWorkspaceId());
        }

        // 绑定码 不能重复
        String bindCode = workspaceDTO.getBindCode();
        if (StringUtils.hasText(bindCode)) {
            if (!bindCode.equals(dbWorkspace.getBindCode())) {
                // 查询
                LambdaQueryWrapper<WorkspaceEntity> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WorkspaceEntity::getBindCode, bindCode);
                List<WorkspaceEntity> bingCodeList = this.list(queryWrapper);
                if (!CollectionUtils.isEmpty(bingCodeList)) {
                    throw new RuntimeException("bindCode is already exit");
                }
            }
            updateWrapper.set(WorkspaceEntity::getBindCode, bindCode);
        }

        // 修改 名称
        if (StringUtils.hasText(workspaceDTO.getWorkspaceName())) {
            updateWrapper.set(WorkspaceEntity::getWorkspaceName, workspaceDTO.getWorkspaceName());
        }
        // 修改 描述
        if (StringUtils.hasText(workspaceDTO.getWorkspaceDesc())) {
            updateWrapper.set(WorkspaceEntity::getWorkspaceDesc, workspaceDTO.getWorkspaceDesc());
        }
        // 修改 platform_name
        if (StringUtils.hasText(workspaceDTO.getPlatformName())) {
            updateWrapper.set(WorkspaceEntity::getPlatformName, workspaceDTO.getPlatformName());
        }

        boolean update = this.update(updateWrapper);

        return update;
    }

    @Override
    public boolean delWorkspaceById(Integer id) {

        if (id == null) {
            throw new RuntimeException("id is null");
        }

        boolean remove = this.removeById(id);

        return remove;
    }

    @Override
    public boolean delWorkspaceByWorkspaceId(String workspaceId) {

        if (StringUtils.hasText(workspaceId)) {
            throw new RuntimeException("workspaceId is null");
        }

        LambdaQueryWrapper<WorkspaceEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkspaceEntity::getWorkspaceId, workspaceId);
        boolean remove = this.remove(wrapper);

        return remove;
    }

    @Override
    public WorkspaceDTO getWorkspace(WorkspaceSearchParam param) {

        LambdaQueryWrapper<WorkspaceEntity> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(param.getRoleWorkspaceId())) {
            wrapper.eq(WorkspaceEntity::getWorkspaceId, param.getRoleWorkspaceId());
        }

        String workSpaceId = param.getWorkspaceId();
        if (StringUtils.hasText(workSpaceId)) {
            wrapper.eq(WorkspaceEntity::getWorkspaceId, workSpaceId);
        }
        Integer id = param.getId();
        if (id != null) {
            wrapper.eq(WorkspaceEntity::getId, id);
        }

        WorkspaceEntity workspaceEntity = this.getOne(wrapper);

        WorkspaceDTO workspaceDTO = this.entityConvertToDto(workspaceEntity);

        return workspaceDTO;
    }

    /**
     * Convert database entity objects into workspace data transfer object.
     * @param entity
     * @return
     */
    private WorkspaceDTO entityConvertToDto(WorkspaceEntity entity) {
        if (entity == null) {
            return null;
        }
        LambdaQueryWrapper<UserEntity> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(UserEntity::getUserId, entity.getAdminUserId());
        UserEntity adminUser = userService.getOne(userWrapper);

        return WorkspaceDTO.builder()
                .id(entity.getId())
                .workspaceId(entity.getWorkspaceId())
                .platformName(entity.getPlatformName())
                .workspaceDesc(entity.getWorkspaceDesc())
                .workspaceName(entity.getWorkspaceName())
                .bindCode(entity.getBindCode())
                .adminUserId(entity.getAdminUserId())
                .adminUserName(adminUser != null ? adminUser.getUsername() : null)
                .build();
    }
}
