package cn.hmsoft.skill.school.control;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 com.itextpdf.kernel.geom.PageSize;
import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.frame.data.dao.FrameParamDao;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameDictUtil;
import cn.hmsoft.helper.FileHelper;
import cn.hmsoft.helper.ZipHelper;
import cn.hmsoft.helper.excel.Excel2007Writer;
import cn.hmsoft.helper.excel.ExcelReaderHelper;
import cn.hmsoft.helper.http.HttpHelper;
import cn.hmsoft.helper.pdf.ItextPdfHelper;
import cn.hmsoft.jdbc.entity.DataRecord;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.skill.constants.SkillLogType;
import cn.hmsoft.skill.constants.StdMateialType;
import cn.hmsoft.skill.data.dao.school.SchoolAspectDao;
import cn.hmsoft.skill.data.dao.school.SchoolLogDao;
import cn.hmsoft.skill.data.dao.std.StdEnrolDao;
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.StdReg;
import cn.hmsoft.skill.helper.SkillMateialHelper;
import cn.hmsoft.skill.helper.SkillParamHelper;
import cn.hmsoft.skill.school.service.SchoolArrangeService;
import cn.hmsoft.skill.service.cf.SchoolAspectService;

@RestController
public class SchoolStdControl extends SchoolAbstractControl {

	@Autowired
	private SchoolAspectDao daoAspect;
	@Autowired
	private SchoolLogDao daoLog;
	@Autowired
	private SchoolAspectService sService;
	@Autowired
	private StdRegDao daoStd;
	@Autowired
	private StdEnrolDao daoEnrol;
	@Autowired
	private SchoolArrangeService sArrange;
	@Autowired
	private FrameParamDao daoFrameParam;
	

	@RequestMapping("/school/school/std/page")
	public Ajax list(String query, Integer start, Integer limit, String order, String type) {
		SchoolReg school = this.getSchool();
		return new Ajax(this.daoAspect.pageAspectStd(school.getSchool_id(), query, start, limit,
				this.getQueryOrder(order, type)));

	}

	@RequestMapping("/school/school/std/pay")
	public Ajax pay(int enrol_id) {
		SchoolReg school = this.getSchool();
		this.sService.cashPay(enrol_id, school, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("/school/school/std/unpay")
	public Ajax unpay(int enrol_id) {
		SchoolReg school = this.getSchool();
		this.sService.unCashPay(enrol_id, school, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("/school/school/std/image/fetch")
	public Ajax fetch() {
		String sql = "select cert_id,std_name,std_id,std_image,std_param4 from std_reg where std_image is null and std_param4 is not null";
		String tSql = "select * from std_enrol e where std_id=? and ticket_num is not null";
		for (StdReg std : this.daoAspect.listBySql(StdReg.class, sql)) {
			File stdUpload = SkillMateialHelper.makeStdImageFile(std.getCert_id(), StdMateialType.StdUpload, "jpeg");
			if (HttpHelper.download(std.getStd_param4(), stdUpload)) {
				std.setStd_image(stdUpload.getName());
				this.daoAspect.update(std);
				LogHelper.info(std.getCert_id() + ": success！");
				// 判断是否需要重新生成准考证
				for (StdEnrol enrol : this.daoAspect.listBySql(StdEnrol.class, tSql, std.getStd_id())) {
					try {
						this.sArrange.makeStdTicket(enrol);
					} catch (Exception e) {

					}
				}

			} else {
				LogHelper.error(std.getCert_id() + ": error！");
			}

		}
		return new Ajax();

	}

	@RequestMapping("/school/school/std/ticket/make")
	public Ajax ticket(int std_id) {
		String tSql = "select * from std_enrol e where std_id=? and ticket_num is not null" ;
		for (StdEnrol enrol : this.daoAspect.listBySql(StdEnrol.class, tSql, std_id)) {
			try {
				this.sArrange.makeStdTicket(enrol);
			} catch (Exception e) {

			}
		}
		return new Ajax();

	}

	@RequestMapping("/school/school/std/find")
	public Ajax findStd(int std_id) {
		SchoolReg school = this.getSchool();
		StdReg std = this.daoStd.find(std_id);
		Map<String, Object> map = new HashMap<String, Object>();
		if (std == null)
			return new Ajax(map);
		List<Map<String, Object>> enrolArray = this.daoEnrol.listEnrol(std_id, school.getSchool_id());
		if (enrolArray.size() == 0
				&& (std.getFrom_school() == null || std.getFrom_school() - school.getSchool_id() != 0))
			return new Ajax(map);
		map.put("EnrolArray", enrolArray);
		map.put("StdReg", std);
		return new Ajax(map);
	}

	@RequestMapping("/school/school/std/aspect/init")
	public Ajax initAspect(int std_id, int aspect_id) {
		SchoolReg school = this.getSchool();
		StdReg std = this.daoStd.find(std_id);
		Map<String, Object> map = new HashMap<String, Object>();
		if (std == null)
			return new Ajax(map);
		List<Map<String, Object>> enrolArray = this.daoEnrol.listEnrol(std_id, school.getSchool_id());
		if (enrolArray.size() == 0
				&& (std.getFrom_school() == null || std.getFrom_school() - school.getSchool_id() != 0))
			return new Ajax(map);
		Map<String, Object> enrol = this.daoEnrol.findEnrol(std_id, aspect_id);
		if (enrol == null || !enrol.get("school_id").toString().equals("" + school.getSchool_id()))
			throw new BusinessException("基础数据错误！");
		map.put("StdEnrol", enrol);
		map.put("StdReg", std);
		map.put("AspectArray", this.daoAspect.list("school_id", school.getSchool_id()));
		return new Ajax(map);
	}

	@RequestMapping("/school/school/std/aspect/save")
	public Ajax saveAspect(int std_id, int enrol_id, int aspect_id) {
		SchoolReg school = this.getSchool();
		this.sService.changeStdAspect(school.getSchool_id(), enrol_id, aspect_id, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("/school/school/std/login/page")
	public Ajax pageStdLogin(int std_id, Integer start, Integer limit, String order, String type) {
		SchoolReg school = this.getSchool();
		return new Ajax(this.daoStd.pageLogin(school.getSchool_id(), std_id, start, limit));
	}

	@RequestMapping("/school/school/std/log/page")
	public Ajax pageStdLog(String query, int std_id, Integer start, Integer limit, String order, String type) {
		SchoolReg school = this.getSchool();
		return new Ajax(this.daoStd.pageLog(school.getSchool_id(), std_id, query, start, limit,
				this.getQueryOrder(order, type)));

	}

	@RequestMapping("/school/school/std/download")
	public void download() {
		SchoolReg school = this.getSchool();
		List<Map<String, Object>> list = this.daoAspect.listAspectStd(school.getSchool_id());
		Map<String, Integer> vMap = Excel2007Writer.createTitleMap("#", 2);
		vMap.put("报考专业", 15);
		vMap.put("毕业学校", 30);
		vMap.put("准考证号", 10);
		vMap.put("考生姓名", 10);
		vMap.put("身份证号", 18);
		vMap.put("考生号", 14);
		vMap.put("性别", 6);
		vMap.put("联系电话1", 12);
		vMap.put("联系电话2", 12);
		vMap.put("通讯地址", 40);
		vMap.put("报考时间", 20);
		vMap.put("缴费渠道", 10);
		vMap.put("缴费时间", 20);
		vMap.put("内部订单号", 32);
		vMap.put("外部订单号", 35);

		List<List<Object>> values = new ArrayList<List<Object>>();

		int index = 1;
		for (Map<String, Object> map : list) {
			List<Object> array = new ArrayList<Object>();
			array.add(++index);
			array.add(map.get("aspect_name"));
			array.add(map.get("std_school"));
			array.add(map.get("std_name"));
			array.add(map.get("ticket_num"));
			array.add(map.get("cert_id"));
			array.add(map.get("exam_id"));
			array.add(map.get("std_sex"));
			array.add(map.get("std_mobile1"));
			array.add(map.get("std_mobile2"));
			array.add(map.get("link_addr"));
			array.add(map.get("enrol_time") == null ? null : map.get("enrol_time"));
			array.add(map.get("channel_id") == null
					? (map.get("pay_status") == null ? "" : (map.get("bill_id") == null ? "现金缴费" : ""))
					: (FrameDictUtil.getFrameDictText("StdPayChannel", map.get("channel_id").toString())));
			array.add(map.get("pay_time") == null ? null : map.get("pay_time"));
			array.add(map.get("bill_no"));
			array.add(map.get("channel_no"));
			values.add(array);

		}

		this.daoLog.log(school.getSchool_id(), SkillLogType.DownladStd.toString(), values.size() + "");
		Excel2007Writer.downloadAsExcel(this.getResponse(), this.getSchool().getSchool_name() + "-考生数据明细", values,
				vMap);
	}

	/**
	 * 导出考生照片（身份证或者准考证）
	 * @throws Exception
	 */
	@RequestMapping("/school/school/std/photo")
	public void downloadPhoto() throws Exception {
		SchoolReg school = this.getSchool();
		Map<String, String> mapPhoto = new HashMap<String,String>();
		mapPhoto = this.daoFrameParam.mapParams(StdMateialType.IsCertIdExportPhoto);
		String sql = "select * from std_reg where std_id in (select std_id from std_enrol where school_id=?)";
		List<File> array = new ArrayList<File>();
		for (StdReg std : this.daoAspect.listBySql(StdReg.class, sql, school.getSchool_id())) {
			File f = SkillMateialHelper.makeStdImageFile(std.getStd_image(), StdMateialType.StdUpload);
			if (f.exists()) {
				System.out.println("参数："+mapPhoto.get(StdMateialType.IsCertIdExportPhoto));
				if(mapPhoto.get(StdMateialType.IsCertIdExportPhoto).equals("true")) {
					System.out.println("考生身份证下载");
					File file = SkillMateialHelper.makeStdImageFile(std.getCert_id() + ".jpeg", StdMateialType.StdTemp);
					FileHelper.copyFile(f, file);
					array.add(file);
				}else {
					System.out.println("考生准考证下载");
					File file = SkillMateialHelper.makeStdImageFile(std.getExam_id() + ".jpeg", StdMateialType.StdTemp);
					FileHelper.copyFile(f, file);
					array.add(file);
				}
				
			}
		}

		File zipFile = SkillMateialHelper.createTempFile();
		ZipHelper.compress(array, zipFile);
		for (File f : array)
			f.delete();
		this.downloadFile(zipFile,
				SkillParamHelper.CurrentYear + school.getSchool_name() + school.getTicket_title() + "-考生图片信息.zip",
				true);
	}
	
	/**
	 * 导出二级学校（高中）登入账号密码
	 */
	@RequestMapping("/school/school/std/school/download")
	public void downloadTwoSchool() {
		System.out.println("学校账号下载");
		SchoolReg school = this.getSchool();
		List<Map<String, Object>> list = this.daoAspect.listTwoSchool(school.getSchool_id());
		Map<String, Integer> vMap = Excel2007Writer.createTitleMap("#", 2);
		vMap.put("学校", 4);
		vMap.put("密码", 5);

		List<List<Object>> values = new ArrayList<List<Object>>();

		int index = 1;
		for (Map<String, Object> map : list) {
			List<Object> array = new ArrayList<Object>();
			array.add(++index);
			array.add(map.get("std_school"));
			array.add(map.get("std_school_pwd"));
			values.add(array);
		}
		this.daoLog.log(school.getSchool_id(), SkillLogType.DownladStd.toString(), values.size() + "");
		Excel2007Writer.downloadAsExcel(this.getResponse(), this.getSchool().getSchool_name() + "-二级学校账户", values,
				vMap);
	}


	@RequestMapping("/school/school/std/upload")
	public Ajax upload(MultipartFile file, boolean auto_reg, boolean auto_enrol, boolean auto_pay, boolean none_trans)
			throws Exception {
		SchoolReg school = this.getSchool();
		List<List<String>> list = null;
		try {
			list = ExcelReaderHelper.readSheet(file.getOriginalFilename(), file.getInputStream(), 1, 10);
		} catch (Exception e) {

		}
		if (list != null && list.size() > 0) {

			this.sService.saveUpload(list, school.getSchool_id(), auto_reg, auto_enrol, auto_pay, none_trans);
			List<List<Object>> values = new ArrayList<List<Object>>();
			for (List<String> array : list) {
				List<Object> oArray = new ArrayList<Object>();
				for (String s : array) {
					oArray.add(s);
				}
				values.add(oArray);
			}
			Map<String, Integer> map = Excel2007Writer.createTitleMap("#", 10);
			map.put("身份证号", 18);
			map.put("考生号", 15);
			map.put("考生姓名", 10);
			map.put("报考专业", 15);
			map.put("联系电话1", 15);
			map.put("联系电话2", 15);
			map.put("邮寄地址", 30);
			map.put("处理结果", 30);
			File f = new File(SpringHelper.WebServletContext.getRealPath("/") + "template" + File.separator + "temp"
					+ File.separator + getSimpleName(file) + "-导入结果.xlsx");
			f.getParentFile().mkdirs();
			Excel2007Writer.saveAsExcel(f, values, map);
			DataRecord dr = new DataRecord();
			dr.setS01(f.getName());
			dr.setBn01(true);
			return new Ajax(dr);

		} else
			throw new BusinessException("在上传的文件中未找到有效的考生数据！");

	}

	private String getSimpleName(MultipartFile file) {
	    if (file.getOriginalFilename().indexOf(".") == -1) {
	        return file.getOriginalFilename();
	      }
	      return file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
	}
	
	private final static String TOTLA_SQL = "select count(1) pay_count,sum(bill_amount) fee_amount,DATE_FORMAT(reply_time,'%Y-%m-%d') pay_date from pay_bill b,std_enrol e where b.bill_id=e.bill_id and bill_status='Complete' and school_id=? group by DATE_FORMAT(reply_time,'%Y-%m-%d') order by DATE_FORMAT(reply_time,'%Y-%m-%d') desc";

	@RequestMapping("/school/school/std/pay/total")
	public Ajax total() {
		SchoolReg school = this.getSchool();
		return new Ajax(this.daoAspect.listMapBySql(TOTLA_SQL, school.getSchool_id()));
	}

	// @RequestMapping("/school/school/std/pay/downlaod")
	// public void downladPay() {
	// SchoolReg school = this.getSchool();
	// List<Map<String, Object>> list = this.daoAspect.listMapBySql(TOTLA_SQL,
	// school.getSchool_id());
	//
	// Map<String, Integer> map = Excel2007Writer.createTitleMap("#", 2);
	// map.put("缴费日期", 10);
	// map.put("缴费金额", 15);
	//
	// }
	
	
}
