package cn.hmsoft.skill.school.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.utils.PdfMerger;

import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.skill.constants.SkillLogType;
import cn.hmsoft.skill.constants.StdMateialType;
import cn.hmsoft.skill.data.dao.school.SchoolLogDao;
import cn.hmsoft.skill.data.dao.school.SchoolRegDao;
import cn.hmsoft.skill.data.dao.std.StdEnrolDao;
import cn.hmsoft.skill.data.dao.std.StdEnrolSubjectDao;
import cn.hmsoft.skill.data.dao.std.StdRegDao;
import cn.hmsoft.skill.data.model.school.SchoolReg;
import cn.hmsoft.skill.data.model.std.StdEnrol;
import cn.hmsoft.skill.data.model.std.StdEnrolSubject;
import cn.hmsoft.skill.data.model.std.StdReg;
import cn.hmsoft.skill.helper.SkillMateialHelper;
import cn.hmsoft.skill.helper.SkillParamHelper;
import cn.hmsoft.skill.school.ticket.SkillTicketHelper;

@Service
public class SchoolArrangeService {

	@Autowired
	private StdRegDao daoStd;
	@Autowired
	private StdEnrolDao daoEnrol;
	@Autowired
	private SchoolRegDao daoSchool;
	@Autowired
	private SchoolLogDao daoLog;

	@Autowired
	private StdEnrolSubjectDao daoSubject;

	public void upload(List<List<String>> array, int school_id) {
		// 清理
		this.daoSubject.clear(school_id);
		this.daoEnrol.clearTicket(school_id);
		int index = 1;
		int std_count = 0;
		for (List<String> list : array) {
			index++;
			String ticket_num = list.get(1);
			String cert_id = list.get(2);
			String std_name = list.get(3);
			String aspect_name = list.get(4);

			StdReg std = this.daoStd.find("cert_id", cert_id);
			FrameAssertUtil.isNotNull(std, ("第【" + index + "】行错误：不存在证件号码为【" + cert_id + "】的考生"));
			// 考生姓名就不验证了
			Map<String, Object> enrol = this.daoEnrol.findEnrol(school_id, std.getStd_id(), aspect_name);
			FrameAssertUtil.isNotNull(enrol, ("第【" + index + "】行错误：考生未报考专业【" + aspect_name + "】"));

			int sb_count = 1;
			for (int i = 0; i < SkillParamHelper.MaxExamSubjectCount; i++) {
				String sb_name = list.get(5 + i * 6);
				String wait_exam_time = list.get(6 + i * 6);
				String wait_room_addr = list.get(7 + i * 6);
				String exam_time = list.get(8 + i * 6);
				String room_addr = list.get(9 + i * 6);
				String exam_seq = list.get(10 + i * 6);
//				String exam_time = list.get(6 + i * 5);
//				String wait_exam_time = list.get(7 + i * 5);
//				String room_addr = list.get(8 + i * 5);
//				String exam_seq = list.get(9 + i * 5);
				
				if (StringHelper.isEmpty(sb_name))
					continue;

				StdEnrolSubject sb = new StdEnrolSubject();
				sb.setAspect_id((int) enrol.get("aspect_id"));

				sb.setSchool_id(school_id);
				sb.setStd_id(std.getStd_id());
				sb.setSubject_name(sb_name);
				sb.setSubject_order(sb_count);

				sb.setExam_seq(exam_seq);
				sb.setExam_time(exam_time);
				sb.setRoom_addr(room_addr);
				sb.setWait_exam_time(wait_exam_time);
				sb.setWait_room_addr(wait_room_addr);

				sb_count++;
				this.daoEnrol.insert(sb);
				
			}
			// 更新准考证号

			StdEnrol e = new StdEnrol();
			e.setEnrol_id((int) enrol.get("enrol_id"));
			e.setTicket_num(ticket_num);
			this.daoEnrol.update(e);
			System.out.println(std_count++ + "：" + std_name);
			
		}
		String sql = "update school_reg set ticket_time=null where school_id=?";
		this.daoEnrol.updateBySql(sql, school_id);
		daoLog.log(school_id, SkillLogType.UploadArrange.toString(), std_count + "");
		System.out.println("ces1:"+std_count++);
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		System.out.println("ces2:"+std_count++);
		
		// 判断是否所有的考生都有准考证了
		// String sql = "select count(1) from std_enrol e where e.school_id=? and
		// pay_status='Active' and ticket_num is null";
		// if (this.daoEnrol.findObject(Integer.class, sql, school_id) > 0)
		// throw new BusinessException("导入失败：有已经缴费的考生没有准考证信息，请核查");

	}

	public void makeAllTicket(int school_id) {
		SchoolReg school = this.daoSchool.find(school_id);
		FrameAssertUtil.isNotEmpty(school.getTicket_title(), "请设置准考证标题");
		FrameAssertUtil.isNotEmpty(school.getTicket_note(), "请设置准考证考试须知");
		String sql = "select * from std_enrol e where e.school_id=? and ticket_num is not null";

		for (StdEnrol e : this.daoSchool.listBySql(StdEnrol.class, sql, school_id)) {
			try {
				StdReg std = this.daoSchool.find(StdReg.class, e.getStd_id());
				Map<String, Object> enrol = this.daoEnrol.findEnrol(e.getStd_id(), e.getAspect_id());
				File file = SkillTicketHelper.makeTicketFile(std, daoEnrol, school, enrol);
				StdEnrol sb = new StdEnrol();
				sb.setEnrol_id(e.getEnrol_id());
				sb.setTicket_file(file.getName());
				this.daoSchool.update(sb);
				LogHelper.info(e.getStd_id());
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

		sql = "update school_reg set ticket_time=? where school_id=?";
		this.daoEnrol.updateBySql(sql, LocalDateTime.now(), school_id);
		daoLog.log(school_id, SkillLogType.GenerateTicket.toString());
	}

	public StdEnrol makeStdTicket(StdEnrol e) {
		if (StringHelper.isEmpty(e.getTicket_num()))
			return null;
		try {

			StdReg std = this.daoSchool.find(StdReg.class, e.getStd_id());
			SchoolReg school = this.daoSchool.find(SchoolReg.class, e.getSchool_id());
			Map<String, Object> enrol = this.daoEnrol.findEnrol(e.getStd_id(), e.getAspect_id());
			File file = SkillTicketHelper.makeTicketFile(std, daoEnrol, school, enrol);
			StdEnrol sb = new StdEnrol();
			sb.setEnrol_id(e.getEnrol_id());
			sb.setTicket_file(file.getName());
			this.daoSchool.update(sb);
			LogHelper.info(e.getStd_id());
			return e;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	//下载学习所有的准考证-职业技术学院级学校
	public void mergePdf(int school_id) throws Exception {
		String sql = "select * from std_enrol e where e.school_id=? and ticket_num is not null order by ticket_num";
		File dest = SkillMateialHelper.makeStdImageFile(StdMateialType.StdTicket, "T" + school_id + ".pdf");

		PdfDocument pdf = new PdfDocument(new PdfWriter(dest.getPath()));
		PdfMerger merger = new PdfMerger(pdf);
		for (StdEnrol e : this.daoEnrol.listBySql(StdEnrol.class, sql, school_id)) {
			// Add pages from the first document
			try {
				PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(
						SkillMateialHelper.getStdImagePath(e.getTicket_file(), StdMateialType.StdTicket)));
				merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());
				firstSourcePdf.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
		pdf.close();
	}
	
}
