package com.njzscloud.dispose.mfg.craft.service;

import cn.hutool.core.util.StrUtil;
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.mfg.craft.mapper.CraftOperationMapper;
import com.njzscloud.dispose.mfg.craft.pojo.entity.CraftOperationEntity;
import com.njzscloud.dispose.mfg.craft.pojo.param.SearchCraftOperationParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 工序
 *
 * @author ljw
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CraftOperationService extends ServiceImpl<CraftOperationMapper, CraftOperationEntity> implements IService<CraftOperationEntity> {

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

    /**
     * 修改
     */
    public void modify(CraftOperationEntity craftOperationEntity) {
        this.updateById(craftOperationEntity);
    }

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

    /**
     * 详情
     */
    public CraftOperationEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<CraftOperationEntity> paging(PageParam pageParam, SearchCraftOperationParam operationParam) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<CraftOperationEntity>lambdaQuery()
            .like(StrUtil.isNotBlank(operationParam.getSn()), CraftOperationEntity::getSn, operationParam.getSn())
            .like(StrUtil.isNotBlank(operationParam.getOperationName()), CraftOperationEntity::getOperationName, operationParam.getOperationName())
            .eq(operationParam.getCheckPoint() != null, CraftOperationEntity::getCheckPoint, operationParam.getCheckPoint())
            .eq(operationParam.getCanuse() != null, CraftOperationEntity::getCanuse, operationParam.getCanuse())));
    }

    /**
     * 生成编码
     *
     * @return sn 编码
     */
    public String generateSn() {
        String sn = SnUtil.next("Operation-SN");
        if (this.exists(Wrappers.<CraftOperationEntity>lambdaQuery().eq(CraftOperationEntity::getSn, sn).eq(CraftOperationEntity::getDeleted, Boolean.FALSE))) {
            this.generateSn();
        }
        return sn;
    }

}
