package com.casic.missiles.service.Impl.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.mapper.business.BusinessOriginalRecordEquipmentRelationMapper;
import com.casic.missiles.model.business.BusinessOriginalRecordEquipmentRelation;
import com.casic.missiles.model.equipment.EquipmentFixedAssets;
import com.casic.missiles.service.business.IBusinessOriginalRecordEquipmentRelationService;
import com.casic.missiles.service.equipment.IEquipmentFixedAssetsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务管理-原始记录-标准装置关联表 服务实现类
 * </p>
 *
 * @author wangpeng
 * @since 2023-02-02
 */
@Service
public class BusinessOriginalRecordEquipmentRelationServiceImpl extends ServiceImpl<BusinessOriginalRecordEquipmentRelationMapper, BusinessOriginalRecordEquipmentRelation> implements IBusinessOriginalRecordEquipmentRelationService {

    @Resource
    IEquipmentFixedAssetsService equipmentFixedAssetsService;

    @Override
    public boolean saveBatch(Long originId, List<EquipmentFixedAssets> equipmentFixedAssetsList) {
        //删除绑定关系
        deleteByOriginId(originId);
        //重新绑定
        List<BusinessOriginalRecordEquipmentRelation> list = new ArrayList<>();
        equipmentFixedAssetsList.forEach(equipmentFixedAssets -> {
            BusinessOriginalRecordEquipmentRelation obj = new BusinessOriginalRecordEquipmentRelation();
            obj.setEquipmentId(equipmentFixedAssets.getId());
            obj.setOriginalRecordId(originId);
            list.add(obj);
        });
        return this.saveBatch(list);
    }

    @Override
    public List<EquipmentFixedAssets> getEquipmentsByOriginalRecordId(Long originId) {
        QueryWrapper<BusinessOriginalRecordEquipmentRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("original_record_id", originId);
        List<BusinessOriginalRecordEquipmentRelation> list = this.baseMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            return equipmentFixedAssetsService.list(list.stream().map(BusinessOriginalRecordEquipmentRelation::getEquipmentId).collect(Collectors.toList()));
        }
        return null;
    }

    @Override
    public Boolean deleteByOriginId(Long originId) {
        QueryWrapper<BusinessOriginalRecordEquipmentRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("original_record_id", originId);
        return this.baseMapper.delete(queryWrapper) > 0 ? true : false;
    }
}
