package com.fjhx.service.supplier.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.entity.material.Material;
import com.fjhx.entity.supplier.Supplier;
import com.fjhx.entity.supplier.SupplierPrice;
import com.fjhx.mapper.supplier.SupplierPriceMapper;
import com.fjhx.params.supplier.SupplierPriceVo;
import com.fjhx.service.supplier.SupplierPriceService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.wrapperUtil.IWrapper;
import com.fjhx.utils.wrapperUtil.KeywordData;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 供应商价格 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-11-25
 */
@Service
public class SupplierPriceServiceImpl extends ServiceImpl<SupplierPriceMapper, SupplierPrice> implements SupplierPriceService {

    @Override
    public Page<SupplierPrice> getPage(Map<String, Object> condition) {

        IWrapper<SupplierPrice> wrapper = IWrapper.getWrapper(condition);
        wrapper.orderByDesc(Supplier::getId)
                .keyword(new KeywordData("s", Supplier::getName),
                        new KeywordData("m", Material::getName),
                        new KeywordData("m", Material::getCode))
                .eq("s", Supplier::getId, condition.get("supplierId"))
                .eq("m", Material::getId, condition.get("materialId"))
                .like("s", Supplier::getName, condition.get("supplierName"))
                .like("m", Material::getName, condition.get("materialName"))
                .like("m", Material::getCode, condition.get("materialCode"))
                .eq("m", Material::getType, condition.get("materialType"));

        return baseMapper.getPage(createPage(condition), wrapper);
    }

    @Override
    public void add(SupplierPriceVo supplierPriceVo) {
        Long supplierId = supplierPriceVo.getSupplierId();
        Long materialId = supplierPriceVo.getMaterialId();
        BigDecimal price = supplierPriceVo.getPrice();

        Assert.notEmpty(supplierId, "供应商id不能为空");
        Assert.notEmpty(materialId, "物料id不能为空");
        Assert.notEmpty(price, "物料价格不能为空");

        long count = count(q -> q.eq(SupplierPrice::getSupplierId, supplierId).eq(SupplierPrice::getMaterialId, materialId));

        Assert.eqZero(count, "此供应商物料价格已存在");
        save(supplierPriceVo);
    }

    @Override
    public void edit(SupplierPriceVo supplierPriceVo) {
        updateById(supplierPriceVo);
    }

    @Override
    public void delete(SupplierPriceVo supplierPriceVo) {
        removeById(supplierPriceVo.getId());
    }

}
