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

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.core.api.PtAssert;
import com.patzn.lims.core.toolkit.FileUtils;
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.LmsQcSubPlanAttachment;
import com.patzn.lims.frame.mapper.LmsQcSubPlanAttachmentMapper;
import com.patzn.lims.frame.service.ILmsQcSubPlanAttachmentService;
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.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 内部质控计划子表附件表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-07-09
 */
@Service
public class LmsQcSubPlanAttachmentServiceImpl extends BaseServiceImpl<LmsQcSubPlanAttachmentMapper, LmsQcSubPlanAttachment> implements ILmsQcSubPlanAttachmentService {

    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsQcSubPlanAttachment> page(Page<LmsQcSubPlanAttachment> page, LmsQcSubPlanAttachment lmsQcSubPlanAttachment) {
        QueryWrapper wrapper = Wrappers.query(lmsQcSubPlanAttachment);
        if (null != lmsQcSubPlanAttachment.getFileName()) {
            wrapper.like("file_name", lmsQcSubPlanAttachment.getFileName());
            lmsQcSubPlanAttachment.setFileName(null);
        }
        List<LmsQcSubPlanAttachment> list = page(page, wrapper).getRecords();
        for (LmsQcSubPlanAttachment e:list) {
            e.setObjectKey(ossClient.getUrl(e.getObjectKey()).toString());
        }
        return  page.setRecords(list);
    }


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

    @Override
    public int getCountByPlanId(Long id) {
        return super.count(Wrappers.<LmsQcSubPlanAttachment>query().eq("sub_plan_id", id));
    }

    @Override
    public boolean save(Long planId, MultipartFile file) {
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return false;
        }
        // 文件类型，版本信息
        LmsQcSubPlanAttachment attachment = new LmsQcSubPlanAttachment();
        attachment.setType(result.getType());
        attachment.setSubPlanId(planId);
        attachment.setBucketName(result.getBucketName());
        attachment.setVersionId(result.getVersionId());
        attachment.setObjectKey(result.getObjectKey());
        // 上传新文件
        int length = result.getName().length();
        if (length > 99) {
            StringBuilder fileName = new StringBuilder();
            fileName.append(result.getName().substring(0, 50));
            fileName.append(result.getName().substring(length - 50));
            attachment.setFileName(fileName.toString());
        } else {
            attachment.setFileName(result.getName());
        }
        return super.save(attachment);
    }

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

    @Override
    public void downloadBatch(Long[] attachmentIds, HttpServletResponse response) {
        PtAssert.fail(null == attachmentIds || attachmentIds.length == 0, "附件id未传递");
        List<LmsQcSubPlanAttachment> attachments = super.list(Wrappers.<LmsQcSubPlanAttachment>query().in("id", attachmentIds));
        PtAssert.fail(CollectionUtils.isEmpty(attachments), "附件查询为空");

        Map<String, InputStream> mapStream = new HashMap<>();
        List<File> deleteList = new ArrayList<>();
        List<File> downLoadList = new ArrayList<>();
        for (LmsQcSubPlanAttachment attachment : attachments) {
            InputStream attachmentStream = ossClient.download(attachment.getObjectKey());
            mapStream.put(attachment.getFileName() + "." + attachment.getType(), attachmentStream);
            File file = new File(System.getProperty("java.io.tmpdir") + File.separator
                    + attachment.getFileName() + "." + attachment.getType());
            try {
                inputStream2File(attachmentStream, file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            downLoadList.add(file);
            deleteList.add(file);
        }

        try {
            FileUtils.downLoadFiles(downLoadList, "内部质控计划附件.zip", response);
        } catch (Exception e) {
            log.error("导出内部质控计划附件失败", e);
        } finally {
            if (CollectionUtils.isNotEmpty(deleteList)) {
                FileUtils.deleteFiles(deleteList);
            }
        }
    }

    public static void inputStream2File(InputStream is, File file) throws IOException {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[8192];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            os.close();
            is.close();
        }
    }
}
