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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.mail.entity.my.dto.MyTagDto;
import com.fjhx.mail.entity.my.dto.MyTagSelectDto;
import com.fjhx.mail.entity.my.po.MyTag;
import com.fjhx.mail.entity.my.po.MyTagMessage;
import com.fjhx.mail.entity.my.vo.MyTagVo;
import com.fjhx.mail.mapper.my.MyTagMapper;
import com.fjhx.mail.service.my.MyTagMessageService;
import com.fjhx.mail.service.my.MyTagService;
import com.obs.services.internal.ServiceException;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


/**
 * <p>
 * 我的标签 服务实现类
 * </p>
 *
 * @author
 * @since 2023-05-29
 */
@Service
public class MyTagServiceImpl extends ServiceImpl<MyTagMapper, MyTag> implements MyTagService {

    @Autowired
    private MyTagMessageService myTagMessageService;

    @Override
    public Page<MyTagVo> getPage(MyTagSelectDto dto) {
        IWrapper<MyTag> wrapper = getWrapper();
        wrapper.orderByDesc("mt", MyTag::getId);
        Page<MyTagVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

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

    @Override
    public void add(MyTagDto myTagDto) {

        MyTag myTag = getOne(q -> q
                .eq(MyTag::getMailboxId, myTagDto.getMailboxId())
                .eq(MyTag::getName, myTagDto.getName())
        );
        if (myTag != null) {
            throw new ServiceException("标签名称已存在");
        }

        this.save(myTagDto);
    }

    @Override
    public void edit(MyTagDto myTagDto) {
        MyTag myTag = getOne(q -> q
                .ne(BaseIdPo::getId, myTagDto.getId())
                .eq(MyTag::getMailboxId, myTagDto.getMailboxId())
                .eq(MyTag::getName, myTagDto.getName())
        );
        if (myTag != null) {
            throw new ServiceException("标签名称已存在");
        }

        this.updateById(myTagDto);
    }

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

    @Override
    public List<MyTag> getListByMessageId(Long id) {
        if (id == null) {
            throw new ServiceException("邮件id不能为空");
        }

        List<MyTagMessage> list = myTagMessageService.list(q -> q.eq(MyTagMessage::getMessageId, id));
        List<Long> myTagIdList = list.stream().map(MyTagMessage::getMyTagId).collect(Collectors.toList());

        if (myTagIdList.size() == 0) {
            return new ArrayList<>();
        }

        return listByIds(myTagIdList);
    }

}
