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

//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.utils.Office2PdfUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.isignature.entity.ISignatureDocument;
import com.jeeplus.modules.isignature.service.ISignatureDocumentService;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.service.ProjectReportDataService;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 电子签章信息Controller
 * @author fgy
 * @version 2018-04-17
 */
@Controller
@RequestMapping(value = "${adminPath}/isignature/iSignatureDocument")
public class ISignatureDocumentController extends BaseController {

	@Autowired
	private ProjectReportDataService projectReportDataService;
	@Autowired
	private ISignatureDocumentService iSignatureDocumentService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private WorkContractInfoService workContractInfoService;

	@ModelAttribute
	public ISignatureDocument get(@RequestParam(required=false) String id) {
		ISignatureDocument entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = iSignatureDocumentService.get(id);
		}
		if (entity == null){
			entity = new ISignatureDocument();
		}
		return entity;
	}
	
	/**
	 * 电子签章信息列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list(ISignatureDocument iSignatureDocument, HttpServletRequest request, HttpServletResponse response, Model model) {
		iSignatureDocument.setCompanyId(UserUtils.getSelectCompany().getId());
		iSignatureDocument.setCreateBy(UserUtils.getUser());
		Page<ISignatureDocument> page = iSignatureDocumentService.findPage(new Page<ISignatureDocument>(request,response), iSignatureDocument);
		model.addAttribute("page",page);
		return "modules/isignature/iSignatureDocumentList";
	}

	/**
	 * 编辑
	 * @return
	 */
	@RequestMapping(value = "sign")
	public String edit(ISignatureDocument iSignatureDocument, HttpServletRequest request,Model model,HttpServletResponse response) {
		ISignatureDocument iSignatureDocument1 = iSignatureDocumentService.getByRecordId(iSignatureDocument.getRecordId());
		//查询
		String path="";
		String type=request.getParameter("type");
		model.addAttribute("iSignatureDocument",iSignatureDocument1);
		Workattachment workattachment=workattachmentService.get(iSignatureDocument.getRecordId());
		if("contract".equals(type)){
			WorkContractInfo workContractInfo=workContractInfoService.get(workattachment.getAttachmentId());
			if(workContractInfo!=null&&workContractInfo.getContractNumPath()!=null){
				path=workContractInfo.getContractNumPath();
				model.addAttribute("contractNum",workContractInfo.getContractNum());
			}
		}
		if("report".equals(type)){
			ProjectReportData projectReportData=projectReportDataService.get(workattachment.getAttachmentId());
			if(projectReportData!=null&&projectReportData.getNumberPath()!=null){
				path=projectReportData.getNumberPath();
				model.addAttribute("contractNum",projectReportData.getNumber());
			}
		}
		model.addAttribute("contractNumPath",path);
		return "modules/isignature/DocumentEdit";
	}

	/**
	 * 编辑
	 * @return
	 */
	@RequestMapping(value = "saveP")
	public ModelAndView saveP(HttpServletRequest request,HttpServletResponse response) {
		return new ModelAndView(new RedirectView("list"));
	}


	/**
	 * 查看，增加，编辑电子签章信息表单页面
	 */
	@RequestMapping(value = "form")
	public String form(ISignatureDocument iSignatureDocument, Model model) {
		if (StringUtils.isNotBlank(iSignatureDocument.getRecordId())){
			ISignatureDocument iSignatureDocument1 = iSignatureDocumentService.getByRecordId(iSignatureDocument.getRecordId());
			model.addAttribute("iSignatureDocument", iSignatureDocument1);
		}else if(StringUtils.isNotBlank(iSignatureDocument.getImagePath())){
			ISignatureDocument iSignatureDocument1 = iSignatureDocumentService.getByRImagePath(iSignatureDocument.getImagePath());
			model.addAttribute("iSignatureDocument", iSignatureDocument1);
		}

		return "modules/isignature/iSignatureDocumentForm";
	}

	/**
	 * 保存电子签章信息
	 */
	@RequestMapping(value = "save")
	public void save(HttpServletRequest request,HttpServletResponse response) throws Exception{
//		iMsgServer2000 iMsgBody = new iMsgServer2000();
//		iMsgBody.Load(request);
//		iSignatureDocumentService.update(iMsgBody);
////		addMessage(redirectAttributes, "保存电子签章信息成功");
//		iMsgBody.MsgTextClear();
//		iMsgBody.MsgFileClear();
//		iMsgBody.Send(response);
	}

	@RequestMapping(value = "load")
	public void load(HttpServletRequest request,HttpServletResponse response) throws Exception{
//		iMsgServer2000 iMsgBody = new iMsgServer2000();
//		iMsgBody.Load(request);
//		String id = iMsgBody.GetMsgByName("RECORDID");
//		String filePath = iMsgBody.GetMsgByName("FILEPATH");
//		String fileName = iMsgBody.GetMsgByName("FILENAME");
//		logger.info("电子签章插件加载文档信息，文档号：{}，文件路径：{}，文件名：{}",id,filePath,fileName);
//		byte [] bytes = null;
//		bytes = iSignatureDocumentService.load(filePath,fileName);
//		//测试代码开始---->
//		FileInputStream inputStream = null;
//		try{
//			File file = new File("C:\\Users\\ssrh\\Desktop\\userTest7.pdf");
//			inputStream =new FileInputStream(file);
//			bytes = new byte[(int) file.length()];
//			inputStream.read(bytes);
//		}finally {
//			inputStream.close();
//		}
		//<----测试代码结束
//		iMsgBody.SetMsgByName("FILENAME",fileName);
//		iMsgBody.MsgFileBody(bytes);					//将文件信息打包
//		iMsgBody.SetMsgByName("STATUS", "打开成功!");			//设置状态信息
//		iMsgBody.Send(response);
	}

	@RequestMapping("seeFile")
	public void seeFile(HttpServletResponse response,HttpServletRequest request,String fileUrl,String fileName){
        byte[] fileBytes = iSignatureDocumentService.load(fileUrl, fileName);
        InputStream inputStream = new ByteArrayInputStream(fileBytes);
        try {
            Office2PdfUtil.officeStream2PDF(inputStream,response.getOutputStream(),fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 下载附件
     */
    @RequestMapping("/download")
    public void downLoadAttach(ISignatureDocument iSignatureDocument,HttpServletRequest request, HttpServletResponse response) throws IOException {
        iSignatureDocument = iSignatureDocumentService.getByRecordId(iSignatureDocument.getRecordId());
        if(iSignatureDocument == null){
            return;
        }
        String filePath = iSignatureDocument.getFilePath();
        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;
        }
        final String[] arr = filePath.split(cons + "/");
        String key = arr[1];
        new OSSClientUtil().downByStream(key, iSignatureDocument.getFileName(), response,request.getHeader("USER-AGENT"));
    }
}