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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
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.core.ex.Exceptions;
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.CraftMapper;
import com.njzscloud.dispose.mfg.craft.pojo.entity.CraftEntity;
import com.njzscloud.dispose.mfg.craft.pojo.param.AddCraftParam;
import com.njzscloud.dispose.mfg.craft.pojo.param.SearchCraftParam;
import com.njzscloud.dispose.mfg.craft.pojo.result.SearchCraftResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 工艺
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CraftService extends ServiceImpl<CraftMapper, CraftEntity> implements IService<CraftEntity> {

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(AddCraftParam addCraftParam) {
        List<CraftEntity> list = this.list(Wrappers.<CraftEntity>lambdaQuery().eq(CraftEntity::getGoodsId, addCraftParam.getGoodsId()));

        Optional<CraftEntity> optionalCraft = list.stream().filter(item -> item.getCraftVer().equals(addCraftParam.getCraftVer())).findFirst();
        Assert.isFalse(optionalCraft.isPresent(), () -> Exceptions.exception("工艺版本号已存在"));

        /* if (addCraftParam.getCanuse()) {
            updateBatchById(list.stream().map(item -> item.setCanuse(false)).toList());
        } */


        this.save(BeanUtil.copyProperties(addCraftParam, CraftEntity.class)
            .setSn(SnUtil.next("Craft-SN"))
        );
    }

    /**
     * 修改
     */
    public void modify(CraftEntity craftEntity) {
        this.updateById(craftEntity);
    }

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

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

    /**
     * 分页查询
     */
    public PageResult<SearchCraftResult> paging(PageParam pageParam, SearchCraftParam searchCraftParam) {
        return PageResult.of(baseMapper.paging(pageParam.toPage(), Wrappers.query()));
    }

    public void disable(Long id, Boolean disable) {
        this.updateById(new CraftEntity().setId(id).setCanuse(disable));
    }
}
