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.BusinessOriginalRecordFileRelationMapper;
import com.casic.missiles.model.business.BusinessOriginalRecordFileRelation;
import com.casic.missiles.model.meter.MeterFile;
import com.casic.missiles.service.business.IBusinessOriginalRecordFileRelationService;
import com.casic.missiles.service.meter.IMeterFileService;
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 BusinessOriginalRecordFileRelationServiceImpl extends ServiceImpl<BusinessOriginalRecordFileRelationMapper, BusinessOriginalRecordFileRelation> implements IBusinessOriginalRecordFileRelationService {

    @Resource
    private IMeterFileService meterFileService;

    @Override
    public boolean saveBatch(Long originId, List<MeterFile> meterFileList) {
        //先删除所有的绑定关系
        deleteByOriginId(originId);
        //新写入绑定关系
        List<BusinessOriginalRecordFileRelation> list = new ArrayList<>();
        meterFileList.forEach(meterFile -> {
            BusinessOriginalRecordFileRelation businessOriginalRecordFileRelation = new BusinessOriginalRecordFileRelation();
            businessOriginalRecordFileRelation.setOriginalRecordId(originId);
            businessOriginalRecordFileRelation.setFileId(meterFile.getId());
            list.add(businessOriginalRecordFileRelation);
        });
        return this.saveBatch(list);
    }

    @Override
    public List<MeterFile> getFilesByOriginalRecordId(Long originId) {
        QueryWrapper<BusinessOriginalRecordFileRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("original_record_id", originId);
        List<BusinessOriginalRecordFileRelation> list = this.baseMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0) {
            return meterFileService.list(list.stream().map(BusinessOriginalRecordFileRelation::getFileId).collect(Collectors.toList()));
        }
        return null;
    }

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

}
