package com.patzn.lims.drug.service.impl;

import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.drug.entity.DrugSampleAnnex;
import com.patzn.lims.drug.mapper.DrugSampleAnnexMapper;
import com.patzn.lims.drug.service.IDrugSampleAnnexService;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.res.service.MongoDbService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 食药单机系统-样品附件表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-09
 */
@Service
public class DrugSampleAnnexServiceImpl extends BaseServiceImpl<DrugSampleAnnexMapper, DrugSampleAnnex> implements IDrugSampleAnnexService {

    @Autowired
    private MongoDbService mongoDbService;

    @Override
    public Page<DrugSampleAnnex> page(Page<DrugSampleAnnex> page, DrugSampleAnnex drugSampleAnnex) {
        QueryWrapper<DrugSampleAnnex> wrapper = Wrappers.<DrugSampleAnnex>query(drugSampleAnnex);
        return this.page(page, wrapper);
    }

    @Override
    public boolean upload(MultipartFile file, Long sampleId) {
        String fileName = file.getOriginalFilename();
        PtAssert.fail(StringUtils.isBlank(fileName), "请上传文件");
        DrugSampleAnnex attachment = new DrugSampleAnnex();
        attachment.setSampleId(sampleId);
        String result = mongoDbService.saveFile(file);
        if (null == result) {
            return false;
        }
        attachment.setType(file.getOriginalFilename().split("\\.")[1]);
        attachment.setObjectKey(result);
        attachment.setFileName(file.getOriginalFilename());
        return super.save(attachment);
    }

    @Override
    public void downloadFile(Long id ,HttpServletRequest request, HttpServletResponse response) {

        if (null == id){
            return;
        }
        DrugSampleAnnex annex = getById(id);
        mongoDbService.downloadFile(annex.getObjectKey(),request,response);

    }
}
