package cn.hmsoft.skill.school.control;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.helper.excel.ExcelReaderHelper;
import cn.hmsoft.helper.pdf.ItextDocumentModel;
import cn.hmsoft.helper.pdf.ItextPdfHelper;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.skill.constants.StdMateialType;
import cn.hmsoft.skill.data.dao.school.SchoolAspectDao;
import cn.hmsoft.skill.data.dao.school.SchoolRegDao;
import cn.hmsoft.skill.data.dao.std.StdEnrolDao;
import cn.hmsoft.skill.data.model.school.SchoolReg;
import cn.hmsoft.skill.data.model.std.StdEnrolSubject;
import cn.hmsoft.skill.data.model.std.StdReg;
import cn.hmsoft.skill.helper.ArtParamHelper;
import cn.hmsoft.skill.helper.SkillMateialHelper;
import cn.hmsoft.skill.helper.SkillParamHelper;
import cn.hmsoft.skill.school.service.SchoolArrangeService;
import cn.hmsoft.skill.school.ticket.SkillTicketHelper;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.*;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;

@RestController
public class SchoolArrangeControl extends SchoolAbstractControl {
	@Autowired
	private SchoolRegDao daoSchool;
	@Autowired
	private SchoolAspectDao daoAspect;
	@Autowired
	private SchoolArrangeService sArrange;

	@Autowired
	private StdEnrolDao daoEnrol;

	@RequestMapping("/school/school/arrange/init")
	public Ajax init() {
		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		Map<String, Object> map = new HashMap<String, Object>();
		// 是否可以编排
		if (school.getEnrol_end_time().isAfter(LocalDateTime.now()))
			map.put("AllowArrange", false);
		else
			map.put("AllowArrange", true);
		map.put("AspectArray", this.daoAspect.totalAspect(school.getSchool_id()));
		map.put("SubjectArray", this.daoAspect.listSchoolSubject(school.getSchool_id()));
		map.put("SchoolReg", school);
		map.put("StdEnrolSubjectCount",
				this.daoAspect.count(StdEnrolSubject.class, "school_id", school.getSchool_id()));
		map.put("AspectScoreCount", this.daoAspect.findObject(Integer.class,
				"select count(1) from std_enrol where school_id=? and std_score is not null", school.getSchool_id()));
		return new Ajax(map);

	}

	@RequestMapping("/school/school/arrange/upload")
	public Ajax upload(MultipartFile file) throws Exception {
		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		final List<List<String>> list = ExcelReaderHelper.readSheet(file.getOriginalFilename(), file.getInputStream(), 1,
				6 + SkillParamHelper.MaxExamSubjectCount * 6);


		if (list != null && list.size() > 0) {
			new Thread() {
				public void run() {
					SpringHelper.getBean(SchoolArrangeService.class).upload(list, school.getSchool_id());
				}
			}.start();
		} else
			throw new BusinessException("在上传的文件中未找到有效的数据！");
		return new Ajax();

	}

	@RequestMapping("/school/school/arrange/ticket/view")
	public void view(String ticket_note, String ticket_title) {
		SchoolReg s = new SchoolReg();
		s.setSchool_id(this.getSchool().getSchool_id());
		s.setTicket_title(ticket_title);
		s.setTicket_note(ticket_note);
		this.daoAspect.update(s);

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		FrameAssertUtil.isNotEmpty(school.getTicket_title(), "请设置准考证标题");
		FrameAssertUtil.isNotEmpty(school.getTicket_note(), "请设置准考证考试须知");
		String sql = "select * from std_enrol_subject sb where school_id=? ";
		StdEnrolSubject sb = this.daoAspect.findBySql(StdEnrolSubject.class, sql, school.getSchool_id());
		FrameAssertUtil.isNotNull(sb, "未上传编排信息，无法预留准考证");
		StdReg std = this.daoAspect.find(StdReg.class, sb.getStd_id());
		Map<String, Object> enrol = this.daoEnrol.findEnrol(sb.getStd_id(), sb.getAspect_id());
		File file = SkillTicketHelper.makeTicketFile(std, daoEnrol, school, enrol);
		this.downloadFile(file, school.getSchool_name() + "准考证模版.pdf", true);

	}

	@RequestMapping("/school/school/arrange/ticket/all")
	public Ajax allTicket(String ticket_note, String ticket_title) {
		SchoolReg s = new SchoolReg();
		s.setSchool_id(this.getSchool().getSchool_id());
		s.setTicket_title(ticket_title);
		s.setTicket_note(ticket_note);
		this.daoAspect.update(s);
		new Thread() {
			public void run() {
				SpringHelper.getBean(SchoolArrangeService.class).makeAllTicket(s.getSchool_id());
			}
		}.start();

		return new Ajax();
	}

	@RequestMapping("/school/school/arrange/ticket/school")
	public void schoolTicket() throws Exception {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());

		File dest = SkillMateialHelper.makeStdImageFile(StdMateialType.StdTicket, "T" + school.getSchool_id() + ".pdf");

		if (dest.exists())
			dest.delete();
		this.sArrange.mergePdf(school.getSchool_id());
		this.downloadFile(dest,
				SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-考生准考证.pdf");

	}

	@RequestMapping("/school/school/arrange/desk")
	public void desk() {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		File tempFile = SkillMateialHelper.createTempFile();

		Document doc = null;
		try {
			ItextDocumentModel model = new ItextDocumentModel();
			model.rotate();
			doc = model.prepareDocument(tempFile);
			PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
			doc.setFont(pdfFont);


			// 每页考生数量
			int pageStdCount = 20;
			// 计算每个考生的margin
			int top = 0, right = 10, bottom = 5, left = 5;
			int std_row_margin = 0;
			// 卡片之间的检录
			int marginTop = 10, marginRight = 10, marginBottom = 10, marginLeft = 10;
//			String sql = "select exam_seq,room_addr,std_name,cert_id,exam_id,ticket_num,std_sex,std_image,std_param4,sb.std_id from std_enrol_subject sb,std_reg s,std_enrol e where sb.std_id=e.std_id and sb.aspect_id=e.aspect_id and sb.STD_ID=s.std_id and sb.school_id=? and subject_order=3 order by ticket_num";
//			List<Map<String, Object>> stdMap = this.daoAspect.listMapBySql(sql, school.getSchool_id());
			String sql = "select exam_seq,room_addr,std_name,cert_id,exam_id,ticket_num,std_sex,std_image,std_param4,sb.std_id,sb.subject_name from std_enrol_subject " +
					"sb,std_reg s,std_enrol e where sb.std_id=e.std_id and sb.aspect_id=e.aspect_id and sb.STD_ID=s.std_id and sb.school_id=?  " +
					"order by subject_name,room_addr,ticket_num";
			List<Map<String, Object>> stdMap = this.daoAspect.listMapBySql(sql, school.getSchool_id());
			Map<String, List<Map<String, Object>>> roomArray = new LinkedHashMap<String, List<Map<String, Object>>>();
			String room_addr = "";
			for (Map<String, Object> map : stdMap) {
				String addr = map.get("room_addr").toString() + "--" + map.get("subject_name").toString();
				if (!addr.equals(room_addr)) {
					roomArray.put(addr, new ArrayList<Map<String, Object>>());
				}
				room_addr = addr;
				roomArray.get(addr).add(map);
			}
			int roomIndex = 1;

			// 每行考生数
			float[] mainCols = new float[5];
			for (int i = 0; i < mainCols.length; i++)
				mainCols[i] = 100 / mainCols.length;
			for (String addr : roomArray.keySet()) {
				Table mainTable = new Table(mainCols);
				this.createDeskNewPage(doc, roomArray.get(addr), school, addr);
				// 宽度 及无边框设置
				mainTable.setWidthPercent(100).setBorder(null);
//				boolean hasStd = false;
				for (int stdIndex = 0; stdIndex < roomArray.get(addr).size(); stdIndex++) {
					Map<String, Object> std = roomArray.get(addr).get(stdIndex);
					Table stdTable = new Table(new float[]{1});
					stdTable.setWidthPercent(100);

					stdTable.addCell(new Cell().add(this.createStdNormalSeat(std.get("room_addr").toString(), std_row_margin, std))
							.setPaddings(top, right, bottom, left));

					mainTable.addCell(new Cell().add(stdTable).setMarginTop(marginTop).setMarginRight(marginRight)
							.setMarginBottom(marginBottom).setMarginLeft(marginLeft).setBorder(null));

					if (stdIndex > 0) {
						// 判断分页
						if ((stdIndex + 1) % pageStdCount == 0 || (stdIndex + 1) == roomArray.get(addr).size()) {
							doc.add(mainTable);
							// 判断本考场是否还有考生
							if (stdIndex < roomArray.get(addr).size() - 1) {
								doc.add(new AreaBreak());
								this.createDeskNewPage(doc, roomArray.get(addr), school, addr);
//								hasStd = true;
							} else {
								// 没考生了
//								hasStd = false;
							}
							mainTable = new Table(mainCols);
							// 宽度 及无边框设置
							mainTable.setWidthPercent(100).setBorder(null);
						}

					}

				}
//				if (hasStd) {
//					doc.add(mainTable);
//				}
				if (roomIndex < roomArray.keySet().size() - 1)
					doc.add(new AreaBreak());
				roomIndex++;

			}

			ItextPdfHelper.closePdf(doc);
			this.downloadFile(tempFile,
					SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-笔试桌贴表.pdf",
					true);
			// return tempFile;
		} catch (Exception e) {
			LogHelper.error(e);
			this.writeAlert("无法生成pdf文件，请联系系统管理员");
		}
	}

	/**********************
	 * 创建普通的单个考生桌贴
	 */
	private Table createStdNormalSeat(String room_addr, int std_row_margin, Map<String, Object> std) {
		float[] cs = {1, 1};
		Table table = new Table(cs);
		// 每个考生的宽度
		table.setWidthPercent(100).setBorder(null);

		String value = room_addr;
		table.addCell(new Cell(1, 2).add(value).setBorder(null).setFontSize(12).setMarginTop(std_row_margin))
				.setTextAlignment(TextAlignment.CENTER).setVerticalAlignment(VerticalAlignment.MIDDLE);

		if (std.containsKey("exam_seq") && std.get("exam_seq") != null && std.get("exam_seq").toString().length() > 0)
			table.addCell(new Cell(1, 2).add(std.get("exam_seq").toString()).setBorder(null).setFontSize(12)
							.setMarginTop(std_row_margin)).setTextAlignment(TextAlignment.CENTER)
					.setVerticalAlignment(VerticalAlignment.MIDDLE);

		table.addCell(new Cell(1, 1).add(std.get("ticket_num").toString()).setBold().setBorder(null).setFontSize(10)
				.setMarginTop(std_row_margin).setTextAlignment(TextAlignment.CENTER).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE));
//		table.addCell(new Cell(1, 1).add(std.get("subject_name").toString()).setBold().setBorder(null).setFontSize(10)
//				.setMarginTop(std_row_margin).setTextAlignment(TextAlignment.CENTER).setBold()
//				.setVerticalAlignment(VerticalAlignment.MIDDLE));
		// 考生姓名
		String std_name = std.get("std_name").toString();
		int font = 10;
		if (std_name.length() == 4)
			font = 9;
		else if (std_name.length() == 5)
			font = 7;
		else if (std_name.length() > 5)
			font = 5;
		table.addCell(
				new Cell(1, 1).add(std_name).setBorder(null).setBold().setFontSize(font).setMarginTop(std_row_margin)
						.setTextAlignment(TextAlignment.CENTER).setVerticalAlignment(VerticalAlignment.MIDDLE));
		// 证件号码
		table.addCell(new Cell(1, 2).add(std.get("cert_id").toString()).setBorder(null).setBold().setFontSize(12)
						.setMarginTop(std_row_margin)).setTextAlignment(TextAlignment.CENTER)
				.setVerticalAlignment(VerticalAlignment.MIDDLE);

		return table;
	}

	@RequestMapping("/school/school/arrange/sign")
	public void sign() {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		File tempFile = SkillMateialHelper.createTempFile();

		Document doc = null;
		try {
			ItextDocumentModel model = new ItextDocumentModel();
			// model.rotate();
			doc = model.prepareDocument(tempFile);
			PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
			doc.setFont(pdfFont);

			// 每页考生数量
			int pageStdCount = 16;
			// 卡片之间的间距
			int marginTop = 5, marginRight = 10, marginBottom = 5, marginLeft = 10;
			// 每行考生数
			float[] mainCols = new float[4];
			for (int i = 0; i < mainCols.length; i++)
				mainCols[i] = 100 / mainCols.length;
			// 考生信息间距
			int std_row_margin = 0;
			String sql = "select room_addr,std_name,cert_id,exam_id,ticket_num,std_sex,std_image,std_param4,sb.std_id,sb.subject_name from " +
					"std_enrol_subject " +
					"sb," +
					"std_reg s,std_enrol e where sb.std_id=e.std_id and sb.aspect_id=e.aspect_id and sb.STD_ID=s.std_id and sb.school_id=?  order " +
					"by subject_name,room_addr,ticket_num";
			List<Map<String, Object>> stdMap = this.daoAspect.listMapBySql(sql, school.getSchool_id());

			Map<String, List<Map<String, Object>>> roomArray = new LinkedHashMap<String, List<Map<String, Object>>>();
			String room_addr = "";
			for (Map<String, Object> map : stdMap) {
				String addr = map.get("room_addr").toString() + "--" + map.get("subject_name").toString();
				if (!addr.equals(room_addr)) {
					roomArray.put(addr, new ArrayList<Map<String, Object>>());
				}
				room_addr = addr;
				roomArray.get(addr).add(map);
			}
			int roomIndex = 1;
			for (String addr : roomArray.keySet()) {
				int exam_seq = 1;
				Table mainTable = new Table(mainCols);
				// 宽度 及无边框设置
				mainTable.setWidthPercent(100).setBorder(null);

				this.createSignNewPage(doc, roomArray.get(addr), school, addr);

				for (Map<String, Object> map : roomArray.get(addr)) {
					StdReg std = this.daoAspect.find(StdReg.class, (int) map.get("std_id"));
					float[] cs = {1, 1};
					Table table = new Table(cs);
					table.setWidthPercent(100).setBorder(null);
					// 图片
					Image imgStdUpload = SkillMateialHelper.createStdImage(std, std.getStd_image(), 64, 96);

					Cell cell = new Cell(1, 2).setBorder(null).add(imgStdUpload)
							.setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setMarginLeft(5);
					table.addCell(cell);

					// 准考证号
					table.addCell(new Cell(1, 1).add(map.get("ticket_num").toString()).setBorder(null)
							.setMarginTop(std_row_margin).setBold().setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setTextAlignment(TextAlignment.CENTER).setVerticalAlignment(VerticalAlignment.MIDDLE)
							.setFontSize(map.get("ticket_num").toString().length() > 6 ? 7 : 11));

					// 姓名
					String std_name = std.getStd_name();
					int std_font = 9;
					if (std_name.length() == 4)
						std_font = 7;
					else if (std_name.length() == 5)
						std_font = 6;
					else if (std_name.length() > 5) {
						std_font = 5;
					}
					table.addCell(new Cell(1, 1).add(std_name).setBorder(null).setMarginTop(std_row_margin).setBold()
							.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(std_font));

					// 证件号码
					table.addCell(new Cell(1, 2).add(std.getCert_id()).setBorder(null).setMarginTop(std_row_margin)
							.setTextAlignment(TextAlignment.CENTER).setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(11).setBold());
//					table.addCell(new Cell(1, 2).add(map.get("subject_name").toString()).setBorder(null).setMarginTop(std_row_margin)
//							.setTextAlignment(TextAlignment.CENTER).setHorizontalAlignment(HorizontalAlignment.CENTER)
//							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(10).setBold());

					// 签名

					table.addCell(new Cell(1, 2).add((exam_seq) + ".签名 _____________").setBorder(null)
							.setMarginTop(std_row_margin + 5).setTextAlignment(TextAlignment.CENTER)
							.setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(10));

					mainTable.addCell(new Cell().add(table).setMarginTop(marginTop).setMarginRight(marginRight)
							.setMarginBottom(marginBottom).setMarginLeft(marginLeft).setBorder(null)
							.setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE));

					if (exam_seq % pageStdCount == 0 || exam_seq == roomArray.get(addr).size()) {
						doc.add(mainTable);
						// 判断需要增加新的一页，还有考场
						if (exam_seq < roomArray.get(addr).size()) {
							// 还是本考场
							doc.add(new AreaBreak());
							this.createSignNewPage(doc, roomArray.get(addr), school, addr);
							mainTable = new Table(mainCols);
							// 宽度 及无边框设置
							mainTable.setWidthPercent(100).setBorder(null);
						}
					}

					exam_seq++;

				}
//				if (exam_seq % pageStdCount != 0) {
//					doc.add(mainTable);
				if (roomIndex < roomArray.size()) {
					doc.add(new AreaBreak());
					mainTable = new Table(mainCols);
					// 宽度 及无边框设置
					mainTable.setWidthPercent(100).setBorder(null);
				} else {
					// 没有考场了，不管
				}
//				}
				roomIndex++;
			}

			ItextPdfHelper.closePdf(doc);
			this.downloadFile(tempFile,
					SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-考生签字单.pdf",
					true);
			// return tempFile;
		} catch (Exception e) {
			LogHelper.error(e);
			this.writeAlert("无法生成pdf文件，请联系系统管理员");
		}
	}

	private void createSignNewPage(Document doc, List<Map<String, Object>> stdArray, SchoolReg school,
	                               String room_addr) {
		Paragraph p1 = new Paragraph(SkillParamHelper.CurrentYear + school.getTicket_title() + "座次表").setFontSize(16)
				.setBold().setTextAlignment(TextAlignment.CENTER);
		doc.add(p1);

		p1 = new Paragraph("考场地址：" + stdArray.get(0).get("room_addr").toString() + "     考试科目：" + stdArray.get(0).get("subject_name").toString() + "      考生总数：" + stdArray.size())
				.setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginLeft(20).setMarginTop(-5);
		doc.add(p1);

	}

	@RequestMapping("/school/school/arrange/confirm")
	public void confirm() {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		File tempFile = SkillMateialHelper.createTempFile();

		Document doc = null;
		try {
			ItextDocumentModel model = new ItextDocumentModel();
			// model.rotate();
			doc = model.prepareDocument(tempFile);
			PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
			doc.setFont(pdfFont);

//			String sql = "select * from std_enrol e where e.school_id=? and ticket_num is not null order by ticket_num";
			String sql = "SELECT e.*,sb.subject_name FROM std_enrol_subject sb,std_enrol e WHERE sb.std_id=e.std_id AND sb.aspect_id=e.aspect_id AND e.school_id=? AND ticket_num IS NOT NULL ORDER BY ticket_num";
			for (Map<String, Object> e : this.daoEnrol.listMapBySql(sql, school.getSchool_id())) {
				StdReg std = this.daoAspect.find(StdReg.class, e.get("std_id"));
				Map<String, Object> enrol = this.daoEnrol.findEnrol(Integer.parseInt(e.get("std_id").toString()),
						Integer.parseInt(e.get("aspect_id").toString()));
				this.addStdConfigm(doc, std, daoEnrol, school, enrol, e);
				doc.add(new AreaBreak());
			}

			ItextPdfHelper.closePdf(doc);
			this.downloadFile(tempFile,
					SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-考生信息确认表.pdf",
					true);
		} catch (Exception e) {
			LogHelper.error(e);
			this.writeAlert("无法生成pdf文件，请联系系统管理员");
		}
	}

	protected void addStdConfigm(Document doc, StdReg std, StdEnrolDao daoEnrol, SchoolReg school,
	                             Map<String, Object> enrol, Map<String, Object> e) {
		Image image = SkillMateialHelper.createStdImage(std, std.getStd_image(), 104, 140);

		// 添加标题
		Table headTable = new Table(new float[]{1}).setWidthPercent(100).setBorder(null);
		headTable.addCell(new Cell(1, 1).add(school.getSchool_name()).setFontSize(18).setBorder(null).setBold()
				.setTextAlignment(TextAlignment.CENTER).setHorizontalAlignment(HorizontalAlignment.CENTER)
				.setMarginRight(5));
		headTable.addCell(new Cell(1, 1).add(SkillParamHelper.CurrentYear
						+ (StringHelper.isEmpty(school.getTicket_title()) ? "" : (school.getTicket_title() + "学生信息确认表")))
				.setFontSize(18).setBorder(null).setBold().setTextAlignment(TextAlignment.CENTER)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setMarginRight(5));
		doc.add(headTable.setMarginTop(30));

		// 考生信息框
		Table stdTable = new Table(new float[]{1, 2, 1, 2, 2f}).setWidthPercent(100);
		stdTable.addCell(new Cell(1, 1).add("证件号码").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));

		stdTable.addCell(new Cell(1, 3).add(std.getCert_id()).setFontSize(20).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		// 考生照片
		stdTable.addCell(new Cell(6, 1).add(new Paragraph().add(image)).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setMarginTop(0));
		// stdTable.addCell(new Cell(4, 1).add(
		// stdUploadImage).setVerticalAlignment(VerticalAlignment.MIDDLE).setMarginTop(0));

		stdTable.addCell(new Cell(1, 1).add("考生姓名").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
		// 姓名
		stdTable.addCell(new Cell(1, 1).add(std.getStd_name()).setFontSize(16).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		stdTable.addCell(new Cell(1, 1).add("性别").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
		// 性别
		stdTable.addCell(new Cell(1, 1).add(std.getStd_sex() == null ? "" : std.getStd_sex()).setFontSize(16).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		stdTable.addCell(new Cell(1, 1).add("准考证号").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
		// 准考证号
		stdTable.addCell(new Cell(1, 1).add(enrol.get("ticket_num").toString()).setFontSize(16).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		stdTable.addCell(new Cell(1, 1).add("高考报名号").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));

		stdTable.addCell(new Cell(1, 1).add(std.getExam_id()).setFontSize(16).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

//		stdTable.addCell(new Cell(1, 1).add("毕业学校").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
//				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
//		// 毕业学校
//		stdTable.addCell(new Cell(1, 3).add(std.getStd_school() + "").setFontSize(14)
//				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
//				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		stdTable.addCell(new Cell(1, 1).add("报考专业").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
		// 报考专业
		stdTable.addCell(new Cell(1, 3).add(enrol.get("aspect_name").toString()).setFontSize(14)
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));
		stdTable.addCell(new Cell(1, 1).add("报考科目").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
		// 报考专业
		stdTable.addCell(new Cell(1, 3).add(e.get("subject_name").toString()).setFontSize(14)
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

//		stdTable.addCell(new Cell(1, 1).add("联系电话1").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
//				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
//		// 报考专业
//		stdTable.addCell(new Cell(1, 1).add(std.getStd_mobile1() == null ? "" : std.getStd_mobile1()).setFontSize(12)
//				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
//				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));
//
//		stdTable.addCell(new Cell(1, 1).add("联系电话2").setFontSize(12).setVerticalAlignment(VerticalAlignment.MIDDLE)
//				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));
//
//		stdTable.addCell(new Cell(1, 1).add(std.getStd_mobile2() == null ? "" : std.getStd_mobile2()).setFontSize(12)
//				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
//				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

//		stdTable.addCell(new Cell(1, 1).add("录取通知书邮寄地址").setFontSize(9).setVerticalAlignment(VerticalAlignment.MIDDLE)
//				.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER));

//		stdTable.addCell(new Cell(1, 4).add(std.getLink_addr() == null ? "" : std.getLink_addr()).setFontSize(12)
//				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.LEFT)
//				.setTextAlignment(TextAlignment.LEFT).setMarginLeft(8));

		stdTable.addCell(new Cell(1, 5).add("以上信息请考生核对无误后确认签字").setFontSize(14).setBold()
				.setVerticalAlignment(VerticalAlignment.MIDDLE).setHorizontalAlignment(HorizontalAlignment.CENTER)
				.setTextAlignment(TextAlignment.CENTER));
		doc.add(stdTable.setMarginTop(20));
		Paragraph p1 = new Paragraph().add("签字：                    ").setMarginLeft(400);
		doc.add(p1.setMarginTop(30));
		p1 = new Paragraph().add("时间：        年    月    日").setMarginLeft(400);
		doc.add(p1.setMarginTop(20));

	}

	@RequestMapping("/school/school/arrange/door")
	public void door() {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		File tempFile = SkillMateialHelper.createTempFile();

		Document doc = null;
		try {
			ItextDocumentModel model = new ItextDocumentModel();
			model.rotate();
			doc = model.prepareDocument(tempFile);
			PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
			doc.setFont(pdfFont);


			// 卡片之间的检录
			int marginTop = 10, marginRight = 10, marginBottom = 10, marginLeft = 10;
			String sql = "SELECT room_addr,subject_name,min(ticket_num) min,max(ticket_num) max FROM std_enrol_subject sb,std_enrol e WHERE sb.std_id=e" +
					".std_id AND sb.aspect_id=e.aspect_id AND sb.school_id=? GROUP BY subject_name,room_addr";
			List<Map<String, Object>> roomArray = this.daoAspect.listMapBySql(sql, school.getSchool_id());


			// 每行考生数


			for (Map<String, Object> addr : roomArray) {


				doc.add(new Paragraph(ArtParamHelper.getParamValue("AppTitle",
						"")).setFontSize(40)
						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(30));
				doc.add(new Paragraph("考场地点 ：" + addr.get("room_addr").toString()).setFontSize(30)
						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(25));
				doc.add(new Paragraph("考试科目 ：" + addr.get("subject_name").toString()).setFontSize(30)
						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(25));
				doc.add(new Paragraph("准考证号：").setFontSize(30)
						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(25));
//				doc.add(new Paragraph(addr.get("min").toString().replace(".0", "") + "-" + addr.get("max").toString().replace(".0", "")).setFontSize(35)
//						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(25));
				doc.add(new Paragraph(addr.get("min").toString() + "-" + addr.get("max").toString()).setFontSize(35)
						.setBold().setTextAlignment(TextAlignment.CENTER).setMarginTop(25));


				doc.add(new AreaBreak());


			}

			ItextPdfHelper.closePdf(doc);
			this.downloadFile(tempFile,
					SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-笔试门贴表.pdf",
					true);
			// return tempFile;
		} catch (Exception e) {
			LogHelper.error(e);
			this.writeAlert("无法生成pdf文件，请联系系统管理员");
		}
	}

	@RequestMapping("/school/school/arrange/desk2")
	public void desk2() {

		SchoolReg school = this.daoSchool.find(this.getSchool().getSchool_id());
		File tempFile = SkillMateialHelper.createTempFile();

		Document doc = null;
		try {
			ItextDocumentModel model = new ItextDocumentModel();
			// model.rotate();
			doc = model.prepareDocument(tempFile);
			PdfFont pdfFont = ItextPdfHelper.getPdfFontSTSong();
			doc.setFont(pdfFont);

			// 每页考生数量
			int pageStdCount = 16;
			// 卡片之间的间距
			int marginTop = 5, marginRight = 10, marginBottom = 5, marginLeft = 10;
			// 每行考生数
			float[] mainCols = new float[4];
			for (int i = 0; i < mainCols.length; i++)
				mainCols[i] = 100 / mainCols.length;
			// 考生信息间距
			int std_row_margin = 0;
			String sql = "select exam_seq,room_addr,subject_name,std_name,cert_id,exam_id,ticket_num,std_sex,std_image,std_param4,sb.std_id,sb.subject_name " +
					"from " +
					"std_enrol_subject sb,std_reg s,std_enrol e where sb.std_id=e.std_id and sb.aspect_id=e.aspect_id and sb.STD_ID=s.std_id and sb" +
					".school_id=?  order by subject_name,room_addr,ticket_num";
			List<Map<String, Object>> stdMap = this.daoAspect.listMapBySql(sql, school.getSchool_id());

			Map<String, List<Map<String, Object>>> roomArray = new LinkedHashMap<String, List<Map<String, Object>>>();
			String room_addr = "";
			for (Map<String, Object> map : stdMap) {
				String addr = map.get("room_addr").toString() + "--" + map.get("subject_name").toString();
				if (!addr.equals(room_addr)) {
					roomArray.put(addr, new ArrayList<Map<String, Object>>());
				}
				room_addr = addr;
				roomArray.get(addr).add(map);
			}
			int roomIndex = 1;
			for (String addr : roomArray.keySet()) {
				int exam_seq = 1;
				Table mainTable = new Table(mainCols);
				// 宽度 及无边框设置
				mainTable.setWidthPercent(100).setBorder(null);

				this.createDeskNewPage(doc, roomArray.get(addr), school, addr);

				for (Map<String, Object> map : roomArray.get(addr)) {
					StdReg std = this.daoAspect.find(StdReg.class, (int) map.get("std_id"));
					float[] cs = {1, 1};
					Table table = new Table(cs);
					table.setWidthPercent(100).setBorder(null);
					// 图片
					Image imgStdUpload = SkillMateialHelper.createStdImage(std, std.getStd_image(), 64, 96);

					Cell cell = new Cell(1, 2).setBorder(null).add(imgStdUpload)
							.setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setMarginLeft(5);
					table.addCell(cell);

					// 准考证号
					table.addCell(new Cell(1, 1).add(map.get("ticket_num").toString()).setBorder(null)
							.setMarginTop(std_row_margin).setBold().setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setTextAlignment(TextAlignment.CENTER).setVerticalAlignment(VerticalAlignment.MIDDLE)
							.setFontSize(map.get("ticket_num").toString().length() > 6 ? 7 : 11));

					// 姓名
					String std_name = std.getStd_name();
					int std_font = 9;
					if (std_name.length() == 4)
						std_font = 7;
					else if (std_name.length() == 5)
						std_font = 6;
					else if (std_name.length() > 5) {
						std_font = 5;
					}
					table.addCell(new Cell(1, 1).add(std_name).setBorder(null).setMarginTop(std_row_margin).setBold()
							.setHorizontalAlignment(HorizontalAlignment.CENTER).setTextAlignment(TextAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(std_font));

					// 证件号码
					table.addCell(new Cell(1, 2).add(std.getCert_id()).setBorder(null).setMarginTop(std_row_margin)
							.setTextAlignment(TextAlignment.CENTER).setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(11).setBold());

					// 签名
					if (map.containsKey("exam_seq") && map.get("exam_seq") != null && map.get("exam_seq").toString().length() > 0)

						table.addCell(new Cell(1, 2).add("座位号：" + map.get("exam_seq").toString()).setBorder(null)
								.setMarginTop(std_row_margin + 5).setTextAlignment(TextAlignment.CENTER)
								.setHorizontalAlignment(HorizontalAlignment.CENTER)
								.setVerticalAlignment(VerticalAlignment.MIDDLE).setFontSize(12));

					mainTable.addCell(new Cell().add(table).setMarginTop(marginTop).setMarginRight(marginRight)
							.setMarginBottom(marginBottom).setMarginLeft(marginLeft).setBorder(null)
							.setHorizontalAlignment(HorizontalAlignment.CENTER)
							.setVerticalAlignment(VerticalAlignment.MIDDLE));

					if (exam_seq % pageStdCount == 0 || exam_seq == roomArray.get(addr).size()) {
						doc.add(mainTable);
						// 判断需要增加新的一页，还有考场
						if (exam_seq < roomArray.get(addr).size()) {
							// 还是本考场
							doc.add(new AreaBreak());
							this.createDeskNewPage(doc, roomArray.get(addr), school, addr);
							mainTable = new Table(mainCols);
							// 宽度 及无边框设置
							mainTable.setWidthPercent(100).setBorder(null);
						}
					}

					exam_seq++;

				}
//				if (exam_seq % pageStdCount != 0) {
//					doc.add(mainTable);
				if (roomIndex < roomArray.size()) {
					doc.add(new AreaBreak());
					mainTable = new Table(mainCols);
					// 宽度 及无边框设置
					mainTable.setWidthPercent(100).setBorder(null);
				} else {
					// 没有考场了，不管
				}
//				}
				roomIndex++;
			}

			ItextPdfHelper.closePdf(doc);
			this.downloadFile(tempFile,
					SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-考场桌贴表.pdf",
					true);
			// return tempFile;
		} catch (Exception e) {
			LogHelper.error(e);
			this.writeAlert("无法生成pdf文件，请联系系统管理员");
		}
	}

	private void createDeskNewPage(Document doc, List<Map<String, Object>> stdArray, SchoolReg school,
	                               String room_addr) {
		Paragraph p1 = new Paragraph(SkillParamHelper.CurrentYear + school.getTicket_title() + "桌贴").setFontSize(16)
				.setBold().setTextAlignment(TextAlignment.CENTER);
		doc.add(p1);

		p1 = new Paragraph("考场地址：" + stdArray.get(0).get("room_addr").toString() + "     考试科目：" + stdArray.get(0).get("subject_name").toString() + "   考生总数：" + stdArray.size())
				.setFontSize(12).setBold().setTextAlignment(TextAlignment.LEFT).setMarginLeft(20).setMarginTop(-5);
		doc.add(p1);

	}

}
