package cn.estsh.i3plus.core.apiservice.serviceimpl.busi;

import cn.estsh.i3plus.core.api.iservice.busi.ISysFileService;
import cn.estsh.i3plus.core.apiservice.util.FileUtil;
import cn.estsh.i3plus.platform.common.tool.StringTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseConstWords;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.platform.bean.SysDictionary;
import cn.estsh.i3plus.pojo.platform.bean.SysFile;
import cn.estsh.i3plus.pojo.platform.repository.SysDictionaryRepository;
import cn.estsh.i3plus.pojo.platform.repository.SysFileRepository;
import cn.estsh.i3plus.pojo.platform.sqlpack.CoreHqlPack;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSClient;
import cn.estsh.impp.framework.boot.fastdfs.FastDFSFile;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * @Description : 文件资源服务接口
 * @Reference :
 * @Author : yunhao
 * @Date : 2018-10-25 16:28
 * @Modify :
 **/
@Service
public class SysFileServiceImpl implements ISysFileService {
    public static final Logger LOGGER = LoggerFactory.getLogger(SysFileServiceImpl.class);

    @Autowired
    private SysFileRepository sysFileRDao;

    @Autowired
    private SysDictionaryRepository sysDictionaryRDao;

    @Autowired
    private FastDFSClient dfsClient;

    @Override
    @ApiOperation(value = "新增资源信息")
    public SysFile insertSysFile(SysFile sysFile) {
        LOGGER.info("文件资源 SYS_FILE :{}",sysFile);
        return sysFileRDao.insert(sysFile);
    }

    @Override
    @ApiOperation(value = "更新资源信息")
    public void updateSysFile(SysFile sysFile) {
        LOGGER.info("文件资源 SYS_FILE :{}",sysFile);
        sysFileRDao.update(sysFile);
    }

    @Override
    @ApiOperation(value = "查询资源信息",notes = "查询所有资源信息")
    public List<SysFile> listSysFile() {
        LOGGER.info("文件资源 SYS_FILE list");
        return sysFileRDao.list();
    }

    @Override
    @ApiOperation(value = "查询资源信息",notes = "根据 ID查询资源信息")
    public SysFile getSysFileById(Long id) {
        LOGGER.info("文件资源 SYS_FILE id:{}",id);
        return sysFileRDao.getById(id);
    }

    @Override
    @ApiOperation(value = "查询资源信息",notes = "查询资源信息(分页、组合)")
    public ListPager querySysFileByPager(SysFile sysFile, Pager pager) {
        LOGGER.info("文件资源 SYS_FILE sysFile:{}，Pager:{}",sysFile,pager);
        if(sysFile == null) {
            pager = PagerHelper.getPager(pager, sysFileRDao.listCount());
            return new ListPager(sysFileRDao.listPager(pager),pager);
        }else {
            String hqlPack = CoreHqlPack.packHqlSysFile(sysFile);
            pager = PagerHelper.getPager(pager, sysFileRDao.findByHqlWhereCount(hqlPack));
            return new ListPager(sysFileRDao.findByHqlWherePage(hqlPack + sysFile.orderBy(),pager),pager);
        }
    }

    @Override
    @ApiOperation(value = "删除资源信息",notes = "根据ID删除资源信息")
    public void deleteSysFileById(Long id) {
        LOGGER.info("文件资源 SYS_FILE id:{}",id);
        sysFileRDao.deleteById(id);
    }

    @Override
    public void deleteSysFileByIds(Long[] ids) {
        LOGGER.info("文件资源 SYS_FILE ids:{}", ids);
        sysFileRDao.deleteByIds(ids);
    }

    @Override
    @ApiOperation(value = "上传文件资源",notes = "上传文件资源")
    public SysFile uploadFile(Object file) throws Exception{
        FastDFSFile fastDFSFile;
        // 判断参数类型
        if(file instanceof File){
            fastDFSFile = new FastDFSFile(((File)file).getName(), FileUtil.file2Byte(((File)file).getPath()),
                    StringTool.getStringFileSuffix(((File)file).getName(),true));
        }else{
            fastDFSFile = dfsClient.saveFile((MultipartFile) file);
        }

        String[] fileAbsolutePath = dfsClient.upload(fastDFSFile);

        // 保存到系统文件表中
        String filePath = dfsClient.getHostUi() + "/" + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        SysDictionary dictionary = sysDictionaryRDao.getByProperty(new String[]{"parentCodeRdd","dictionaryValue"},
                new Object[]{BaseConstWords.DICTIONARY_FILE_TYPE, fastDFSFile.getExt()});

        if(dictionary == null){
            dictionary = sysDictionaryRDao.getByProperty(new String[]{"parentCodeRdd","dictionaryValue"},
                    new Object[]{BaseConstWords.DICTIONARY_FILE_TYPE, "."+fastDFSFile.getExt()});
        }


        SysFile sysFile = new SysFile();
        sysFile.setDfsGroupName(fileAbsolutePath[0]);
        sysFile.setDfsFileName(fileAbsolutePath[1]);
        sysFile.setFileSize(fastDFSFile.getContent().length);
        sysFile.setFilePath(filePath);
        sysFile.setFileOriginalName(fastDFSFile.getName());
        sysFile.setFileTypeId(dictionary.getId());
        sysFile.setFileTypeName(dictionary.getName());
        sysFile.setDownloadNum(0);
        sysFile.setCreateDatetime(TimeTool.getNowTime(true));

        return insertSysFile(sysFile);
    }
}
