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

import com.google.common.collect.Lists;
import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.cloud.commons.zip.FileEntry;
import com.patzn.cloud.commons.zip.ZipUtils;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.oss.OssFileResult;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.drug.entity.DrugSample;
import com.patzn.lims.drug.entity.DrugSampleReport;
import com.patzn.lims.drug.mapper.DrugSampleReportMapper;
import com.patzn.lims.drug.service.IDrugSampleReportService;
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 org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * <p>
 * 食药单机版报告表 服务实现类
 * </p>
 *
 * @author wwd
 * @since 2020-03-10
 */
@Service
public class DrugSampleReportServiceImpl extends BaseServiceImpl<DrugSampleReportMapper, DrugSampleReport> implements IDrugSampleReportService {

    @Autowired
    private OssClient ossClient;


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


    @Override
    public DrugSampleReport getLastByContractId(Long sampleId){
        return getOne(Wrappers.<DrugSampleReport>query().eq("sample_id",sampleId).orderBy(true,false,"version").last("LIMIT 1"));
    }

    @Override
    public void download(Long[] sampleId, HttpServletResponse response, DrugSampleReport drugSampleReport) {
        if (sampleId.length==1){
            DrugSampleReport report =getLastByContractId(sampleId[0]);
            RestAssert.fail(null == report || StringUtils.isEmpty(report.getUri()), "报告未生成稍后下载");
            String objectKey = report.getUri().split("#")[1];
            ossClient.download(objectKey, response);
            return;
        }
        Map<InputStream,String> mapStream = new HashMap<>(16);
        List<DrugSampleReport> listAttachment=new ArrayList<>();
        for (Long  id : sampleId) {
            DrugSampleReport report =getLastByContractId(id);
            if (null!=report){
                listAttachment.add(report);
            }
        }
        RestAssert.fail (CollectionUtils.isEmpty(listAttachment),"报告未生成");
        for (DrugSampleReport attachment:listAttachment) {
            RestAssert.fail(null == attachment || StringUtils.isEmpty(attachment.getUri()), "报告未生成稍后下载");
            String objectKey = attachment.getUri().split("#")[1];
            InputStream contractStream = ossClient.download(objectKey);
            mapStream.put( contractStream,attachment.getUri().split("#")[0] + "" + attachment.getVersion()
                    +"."+attachment.getUri().split("#")[attachment.getUri().split("#").length-1]);
        }
        try {
            OutputStream fos = response.getOutputStream();
            List<FileEntry> fileEntryList = Lists.newArrayList();
            for (Map.Entry<InputStream,String> streamEntry : mapStream.entrySet()) {
                fileEntryList.add(new FileEntry(streamEntry.getKey(), streamEntry.getValue()));
            }
            ZipUtils.zipFile(fos, fileEntryList);
        } catch (Exception e) {
            log.error("down report fail " + Arrays.toString(sampleId), e);
        }
    }

    @Override
    public void uploadSampleGenerateDocx(DrugSample dbSample, Account account, String remark, File file) {
        RestAssert.fail(null == dbSample, "请选择上传的报检单");
        DrugSampleReport   report = getLastByContractId(dbSample.getId());
        int version = 1;
        if (null != report) {
            version = report.getVersion() + 1;
        }
        if (version == 1) {
            RestAssert.fail(StringUtils.isBlank(remark), "请填写上传备注");
        }
        // 上传报告文件
        OssFileResult obsFileResult = ossClient.upload(file);
        if (null == obsFileResult) {
            return ;
        }
        DrugSampleReport tempReportInfo = new DrugSampleReport();
        tempReportInfo.setUri(obsFileResult.getUri());
        tempReportInfo.setRemark(remark);
        tempReportInfo.setVersion(version);
        tempReportInfo.setSampleId(dbSample.getId());
        tempReportInfo.setMaker(account.getUserName());
        tempReportInfo.setMakeId(account.getUserId());
        tempReportInfo.setReportCode(dbSample.getReportCode());
        tempReportInfo.setMakeTime(new Date());
        super.save(tempReportInfo);
    }
}
