package com.fjhx.material.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.entity.material.MaterialCategory;
import com.fjhx.material.mapper.MaterialCategoryMapper;
import com.fjhx.material.service.MaterialCategoryService;
import com.fjhx.params.material.EditMaterialCategoryVo;
import com.fjhx.utils.Assert;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 物料分类 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-11-23
 */
@Service
public class MaterialCategoryServiceImpl extends ServiceImpl<MaterialCategoryMapper, MaterialCategory> implements MaterialCategoryService {

    @Override
    public boolean edit(EditMaterialCategoryVo editMaterialCategoryVo) {

        MaterialCategory materialCategory = new MaterialCategory();

        String code = editMaterialCategoryVo.getCode();
        Assert.notEmpty(code, "分类编码不能为空");

        materialCategory.setCode(editMaterialCategoryVo.getCode());
        materialCategory.setName(editMaterialCategoryVo.getName());
        materialCategory.setParentCode(editMaterialCategoryVo.getParentCode());

        MaterialCategory oldMaterialCategory = getOne(Wrappers.<MaterialCategory>lambdaQuery()
                .eq(MaterialCategory::getCode, editMaterialCategoryVo.getCode())
                .last("limit 1")
        );

        Date date = new Date();

        switch (editMaterialCategoryVo.getType()) {
            case 1:
                Assert.empty(oldMaterialCategory, "新增失败，分类编码已存在");
                materialCategory.setIsDelete(0);
                materialCategory.setCreatedTime(date);
                materialCategory.setUpdatedTime(date);
                materialCategory.setIsForChose(0);
                return save(materialCategory);
            case 2:
                Assert.notEmpty(oldMaterialCategory, "编辑失败，分类编码不存在");
                materialCategory.setId(oldMaterialCategory.getId());
                materialCategory.setUpdatedTime(date);
                return updateById(materialCategory);
            case 3:
                Assert.notEmpty(oldMaterialCategory, "删除失败，分类编码不存在");
                return removeById(oldMaterialCategory.getId());
            default:
                return false;
        }
    }
}
