package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shkj.common.core.domain.Result;
import com.shkj.common.utils.SecurityUtils;
import com.shkj.wms.bo.BaseMoldBarcodeAddBo;
import com.shkj.wms.domain.BaseMoldBarcode;
import com.shkj.wms.enums.YesAndNoEnum;
import com.shkj.wms.mapper.BaseMoldBarcodeMapper;
import com.shkj.wms.service.IBaseMoldBarcodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 模具条码Service业务层处理
 *
 * @author lch
 * @date 2023-06-02
 */
@Slf4j
@Service
public class BaseMoldBarcodeServiceImpl extends ServiceImpl<BaseMoldBarcodeMapper, BaseMoldBarcode> implements IBaseMoldBarcodeService {


    /**
     * 根据新增业务对象插入模具条码
     *
     * @param bo 模具条码新增业务对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<BaseMoldBarcode> addMoldBarcode(BaseMoldBarcodeAddBo bo) {
        BaseMoldBarcode add = BeanUtil.toBean(bo, BaseMoldBarcode.class);

        //根据规则生成条码code == 模具编码+"-" + 自增数 01  存在则加1
        LambdaQueryWrapper<BaseMoldBarcode> wrapper = new LambdaQueryWrapper<BaseMoldBarcode>()
                .eq(BaseMoldBarcode::getMoldId, bo.getMoldId())
                .orderByDesc(BaseMoldBarcode::getId)
                .last("limit 1");
        BaseMoldBarcode one = getOne(wrapper);
        String code = bo.getMoldNo() + "-" + "01";
        if (one != null) {
            String[] split = one.getMoldBarcode().split("-");
            Integer num = Integer.parseInt(split[split.length - 1]) + 1;
            code = bo.getMoldNo() + "-" + (num > 9 ? String.valueOf(num) : ("0" + num));
        }
        add.setMoldBarcode(code);
        add.setIsActivity(YesAndNoEnum.YES.getValue());
        add.setBranchId(SecurityUtils.getCurrentBranchId());
        this.save(add);
        return Result.ok().data(add);
    }

    /**
     * 查询模具条码列表
     *
     * @param moldBarcodeList 模具条码列表
     * @return {@code BaseMoldBarcode}
     */
    @Override
    public List<BaseMoldBarcode> queryByMoldBarcodeList(List<String> moldBarcodeList) {
        LambdaQueryWrapper<BaseMoldBarcode> wrapper = new LambdaQueryWrapper<BaseMoldBarcode>()
                .in(BaseMoldBarcode::getMoldBarcode, moldBarcodeList);
        return this.list(wrapper);
    }

    /**
     * 查询模具条形码
     *
     * @param moldBarcode 模具条形码
     * @return {@code BaseMoldBarcode}
     */
    @Override
    public BaseMoldBarcode queryByMoldBarcode(String moldBarcode) {
        LambdaQueryWrapper<BaseMoldBarcode> wrapper = new LambdaQueryWrapper<BaseMoldBarcode>()
                .eq(BaseMoldBarcode::getMoldBarcode, moldBarcode);
        BaseMoldBarcode barcode = this.getOne(wrapper);
        return barcode;
    }
}
