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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.mail.config.MailServiceConfig;
import com.fjhx.mail.entity.personal.dto.PersonalMailboxDto;
import com.fjhx.mail.entity.personal.dto.PersonalMailboxSelectDto;
import com.fjhx.mail.entity.personal.po.PersonalMailbox;
import com.fjhx.mail.entity.personal.vo.PersonalMailboxVo;
import com.fjhx.mail.mapper.personal.PersonalMailboxMapper;
import com.fjhx.mail.service.personal.PersonalMailboxService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


/**
 * <p>
 * 个人邮箱 服务实现类
 * </p>
 *
 * @author
 * @since 2023-04-06
 */
@Service
public class PersonalMailboxServiceImpl extends ServiceImpl<PersonalMailboxMapper, PersonalMailbox> implements PersonalMailboxService {

    @Override
    public Page<PersonalMailboxVo> getPage(PersonalMailboxSelectDto dto) {
        IWrapper<PersonalMailbox> wrapper = getWrapper();
        wrapper.eq("pm", PersonalMailbox::getUserId, SecurityUtils.getUserId());
        wrapper.keyword(dto, new SqlField("pm", PersonalMailbox::getMailUser));
        wrapper.orderByDesc("pm", PersonalMailbox::getId);
        Page<PersonalMailboxVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject add(PersonalMailboxDto personalMailboxDto) {
        personalMailboxDto.setCreateUser(SecurityUtils.getUserId());
        personalMailboxDto.setUpdateUser(SecurityUtils.getUserId());
        personalMailboxDto.setUserId(SecurityUtils.getUserId());
        personalMailboxDto.setTenantId(SecurityUtils.getTenantId());
        String urlPrefix;
        if (Objects.equals(personalMailboxDto.getType(), 2)) {
            urlPrefix = MailServiceConfig.abroadUrlPrefix;
        } else {
            urlPrefix = MailServiceConfig.urlPrefix;
        }

        String post = HttpUtil.post(urlPrefix + "addPersonalMailbox", JSON.toJSONString(personalMailboxDto));
        return JSON.parseObject(post);
    }

    @Override
    public void edit(PersonalMailboxDto personalMailboxDto) {
        this.updateById(personalMailboxDto);
    }

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

}
