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.oss.OssClient;
import com.patzn.lims.core.oss.OssFileResult;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.frame.entity.LmsYearPlanAttachment;
import com.patzn.lims.frame.mapper.LmsYearPlanAttachmentMapper;
import com.patzn.lims.frame.service.ILmsYearPlanAttachmentService;
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;

/**
 * <p>
 * 年度计划主表附件表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-07-25
 */
@Service
public class LmsYearPlanAttachmentServiceImpl extends BaseServiceImpl<LmsYearPlanAttachmentMapper, LmsYearPlanAttachment> implements ILmsYearPlanAttachmentService {

    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsYearPlanAttachment> page(Page<LmsYearPlanAttachment> page, LmsYearPlanAttachment lmsYearPlanAttachment) {
        QueryWrapper wrapper = Wrappers.query(lmsYearPlanAttachment);

        return page(page, wrapper);
    }


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


    @Override
    public boolean save(Long planId, MultipartFile file) {
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return false;
        }
        // 文件类型，版本信息
        LmsYearPlanAttachment attachment = new LmsYearPlanAttachment();
        attachment.setType(result.getType());
        attachment.setYearPlanId(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) {
        LmsYearPlanAttachment attachment = super.getById(id);
        PtAssert.fail(null == attachment, "抱歉！该附件不存在");
        ossClient.download(attachment.getObjectKey(), response);
    }
}
