package com.njzscloud.dispose.wh.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.common.sn.support.SnUtil;
import com.njzscloud.dispose.wh.mapper.PurchaseRecordMapper;
import com.njzscloud.dispose.wh.pojo.entity.PurchaseRecordEntity;
import com.njzscloud.dispose.wh.pojo.result.PurchaseRecordResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 采购记录
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PurchaseRecordService extends ServiceImpl<PurchaseRecordMapper, PurchaseRecordEntity> implements IService<PurchaseRecordEntity> {

    /**
     * 新增
     */
    public void add(PurchaseRecordEntity purchaseRecordEntity) {
        purchaseRecordEntity.setSn(this.generateSn());
        this.save(purchaseRecordEntity);
    }

    /**
     * 修改
     */
    public void modify(PurchaseRecordEntity purchaseRecordEntity) {
        this.updateById(purchaseRecordEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public PurchaseRecordResult detail(Long id) {
        return baseMapper.detail(id);
    }

    /**
     * 分页查询
     */
    public PageResult<PurchaseRecordResult> paging(PageParam pageParam, PurchaseRecordEntity purchaseRecordEntity) {
        String sn = purchaseRecordEntity.getSn();
        String supplierName = purchaseRecordEntity.getSupplierName();
        String productName = purchaseRecordEntity.getProductName();
        Long handlerId = purchaseRecordEntity.getHandlerId();

        QueryWrapper<?> ew = Wrappers.query()
            .eq("wpr.deleted", Boolean.FALSE)
            .like(StrUtil.isNotBlank(sn), "wpr.sn", sn)
            .like(StrUtil.isNotBlank(supplierName), "wpr.supplier_name", supplierName)
            .like(StrUtil.isNotBlank(productName), "wpr.product_name", productName)
            .eq(handlerId != null, "wpr.handler_id", handlerId);

        IPage<PurchaseRecordResult> page = baseMapper.paging(pageParam.toPage(), ew);
        return PageResult.of(page);
    }

    public String generateSn() {
        String sn = SnUtil.next("PR-SN");
        if (this.exists(Wrappers.<PurchaseRecordEntity>lambdaQuery().eq(PurchaseRecordEntity::getSn, sn)
            .eq(PurchaseRecordEntity::getDeleted, Boolean.FALSE))) {
            this.generateSn();
        }
        return sn;
    }
}
