package com.yihu.hos.rest.services.crawler;

import com.yihu.hos.core.compress.Zipper;
import com.yihu.hos.core.encrypt.RSA;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.rest.models.crawler.config.SysConfig;
import com.yihu.hos.rest.models.crawler.patient.Patient;

import java.io.File;
import java.security.Key;
import java.util.UUID;

/**
 * 档案上传
 *
 * @author Air
 * @version 1.0
 * @created 2015.07.06 15:58
 */
public class PatientCDAUpload {

    private static Logger logger = LoggerFactory.getLogger(PatientCDAUpload.class);

    public static String uploadMethod;

    /**
     * @param patient
     * @return
     * @modify 2015.09.15 airhead 修订删除目录
     * @modify 2015.09.19 airhead 修复无文档问题及错误信息
     */
    public Boolean upload(Patient patient, String token) {
        ZipFile zipFile = zip(patient);
        try {
            if (zipFile == null || zipFile.file == null) {
                logger.info("压缩病人档案失败,病人文档未生成,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return false;
            }

            boolean result = upload(patient, zipFile, token);
            if (!result) {
                logger.info("上传病人档案失败,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return result;
            }

            logger.trace(zipFile.directory);
            result = FileUtil.deleteDirectory(new File(zipFile.directory));
            if (!result) {
                logger.info("删除临时文件失败,patient_id:" + patient.getPatientId() + ",event_no:" + patient.getEventNo());
                return result;
            }
        } catch (Exception e) {
            FileUtil.deleteDirectory(new File(zipFile.directory));
            return false;
        }
        return true;
    }

    /**
     * @param patient
     * @return
     * @modify 从data目录生成zip数据
     */
    public ZipFile zip(Patient patient) {
        try {
            PatientCDAIndex patientCDAIndex = new PatientCDAIndex(patient);
            String dataDirectory = patientCDAIndex.getDataDirectory();
            String filePath = patientCDAIndex.createIndex(PatientCDAIndex.IndexType.ZIP, PatientCDAIndex.FileType.ZIP);
            UUID uuidPwd = UUID.randomUUID();
            String pwd = uuidPwd.toString();
            String publicKey = SysConfig.getInstance().getPublicKeyMap().get(patient.getOrgCode());
            if(publicKey== null ||  publicKey.length() == 0) {
                publicKey = EsbHttp.getPublicKey(patient.getOrgCode());
                SysConfig.getInstance().getPublicKeyMap().put(patient.getOrgCode(), publicKey);
            }

            Key key = RSA.genPublicKey(publicKey);
            if (key == null) {
                logger.info("压缩文件错误,获取公钥错误.");
                return null;
            }

            ZipFile zipFile = new ZipFile();
            zipFile.encryptPwd = RSA.encrypt(pwd, key);

            Zipper zipper = new Zipper();
            zipFile.file = zipper.zipFileForAll(new File(dataDirectory), filePath, pwd);
            zipFile.dataDirectory = dataDirectory;
            zipFile.directory = patientCDAIndex.getDirectory();

            return zipFile;
        } catch (Exception e) {
            logger.error("从data目录生成zip数据时，压缩文件异常");
            logger.error(e.getCause().toString());
        }

        return null;
    }

    private boolean upload(Patient patient, ZipFile zipFile, String token) {
        return EsbHttp.upload(patient, zipFile.file, zipFile.encryptPwd, token);
    }

    private class ZipFile {
        public File file;
        public String encryptPwd;
        public String directory;
        public String dataDirectory;
    }

}
