package com.fjhx.mail.service.my.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.mail.entity.my.dto.MyFolderDto;
import com.fjhx.mail.entity.my.dto.MyFolderSelectDto;
import com.fjhx.mail.entity.my.po.MyFolder;
import com.fjhx.mail.entity.my.vo.MyFolderVo;
import com.fjhx.mail.mapper.my.MyFolderMapper;
import com.fjhx.mail.service.my.MyFolderService;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.utils.TreeUtil;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 我的文件夹 服务实现类
 * </p>
 *
 * @author
 * @since 2023-05-29
 */
@Service
public class MyFolderServiceImpl extends ServiceImpl<MyFolderMapper, MyFolder> implements MyFolderService {

    @Override
    public List<JSONObject> tree(MyFolderSelectDto dto) {
        List<MyFolder> list = list(q -> q.eq(MyFolder::getMailboxId, dto.getMailboxId()));
        return TreeUtil.buildTree("name", list);
    }

    @Override
    public MyFolderVo detail(Long id) {
        MyFolder MyFolder = this.getById(id);
        MyFolderVo result = BeanUtil.toBean(MyFolder, MyFolderVo.class);
        return result;
    }

    @Override
    public void add(MyFolderDto myFolderDto) {
        if (myFolderDto.getParentId() == null) {
            myFolderDto.setParentId(0L);
        }

        MyFolder myFolder = getOne(q -> q
                .eq(MyFolder::getMailboxId, myFolderDto.getMailboxId())
                .eq(MyFolder::getParentId, myFolderDto.getParentId())
                .eq(MyFolder::getName, myFolderDto.getName())
        );
        if (myFolder != null) {
            throw new ServiceException("文件夹名称已存在");
        }

        this.save(myFolderDto);
    }

    @Override
    public void edit(MyFolderDto myFolderDto) {
        Long id = myFolderDto.getId();
        if (id == null) {
            throw new ServiceException("文件夹id不能为空");
        }

        MyFolder myFolder = getOne(q -> q
                .eq(MyFolder::getParentId, myFolderDto.getParentId())
                .eq(MyFolder::getName, myFolderDto.getName())
                .ne(BaseIdPo::getId, myFolderDto.getId())
        );
        if (myFolder != null) {
            throw new ServiceException("文件夹名称已存在");
        }

        this.updateById(myFolderDto);
    }

    @Override
    public void delete(Long id) {
        this.removeById(id);
    }

}
