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.MyContactPersonDto;
import com.fjhx.mail.entity.my.dto.MyContactPersonSelectDto;
import com.fjhx.mail.entity.my.po.MyContactPerson;
import com.fjhx.mail.entity.my.vo.MyContactPersonVo;
import com.fjhx.mail.mapper.my.MyContactPersonMapper;
import com.fjhx.mail.service.my.MyContactPersonService;
import com.ruoyi.common.core.domain.BaseIdPo;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import org.springframework.stereotype.Service;


/**
 * <p>
 * 联系人 服务实现类
 * </p>
 *
 * @author
 * @since 2023-06-09
 */
@Service
public class MyContactPersonServiceImpl extends ServiceImpl<MyContactPersonMapper, MyContactPerson> implements MyContactPersonService {

    @Override
    public Page<MyContactPersonVo> getPage(MyContactPersonSelectDto dto) {
        IWrapper<MyContactPerson> wrapper = getWrapper();
        wrapper.eq("mcp", MyContactPerson::getCreateUser, SecurityUtils.getUserId());
        wrapper.orderByDesc("mcp", MyContactPerson::getId);
        Page<MyContactPersonVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);
        return page;
    }

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

    @Override
    public void add(MyContactPersonDto myContactPersonDto) {
        long count = count(q -> q
                .eq(MyContactPerson::getName, myContactPersonDto.getName())
                .eq(BasePo::getCreateUser, SecurityUtils.getUserId())
                .last("limit 1")
        );
        if (count > 0) {
            throw new ServiceException("联系人已存在");
        }

        this.save(myContactPersonDto);
    }

    @Override
    public void edit(MyContactPersonDto myContactPersonDto) {
        long count = count(q -> q
                .ne(BaseIdPo::getId, myContactPersonDto.getId())
                .eq(MyContactPerson::getName, myContactPersonDto.getName())
                .eq(BasePo::getCreateUser, SecurityUtils.getUserId())
                .last("limit 1")
        );
        if (count > 0) {
            throw new ServiceException("联系人已存在");
        }
        this.updateById(myContactPersonDto);
    }

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

}
