package vip.xiaonuo.quality.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.quality.entity.QualityReagentStock;
import vip.xiaonuo.quality.mapper.QualityReagentStockMapper;
import vip.xiaonuo.quality.param.QualityStockPageParam;
import vip.xiaonuo.quality.service.IQualityReagentStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 质量试剂仓库 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-10
 */
@Service
public class QualityReagentStockServiceImpl extends ServiceImpl<QualityReagentStockMapper, QualityReagentStock> implements IQualityReagentStockService {

    @Autowired
    private QualityReagentStockMapper stockMapper;

    @Override
    public Page<QualityReagentStock> page(QualityStockPageParam stockPageParam) {
        String orgId = stockPageParam.getOrgId();
        Integer pageNum = stockPageParam.getPageNum();
        Integer pageSize = stockPageParam.getPageSize();
        Page<QualityReagentStock> page = new Page<>(pageNum, pageSize);
        QueryWrapper<QualityReagentStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(orgId), "org_id", orgId);
        return stockMapper.selectPage(page,queryWrapper);
    }

    @Override
    public CommonResult add(QualityReagentStock qualityReagentStock) {
        String orgId = qualityReagentStock.getOrgId();
        String reagent = qualityReagentStock.getReagent();
        if ("".equals(orgId) || null == orgId) {
            return CommonResult.error();
        }
        QueryWrapper<QualityReagentStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId).eq("reagent", reagent);
        QualityReagentStock reagentStock = stockMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(reagentStock)) {
            stockMapper.insert(qualityReagentStock);
        } else {
            return CommonResult.error();
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult edit(QualityReagentStock qualityReagentStock) {
        QueryWrapper<QualityReagentStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", qualityReagentStock.getOrgId()).eq("reagent", qualityReagentStock.getReagent())
                .ne("id", qualityReagentStock.getId());
        QualityReagentStock reagentStock = stockMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(reagentStock)) {
            stockMapper.updateById(qualityReagentStock);
        } else {
            return CommonResult.error();
        }
        return CommonResult.ok();
    }
}
