package cc.smtweb.system.bpm.spring.file.attach;

import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.util.CommUtil;
import cc.smtweb.framework.core.util.DateUtil;
import cc.smtweb.framework.core.util.NumberUtil;
import cc.smtweb.framework.core.util.StringUtil;
import cc.smtweb.system.bpm.spring.config.FileConfigProperties;
import cc.smtweb.system.bpm.util.UtilFile;
import cc.smtweb.system.bpm.web.sys.base.attach.AttachInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * Created by AKmm at 11-6-15 下午3:32
 * 附件管理
 */
@Component
public final class AttachHelper {
    Logger logger = LoggerFactory.getLogger(AttachHelper.class);
    @Autowired
    private FileConfigProperties properties;
    @Autowired
    private DbEngine dbEngine;
    @Autowired
    private AttachUtil attachUtil;

    //得到附件临时目录
    public String getAttachTmpPath() {
        String tmp_attach = properties.getAttachTempPath();
        if (!tmp_attach.endsWith("/")) tmp_attach += "/";
        File file = new File(tmp_attach);
        if (!file.exists()) {
            file.mkdirs();
        }
        return tmp_attach;
    }

    //删除ftp服务器的文件
    public boolean deleteOneAttach(String attachId) throws Exception {
        if (StringUtil.isEmpty(attachId)) return true;
        AttachInfo attachInfo = dbEngine.queryEntity(AttachInfo.class, Long.valueOf(attachId));
        if (null == attachInfo) {
            return true;
        }
        boolean deleteSuccess = deleteAttachInFtpServer(attachInfo.getPath(), attachInfo.getName());
        if (deleteSuccess) {
            dbEngine.deleteEntity(attachInfo);
        }
        return deleteSuccess;
    }

    //删除ftp服务器的文件
    public boolean deleteOneAttach(AttachInfo bean) {
        boolean deleteSuccess = deleteAttachInFtpServer(bean.getPath(), bean.getName());
        if (deleteSuccess) {
            dbEngine.deleteEntity(bean);
        }
        return deleteSuccess;
    }

    //删除ftp服务器的文件夹
    public void deleteFolder(final String remotePath) throws Exception {
        attachUtil.deletePath(remotePath);
    }

    public List<AttachInfo> getAttachListByOwnerId(String ownerId) throws Exception {
        return dbEngine.query("select * from " + AttachInfo.ENTITY_NAME + " where attach_owner_id=? ", AttachInfo.class, ownerId);
    }

    public List<AttachInfo> listAttachListByOwnerIdAndType(String ownerId, String attach_type) throws Exception {
        return dbEngine.query("select * from " + AttachInfo.ENTITY_NAME + " where attach_owner_id=? and attach_type=? ", AttachInfo.class, ownerId, attach_type);
    }

    public int getAttachCountByOwnerId(String ownerId) throws Exception {
        return dbEngine.queryInt("select count(0) from " + AttachInfo.ENTITY_NAME + " where attach_owner_id=? ", ownerId);
    }

    //根据附件拥有者和附件类型删除
    public boolean deleteAttachByOwnerIdAndType(String ownerId, String attachType) throws Exception {
        final List<AttachInfo> list = listAttachListByOwnerIdAndType(ownerId, attachType);
        return deleteAttachListEx(list);
    }

    public boolean deleteAttachByOwnerId(String ownerId) throws Exception {
        final List<AttachInfo> list = getAttachListByOwnerId(ownerId);
        return deleteAttachListEx(list);
    }

    //批量删除
    public boolean deleteAttachList(List<String> attachIdList) throws Exception {
        if (CommUtil.isEmpty(attachIdList)) return false;
        dbEngine.update("delete from " + AttachInfo.ENTITY_NAME + " where attach_id in(" + StringUtil.join(attachIdList,",") + ")");
        return true;
    }

    public boolean deleteAttachListEx(List<AttachInfo> list) throws Exception {
        boolean result = true;
        for (AttachInfo bean : list) {
            if (!deleteAttachInFtpServer(bean.getPath(), bean.getName())) {
                result = false;
                break;
            }
        }
        if (result) {
            for (AttachInfo bean : list) {
                dbEngine.deleteEntity(bean);
            }
        }
        return result;
    }

    //删除在ftp服务器上的附件
    public boolean deleteAttachInFtpServer(String remotePath, String remoteName) {
        try {
            attachUtil.deleteAttach(remotePath, remoteName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 下载附件
     *
     * @param attachId  附件id
     * @param localPath 要下载到的本地路径
     * @return 返回文件名
     * @throws Exception
     */
    public String getAttachFromFtp(final String attachId, final String localPath) throws Exception {
        AttachInfo attach = dbEngine.queryEntity(AttachInfo.class, Long.valueOf(attachId));
        if (null == attach) throw new Exception("附件不存在！");

        final String remoteFileName = attach.getName();
        final String remotePath = attach.getPath();

        attachUtil.downloadAttach(remotePath, remoteFileName, localPath);
        return remoteFileName;

    }

    /**
     * 下载附件
     *
     * @param attachId  附件id
     * @param localPath 要下载到的本地路径
     * @return 返回文件名
     * @throws Exception
     */
    public String getAttachFromFtp(final String attachId, final String localPath, String localName) throws Exception {
        AttachInfo attach = dbEngine.queryEntity(AttachInfo.class, Long.valueOf(attachId));
        if (null == attach) throw new Exception("附件不存在！");
        final String remoteFileName = attach.getName();
        final String remotePath = attach.getPath();

        attachUtil.downloadAttach(remotePath, remoteFileName, localPath, localName);
        return remoteFileName;

    }

    /**
     * 下载附件
     *
     * @param attachlist 附件列表
     * @param ownerType  附件类别
     * @return 返回文件名列表，本地有此文件将不再下载
     * @throws Exception
     */
    private List<String> getAttachListFromFtp(final List<AttachInfo> attachlist, final String ownerType) throws Exception {
        return attachUtil.getAttachListFromFtp(attachlist, ownerType, getAttachTmpPath());
    }

    /**
     * 下载附件
     *
     * @param ownerId   附件拥有者id
     * @param ownerType 附件类别
     * @return 返回文件名列表，本地有此文件将不再下载
     * @throws Exception
     */
    public List<String> getAttachsFromFtp(final String ownerId, final String ownerType) throws Exception {
        final List<AttachInfo> attachlist = getAttachListByOwnerId(ownerId);

        return getAttachListFromFtp(attachlist, ownerType);

    }

    /**
     * 下载附件
     *
     * @param attachIds 附件id
     * @param ownerType 附件类别
     * @return 返回文件名列表，本地有此文件将不再下载
     * @throws Exception
     */
    public List<String> getAttachsFromFtp(final List<String> attachIds, final String ownerType) throws Exception {
        List<Object> paras = new ArrayList<Object>();
        if (!CommUtil.isEmpty(attachIds)) {
            StringBuilder sb = new StringBuilder(128);
            for (int i = 0; i < attachIds.size(); i++) {
                if (i == 0) {
                    sb.append(" attach_id=? ");
                } else {
                    sb.append(" or attach_id=? ");
                }
                paras.add(attachIds.get(i));
            }
            final List<AttachInfo> attachlist = dbEngine.queryWhere(AttachInfo.class, sb.toString(), paras.toArray());
            if (null == attachlist || attachlist.size() < 1) throw new Exception("附件不存在！");
            return getAttachListFromFtp(attachlist, ownerType);
        }
        return new ArrayList<>();
    }

    /**
     * 得到文件大小
     *
     * @return
     */
    public String getSizeStr(long fileSize) {
        if (fileSize < 1024) return fileSize + "B";
        double n = fileSize * 1.0 / 1024;
        if (NumberUtil.compare(n, 1024) < 0) return NumberUtil.toStdNumberString(n, 0) + "KB";
        n = n / 1024;
        return NumberUtil.toStdNumberString(n) + "MB";
    }

    /**
     * 清除临时标志
     *
     * @param attach_owner_id 拥有者
     * @throws Exception
     */
    public void removeTempTag(String attach_owner_id) throws Exception {
        dbEngine.update("update " + AttachInfo.ENTITY_NAME + " set  attach_is_temp=0 WHERE attach_owner_id=? AND attach_is_temp=1 ", attach_owner_id);
    }

    public String copyupload(String type, Long attachId) {
        AttachInfo attach = dbEngine.queryEntity(AttachInfo.class, attachId);
        if (attach == null) {
            return "";
        }
        String remoteName = attach.getId() + attach.getName().substring(attach.getName().lastIndexOf("."));
        String remotePath = attach.getPath();
        String filePath = getAttachTmpPath() + "tempFiles/";
        UtilFile.makeDir(filePath);
        Map<String, String> map = null;
        try {
            attachUtil.downloadAttach(remotePath, remoteName, filePath);
            String filePaths = filePath + remoteName;

            attach.setId(dbEngine.nextId());
            attach.setType(type);//附件类别
            attach.setOwnerId(-1l);//附件拥有者id
            attach.setPartyId(-1l);
            attach.setTime(DateUtil.nowDateTimeLong());
            attach.setUserId(-1l);
            attach.setName(attach.getId() + attach.getSuffix());
            // 上传文件域对象
            File upload = new File(filePaths);
//            attach.setAttachSize((long) FileCopyUtils.copy(file.getInputStream(), new BufferedOutputStream(new FileOutputStream(upload))));
            try {
                //一般附件，上传到服务器，并记录附件
                //传到ftp服务器上
                attachUtil.saveAttach(attach, upload.getPath(), false);
                //写入数据库
                dbEngine.insertEntity(attach);
            } finally {
                UtilFile.delFile(upload.getAbsolutePath());
            }
        } catch (Exception e) {
            logger.error("复制文件失败", e);
            return "";
        }
        return attach.getId() + "";
    }
}
