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.oss.OssFileResult;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.frame.entity.LmsFrameFile;
import com.patzn.lims.frame.mapper.LmsFrameFileMapper;
import com.patzn.lims.frame.service.ILmsFrameFileService;
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 patzn123
 * @since 2018-01-09
 */
@Service
public class LmsFrameFileServiceImpl extends BaseServiceImpl<LmsFrameFileMapper, LmsFrameFile> implements ILmsFrameFileService {

    @Autowired
    private OssClient ossClient;

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

        return page(page, wrapper);
    }


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

    @Override
    public LmsFrameFile saveAndUpload(MultipartFile file, String bucketName, String foldPath, Long relId, Integer type) {
        LmsFrameFile lmsFrameFile = new LmsFrameFile();
        String fileName = file.getOriginalFilename();
        OssFileResult result = ossClient.upload(file);
        if (null == result) {
            return null;
        }
        lmsFrameFile.setRelId(relId);
        lmsFrameFile.setOrginName(fileName);
        lmsFrameFile.setFilePath(result.getObjectKey());
        //核查类型
        lmsFrameFile.setType(type);
        save(lmsFrameFile);
        lmsFrameFile.setFilePath(ossClient.getUrl(lmsFrameFile.getFilePath()).toString());
        return lmsFrameFile;
    }

    @Override
    public Boolean deleteBatch(Long[] ids) {
        for (int i = 0; i < ids.length; i++) {
            LmsFrameFile lmsFrameFile = getById(ids[i]);
            if (null != lmsFrameFile) {
                ossClient.deleteObject(lmsFrameFile.getFilePath());
            }
        }

        return remove(Wrappers.<LmsFrameFile>query().in("id", ids));
    }


    @Override
    public boolean deleteByInnerCheckPlan(Long innerPlanId) {
        if (null == innerPlanId) {
            return false;
        }
        return remove(Wrappers.<LmsFrameFile>query().eq("rel_id", innerPlanId));
    }

    @Override
    public void downloadFile(HttpServletResponse response, String bucket, String fileName, String orgFileName) {
        ossClient.download(fileName, response);
    }
}
