package com.patzn.lims.frame.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.oss.OssFileResult;
import com.patzn.lims.frame.entity.LmsQcMainPlanAttachment;
import com.patzn.lims.frame.mapper.LmsQcMainPlanAttachmentMapper;
import com.patzn.lims.frame.service.ILmsQcMainPlanAttachmentService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import static java.util.stream.Collectors.toList;
/**
 * <p>
 * 内部质控计划主表附件表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-07-09
 */
@Service
public class LmsQcMainPlanAttachmentServiceImpl extends BaseServiceImpl<LmsQcMainPlanAttachmentMapper, LmsQcMainPlanAttachment> implements ILmsQcMainPlanAttachmentService {

    @Autowired
    private OssClient ossClient;

    @Override
    public List<LmsQcMainPlanAttachment> list(LmsQcMainPlanAttachment lmsFrameFile) {
        return list(Wrappers.query(lmsFrameFile));
    }

    @Override
    public LmsQcMainPlanAttachment saveAndUpload(MultipartFile file, String bucketName, String foldPath, Long relId, Integer type) {
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return null;
        }
        LmsQcMainPlanAttachment attachment = new LmsQcMainPlanAttachment();
        String fileName = file.getOriginalFilename();
        attachment.setMainPlanId(relId);
        attachment.setFileName(fileName);
        attachment.setObjectKey(result.getObjectKey());
        save(attachment);
        attachment.setObjectKey(ossClient.getUrl(attachment.getObjectKey()).toString());
        return attachment;
    }

    @Override
    public boolean deleteBatch(Long[] ids) {
        List<LmsQcMainPlanAttachment> attachmentList = list(Wrappers.<LmsQcMainPlanAttachment>query().in("id", ids));
        if (CollectionUtils.isEmpty(attachmentList)) {
            return false;
        }
        ossClient.deleteObjects(attachmentList.stream().map(e -> e.getObjectKey()).collect(toList()));
        return remove(Wrappers.<LmsQcMainPlanAttachment>query().in("id", ids));
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        LmsQcMainPlanAttachment attachment = super.getById(id);
        if (null == attachment) {
            PtAssert.fail("抱歉！该附件不存在");
        }
        ossClient.download(attachment.getObjectKey(), attachment.getFileName(), response);
    }
}
