/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.isignature.service;

//import DBstep.iMsgServer2000;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.Office2PdfUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.isignature.dao.ISignatureDocumentDao;
import com.jeeplus.modules.isignature.entity.ISignatureDocument;
import com.jeeplus.modules.isignature.workthread.ImageConvertThread;
import com.jeeplus.modules.sys.dao.WorkattachmentDao;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 电子签章信息Service
 * @author fgy
 * @version 2018-04-17
 */
@Service
@Transactional(readOnly = true)
public class ISignatureDocumentService extends CrudService<ISignatureDocumentDao, ISignatureDocument> {

    private static final String[] PDF = new String[]{"PDF","pdf"};
    private static final String[] OFFICE = new String[]{"doc","DOC","xls","XLS","ppt","PPT","docx","DOCX","xlsx","XLSX","pptx","PPTX"};

	@Autowired
	private WorkattachmentDao workattachmentDao;

	public ISignatureDocument get(String id) {
		return super.get(id);
	}
	
	public List<ISignatureDocument> findList(ISignatureDocument iSignatureDocument) {
		return super.findList(iSignatureDocument);
	}
	
	public Page<ISignatureDocument> findPage(Page<ISignatureDocument> page, ISignatureDocument iSignatureDocument) {
		return super.findPage(page, iSignatureDocument);
	}
	
	@Transactional(readOnly = false)
	public void save(ISignatureDocument iSignatureDocument) {
		super.save(iSignatureDocument);
	}
	
	@Transactional(readOnly = false)
	public void delete(ISignatureDocument iSignatureDocument) {
		super.delete(iSignatureDocument);
	}

	/**
	 * 更新签章文档
	 * @param iMsgBody
	 */
//	@Transactional(readOnly = false)
//	public void update(iMsgServer2000 iMsgBody){
//		String id = iMsgBody.GetMsgByName("RECORDID");//取得文档编号
//		String filename = iMsgBody.GetMsgByName("FILENAME");//取得文档名称
////		String filetype = iMsgBody.GetMsgByName("FILETYPE");//取得文档类型
//		String filepath = iMsgBody.GetMsgByName("FILEPATH");//取得文档存储路径
//		byte[] bytes = iMsgBody.MsgFileBody();
//		logger.info("保存签章文档，文档号：{}，文档名称：{}",id,filename);
//
//		OSSClientUtil ossClientUtil = new OSSClientUtil();
//		ByteArrayInputStream byteArrayInputStream = null;
//		ByteArrayOutputStream imageOutputStream = null;
//		ByteArrayInputStream imageInputStream = null;
//		byteArrayInputStream = new ByteArrayInputStream(bytes);
//		imageInputStream = new ByteArrayInputStream(bytes);
//		String pathString = getPathString(filepath, filename);
//		pathString = pathString.replace(filename,"");
//		logger.info("文档保存路径：{}",pathString);
//		ossClientUtil.uploadFile2OSS(byteArrayInputStream, pathString, filename);
//		logger.info("成功保存签章文档");
//		//转图片保存 文件大会慢，之后转异步处理
//		new Thread(new ImageConvertThread(imageInputStream,pathString,filename,ossClientUtil)).start();
//
////		filepath = Global.getAliyunUrl() + "/" + Global.getISignature() + filename;
//		String imagePath = Office2PdfUtil.convertPdfFileName(filepath);
//		ISignatureDocument iSignatureDocument = new ISignatureDocument(id);
//		iSignatureDocument.setFilePath(filepath);
//		iSignatureDocument.setFileName(filename);
//		iSignatureDocument.setUpdateBy(UserUtils.getUser());
//		iSignatureDocument.setUpdateDate(new Date());
//		iSignatureDocument.setImagePath(imagePath);
//        iSignatureDocument.setIsignatureStatus("0");
//		dao.updateSelective(iSignatureDocument);
//		return;
//	}

	/**
	 * 创建待签章文档
	 * @param fileUrl
	 * @param fileName
	 * @param recordId
	 * @param subject
	 */
	public void createIsignature(String fileUrl,String fileName,String recordId,String subject){
	    if(!FilenameUtils.isExtension(fileName,PDF)&&!FilenameUtils.isExtension(fileName,OFFICE)){
	        return;
        }
		ByteArrayOutputStream byteArrayOutputStream = null;
		ByteArrayInputStream byteArrayInputStream = null;
		InputStream inputStream = null;
		ByteArrayInputStream imageInputStream = null;
		try {
			byte[] fileBytes = this.load(fileUrl, fileName);
			inputStream = new ByteArrayInputStream(fileBytes);
			String  newFileName = fileName;
			if (!FilenameUtils.isExtension(fileName,PDF)){
				newFileName = FilenameUtils.removeExtension(fileName)+".pdf";
				byteArrayOutputStream = Office2PdfUtil.officeStream2PDF(inputStream, fileName);
				byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
				imageInputStream  = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
			}else {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = inputStream.read(buffer)) > -1 ) {
					baos.write(buffer, 0, len);
				}
				baos.flush();
				byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray());
				imageInputStream  = new ByteArrayInputStream(baos.toByteArray());
			}
			newFileName = System.currentTimeMillis()+"-"+newFileName;
			OSSClientUtil ossClientUtil = new OSSClientUtil();
			String iSignaturePath = Global.getISignature()+ DateUtils.formatDate(new Date(),null)+"/";
//			String iSignaturePath = Global.getISignature();
			ossClientUtil.uploadFile2OSS(byteArrayInputStream,iSignaturePath,newFileName);

			//转图片保存 文件大会慢，之后转异步处理
			new Thread(new ImageConvertThread(imageInputStream, iSignaturePath, newFileName,ossClientUtil)).start();

			String filePath = Global.getAliDownloadUrl() + "/" + iSignaturePath + newFileName;
			String imagePath = Office2PdfUtil.convertPdfFileName(filePath);
			ISignatureDocument iSignatureDocument = new ISignatureDocument();
			User user = UserUtils.getUser();
			iSignatureDocument.setCreateDate(new Date());
			iSignatureDocument.setCreateBy(user);
			iSignatureDocument.setUpdateDate(new Date());
			iSignatureDocument.setUpdateBy(user);
			iSignatureDocument.setFilePath(filePath);
			iSignatureDocument.setFileName(newFileName);
			iSignatureDocument.setCompanyId(user.getComId());
			iSignatureDocument.setRecordId(recordId);
			iSignatureDocument.setSubject(subject);
			iSignatureDocument.setType("PDF");
			iSignatureDocument.setImagePath(imagePath);
			iSignatureDocument.setIsignatureStatus("1");
//			iSignatureDocument.setStatus(Status);
			this.save(iSignatureDocument);
		} catch (Exception e) {
			logger.error("创建电子签章PDF异常，文件名：{}",fileName,e);
		}finally {
			if (inputStream!=null){
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 加载签章文件
	 * @param filePath
	 * @param fileName
	 * @return
	 */
	public byte[] load(String filePath, String fileName) {
		OSSClientUtil ossClientUtil = new OSSClientUtil();
		String key = getPathString(filePath, fileName);
		byte[] bytes = ossClientUtil.downBytesByStream(key, fileName);
		return bytes;
	}

	private String getPathString(String filePath, String fileName) {
		String aliyunUrl = Global.getAliyunUrl();
		String aliDownloadUrl = Global.getAliDownloadUrl();
		String cons = "";
		if (filePath.contains(aliyunUrl)){
			cons = aliyunUrl;
		}else if (filePath.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")){
			cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
		}else {
			cons = aliDownloadUrl;
		}
		String key = filePath.split(cons+"/")[1];
		logger.info("-----------------------------------------");
		logger.info("fileName="+fileName);
		logger.info("key="+key);
		logger.info("-----------------------------------------");
		return key;
	}

	public ISignatureDocument getByRecordId(String recordId) {
		return dao.getByRecordId(recordId);
	}
	public ISignatureDocument getByRImagePath(String imagePath) {
		Workattachment workattachment = workattachmentDao.getByUrl(imagePath);
		if(workattachment!=null && StringUtils.isNotBlank(workattachment.getId())) {
			return dao.getByRecordId(workattachment.getId());
		}else {
			return  new ISignatureDocument();
		}
	}
}