package cn.iocoder.yudao.module.asset.service.supplier;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.asset.controller.admin.supplier.vo.SupplierPageReqVO;
import cn.iocoder.yudao.module.asset.controller.admin.supplier.vo.SupplierSaveReqVO;
import cn.iocoder.yudao.module.asset.convert.supplier.SupplierConvert;
import cn.iocoder.yudao.module.asset.dal.dataobject.supplier.SupplierDO;
import cn.iocoder.yudao.module.asset.dal.mysql.supplier.SupplierMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.asset.enums.ErrorCodeConstants.SUPPLIER_NOT_EXISTS;

/**
 * 供应商信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class SupplierServiceImpl implements SupplierService {

    @Resource
    private SupplierMapper supplierMapper;

    @Override
    public Long createSupplier(SupplierSaveReqVO createReqVO) {
        // 插入
        SupplierDO supplier = SupplierConvert.INSTANCE.convert(createReqVO);
        supplierMapper.insert(supplier);

        log.info("[createSupplier][创建供应商成功，ID：{}，供应商编码：{}，供应商名称：{}]",
                supplier.getId(), supplier.getSupplierCode(), supplier.getSupplierName());

        return supplier.getId();
    }

    @Override
    public void updateSupplier(SupplierSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierExists(updateReqVO.getId());

        // 更新
        SupplierDO updateObj = SupplierConvert.INSTANCE.convert(updateReqVO);
        supplierMapper.updateById(updateObj);

        log.info("[updateSupplier][更新供应商成功，ID：{}，供应商编码：{}，供应商名称：{}]",
                updateObj.getId(), updateObj.getSupplierCode(), updateObj.getSupplierName());
    }

    @Override
    public void deleteSupplier(Long id) {
        // 校验存在
        validateSupplierExists(id);

        // 删除
        supplierMapper.deleteById(id);

        log.info("[deleteSupplier][删除供应商成功，ID：{}]", id);
    }

    private void validateSupplierExists(Long id) {
        if (supplierMapper.selectById(id) == null) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
    }

    @Override
    public SupplierDO getSupplier(Long id) {
        return supplierMapper.selectById(id);
    }

    @Override
    public PageResult<SupplierDO> getSupplierPage(SupplierPageReqVO pageReqVO) {
        return supplierMapper.selectPage(pageReqVO);
    }

}
