package com.xjrsoft.module.material.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.module.material.dto.AddMaterialTypeAssignDto;
import com.xjrsoft.module.material.dto.MaterialAssignUserDto;
import com.xjrsoft.module.material.entity.MaterialTypeAssign;
import com.xjrsoft.module.material.mapper.MaterialTypeAssignMapper;
import com.xjrsoft.module.material.service.IMaterialTypeAssignService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@AllArgsConstructor
public class MaterialTypeAssignServiceImpl extends MPJBaseServiceImpl<MaterialTypeAssignMapper, MaterialTypeAssign> implements IMaterialTypeAssignService {
    private final MaterialTypeAssignMapper materialTypeMaterialTypeAssignMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(AddMaterialTypeAssignDto addMaterialTypeAssignDto) {

        if (addMaterialTypeAssignDto.getUserList() != null && addMaterialTypeAssignDto.getUserList().size() > 0) {
            List<MaterialTypeAssign> materialTypeAssignList = materialTypeMaterialTypeAssignMapper.selectList(Wrappers.<MaterialTypeAssign>query().lambda()
                    .eq(MaterialTypeAssign::getMaterialTypeId, addMaterialTypeAssignDto.getMaterialTypeId()));
            for (MaterialAssignUserDto addMaterialTypeAssignUserDto : addMaterialTypeAssignDto.getUserList()) {
                Optional<MaterialTypeAssign> materialTypeAssignAny = materialTypeAssignList.stream().filter(item -> item.getUserId().equals(addMaterialTypeAssignUserDto.getUserId()) ).findAny();
                if (!materialTypeAssignAny.isPresent()) {
                    MaterialTypeAssign materialTypeAssign = new MaterialTypeAssign();
                    materialTypeAssign.setMaterialTypeId(addMaterialTypeAssignDto.getMaterialTypeId());
                    materialTypeAssign.setUserId(addMaterialTypeAssignUserDto.getUserId());
                    materialTypeAssign.setUserType(addMaterialTypeAssignUserDto.getUserType());
                    materialTypeAssign.setUserNumber(addMaterialTypeAssignUserDto.getUserNumber());
                    materialTypeMaterialTypeAssignMapper.insert(materialTypeAssign);
                }
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(List<Long> ids) {
        materialTypeMaterialTypeAssignMapper.deleteBatchIds(ids);
        return true;
    }
}
