package com.yc.ship.module.otc.service.link;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.otc.controller.admin.link.detail.LinkDetailSaveReqVO;
import com.yc.ship.module.otc.dal.dataobject.link.LinkDetailDO;
import com.yc.ship.module.otc.dal.mysql.link.LinkDetailMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.module.otc.enums.ErrorCodeConstants.LINK_DETAIL_NOT_EXISTS;

/**
 * 链接扩展明细 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class LinkDetailServiceImpl implements LinkDetailService {

    @Resource
    private LinkDetailMapper linkDetailMapper;

    @Override
    public Long createLinkDetail(LinkDetailSaveReqVO createReqVO) {
        // 插入
        LinkDetailDO linkDetail = BeanUtils.toBean(createReqVO, LinkDetailDO.class);
        linkDetail.setId(IdWorker.getId(linkDetail));
        linkDetailMapper.insert(linkDetail);
        // 返回
        return linkDetail.getId();
    }

    @Override
    public void updateLinkDetail(LinkDetailSaveReqVO updateReqVO) {
        // 校验存在
        validateLinkDetailExists(updateReqVO.getId());
        // 更新
        LinkDetailDO updateObj = BeanUtils.toBean(updateReqVO, LinkDetailDO.class);
        linkDetailMapper.updateById(updateObj);
    }

    @Override
    public void deleteLinkDetail(Long id) {
        // 校验存在
        validateLinkDetailExists(id);
        // 删除
        linkDetailMapper.deleteById(id);
    }

    @Override
    public void deleteLinkDetailByLinkId(Long linkId) {
        linkDetailMapper.delete(LinkDetailDO::getLinkId, linkId);
    }

    private void validateLinkDetailExists(Long id) {
        if (linkDetailMapper.selectById(id) == null) {
            throw exception(LINK_DETAIL_NOT_EXISTS);
        }
    }

    @Override
    public LinkDetailDO getLinkDetail(Long id) {
        return linkDetailMapper.selectById(id);
    }

    @Override
    public List<LinkDetailDO> getLinkDetailByLinkId(Long linkId) {
        return linkDetailMapper.getLinkDetailByLinkId(linkId);
    }

}
