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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.oss.OssClient;
import com.patzn.lims.core.oss.OssFileResult;
import com.patzn.lims.core.toolkit.FileUtils;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.frame.entity.LmsMonthPlanAttachment;
import com.patzn.lims.frame.mapper.LmsMonthPlanAttachmentMapper;
import com.patzn.lims.frame.service.ILmsMonthPlanAttachmentService;
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-06-26
 */
@Service
public class LmsMonthPlanAttachmentServiceImpl extends BaseServiceImpl<LmsMonthPlanAttachmentMapper, LmsMonthPlanAttachment> implements ILmsMonthPlanAttachmentService {

    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsMonthPlanAttachment> page(Page<LmsMonthPlanAttachment> page, LmsMonthPlanAttachment lmsMonthPlanAttachment) {
        QueryWrapper wrapper = Wrappers.query(lmsMonthPlanAttachment);
        wrapper.like("file_name", lmsMonthPlanAttachment.getFileName());
        lmsMonthPlanAttachment.setFileName(null);
        List<LmsMonthPlanAttachment> list = page(page, wrapper).getRecords();
        list.forEach(e->{
            e.setObjectKey(ossClient.getUrl(e.getObjectKey()).toString());
        });
        return page.setRecords(list);
    }


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


    @Override
    public int getCountByPlanId(Long planId) {
        return super.count(Wrappers.<LmsMonthPlanAttachment>query().eq("month_plan_id", planId));
    }

    @Override
    public boolean save(Long planId, MultipartFile file) {
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return false;
        }
        // 文件类型，版本信息
        LmsMonthPlanAttachment attachment = new LmsMonthPlanAttachment();
        attachment.setType(result.getType());
        attachment.setMonthPlanId(planId);
        attachment.setBucketName(result.getBucketName());
        attachment.setObjectKey(result.getObjectKey());
        attachment.setVersionId(result.getVersionId());
        // 上传新文件
        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) {
        LmsMonthPlanAttachment 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<LmsMonthPlanAttachment> attachments = super.list(Wrappers.<LmsMonthPlanAttachment>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 (LmsMonthPlanAttachment 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();
        }
    }
}
