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

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.*;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.projectcontentinfo.dao.ProjectReportDataDao;
import com.jeeplus.modules.projectcontentinfo.entity.ProjectReportData;
import com.jeeplus.modules.projectcontentinfo.service.ProjectReportDataService;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.projectreportnum.entity.ReportNum;
import com.jeeplus.modules.projectreportnum.service.ProjectReportNumService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tools.utils.TwoDimensionCode;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping(value = "${adminPath}/projectreportnum/projectReportNum")
public class ProjectReportNumController extends BaseController {

	@Autowired
	private ProjectReportNumService projectReportNumService;
	@Autowired
	private ProjectReportDataDao projectReportDataDao;
	@Autowired
    private ProjectRecordsService projectRecordsService;
	

	
	/**
	 * 列表页面
	 */

	@RequestMapping(value = {"list", ""})
	public String list(ReportNum reportNum, HttpServletRequest request, HttpServletResponse response, Model model) {
		String userId = UserUtils.getUser().getId();
		reportNum.setUserId(userId);
		Page<ReportNum> page = projectReportNumService.findPage(new Page<ReportNum>(request, response), reportNum);
		model.addAttribute("page", page);
		return "modules/projectreportnum/projectReportNumList";
	}


	@RequestMapping(value = "select")
	public String select(ReportNum reportNum, HttpServletRequest request, HttpServletResponse response, Model model) {
		String userId = UserUtils.getUser().getId();
		reportNum.setUserId(userId);
		Page<ReportNum> page = projectReportNumService.findPage(new Page<ReportNum>(request, response), reportNum);
		model.addAttribute("page", page);
		return "modules/projectreportnum/projectReportNumSel";
	}

    @RequestMapping(value = "download")
    public String download(HttpServletRequest request,RedirectAttributes redirectAttributes,HttpServletResponse response){
		Template template=null;
        try{
			String num = request.getParameter("number");
			String querySite = Global.getConfig("serverDomain")+"/projectreportnum/projectReportNum/report?number="+ URLEncoder.encode(num,"UTF-8");
			num = URLDecoder.decode(num,"UTF-8");
        	int index1 = num.indexOf("【");
        	int index2 = num.indexOf("】");
        	String repType = num.substring(0,index1);
        	String repYear = num.substring(index1+1,index2);
        	String repNum = num.substring(index2+1,num.length());
        	String pa = this.getClass().getResource("/").getPath();
        	if(pa.contains("%20")){
        		pa = pa.replace("%20"," ");
			}
			File path = new File(pa+"/freemarker");
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(path);
			cfg.setDefaultEncoding("UTF-8");
			template = cfg.getTemplate("current.ftl","UTF-8");
			Map<String,Object> data  = new HashMap<>();
			data.put("repType",repType);
			data.put("repYear",repYear);
			data.put("repNum",repNum);
			data.put("querySite","re.xgccpm.com/ccpm_query");
			String commonFileName = UUID.randomUUID().toString();
			String tempPath = pa+"/temp/";
			File temP = new File(tempPath);
			if(!temP.exists()){
                temP.mkdirs();
			}
			String qrCodePath = tempPath + commonFileName + ".png";
			TwoDimensionCode.encoderQRCode(querySite, qrCodePath, "png");//执行生成二维码
			String imageStr = ImageUtil.getImageStr(qrCodePath);
			data.put("qrcode",imageStr);

			File docFile = new File(tempPath+commonFileName+".doc");
			FreemarkerUtil.generateFile(data,template,docFile);

			ResponseUtil.docResponse("防伪报告模板.doc",docFile,response);

			if(docFile != null) docFile.delete(); // 删除doc临时文件
			File imageFile = new File(qrCodePath);
			if(imageFile.exists() && imageFile.isFile()) {
				imageFile.delete();//删除二维码图片临时文件
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "下载失败！失败信息："+e.getMessage());
		}
	    return null;
    }


	/**
	 * 保存记录
	 */
    @ResponseBody
	@RequestMapping(value = "save")
	public Map save(HttpServletRequest request){
    	Map map = new HashMap();
    	try {
			String type = request.getParameter("type");
			String msg = projectReportNumService.save(type);//保存
			map.put("msg",msg);
			if(msg.length()>5){
				map.put("code","0");
			}else {
				map.put("code","1");
			}
		}catch (Exception e){
    		map.put("msg","领取失败");
    		map.put("code","0");
		}
		return map;
	}

	@RequestMapping("report")
	public String report(HttpServletRequest request,Model model) throws Exception{
		ProjectRecords data = new ProjectRecords();
    	String num = request.getParameter("number");
		num = URLDecoder.decode(num,"UTF-8");
		ProjectReportData projectReportData = projectReportDataDao.findByNum(num);
		if(projectReportData != null && projectReportData.getProject() != null) {
			String projectId = projectReportData.getProject().getId();
			data = projectRecordsService.getQueryProjectUsers(projectId);
			data.setReportData(projectReportData);
		}
		model.addAttribute("projectRecords",data);
		return "modules/projectreportnum/reportAuditProject";
	}
	




	



	


	
	
	

}