package cn.hmsoft.skill.enrol.control;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
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 cn.hmsoft.application.web.Ajax;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.helper.http.HttpHelper;
import cn.hmsoft.helper.http.HttpRequestEntity;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.pay.constants.PayChannel;
import cn.hmsoft.pay.data.model.PayBill;
import cn.hmsoft.pay.data.model.PayChannelInfo;
import cn.hmsoft.pay.impl.PayAnxinPayChannelImpl;
import cn.hmsoft.pay.impl.PayWeiXinChannelImpl;
import cn.hmsoft.pay.impl.anxinpay.AnxinPayBillRequest;
import cn.hmsoft.pay.impl.anxinpay.AnxinPayUtil;
import cn.hmsoft.pay.impl.weixin.WeiXinPayUtil;
import cn.hmsoft.pay.util.PayParamUtil;
import cn.hmsoft.pay.util.PayUtil;
import cn.hmsoft.skill.constants.StdLogType;
import cn.hmsoft.skill.constants.StdMateialType;
import cn.hmsoft.skill.constants.StdMaterialType;
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.StdLogDao;
import cn.hmsoft.skill.data.dao.std.StdMaterialDao;
import cn.hmsoft.skill.data.model.school.SchoolReg;
import cn.hmsoft.skill.data.model.std.StdEnrol;
import cn.hmsoft.skill.data.model.std.StdMaterial;
import cn.hmsoft.skill.data.model.std.StdReg;
import cn.hmsoft.skill.enrol.service.EnrolStdEnrolService;
import cn.hmsoft.skill.helper.SkillParamHelper;

@RestController
public class EnrolStdEnrolControl extends EnrolAbstractControl {

	@Autowired
	private EnrolStdEnrolService sEnrol;
	@Autowired
	private StdEnrolDao daoEnrol;
	@Autowired
	private StdLogDao daoLog;
	@Autowired
	private StdEnrolSubjectDao daoEnrolSubject;
	@Autowired
	private StdMaterialDao stdMaterialDao;
	@Autowired
	private SchoolRegDao schoolRegDao;

	@RequestMapping("/enrol/std/enrol/list")
	public Ajax listEnrol() {
		StdReg std = this.getStdReg();
		SchoolReg school = this.getSchoolReg();
		List<Map<String, Object>> array = this.daoEnrol.listEnrol(std.getStd_id(), school.getSchool_id());
		for (Map<String, Object> map : array) {
			if (school.getTicket_start_time() == null || school.getTicket_start_time().isAfter(LocalDateTime.now())) {
				map.put("AllowTicket", false);
				map.put("ticket_file", null);
				map.put("ticket_num", null);
			} else {
				map.put("AllowTicket", true);
				if (map.containsKey("ticket_file") && map.get("ticket_file") != null
						&& map.get("ticket_file").toString().length() > 0) {
					map.put("ticket_file", SkillParamHelper.MateialWebPath + StdMateialType.StdTicket + "/"
							+ map.get("ticket_file").toString());
				}
			}

		}
		return new Ajax(array);
	}

	@RequestMapping("/enrol/std/enrol/save")
	public Ajax saveEnrol(int std_id, int school_id, int aspect_id) {
		StdReg std = this.getStdReg();
		FrameAssertUtil.isNotNull(std.getConfirm_time(), "报考前请务必确认个人信息无误！");
		StdEnrol enrol = new StdEnrol();
		enrol.setStd_id(std.getStd_id());
		enrol.setSchool_id(school_id);
		enrol.setAspect_id(aspect_id);
		// 判断报考是否本校专业
		/*SchoolAspect aspect = daoAspect.find(aspect_id);
		FrameAssertUtil.isNotNull(aspect, "专业不存在！");
		if (aspect.getSchool_id().intValue() != school_id) {
			throw new BusinessException("报考的为非本校专业，无法报考！");
		}*/
		this.sEnrol.save(std, enrol, false);
		return new Ajax(this.sEnrol.findByEnrolId(enrol.getEnrol_id()));
	}

	@RequestMapping("/enrol/std/enrol/cancel")
	public Ajax cancelEnrol(int enrol_id) {
		this.sEnrol.cancel(this.getStdReg().getStd_id(), enrol_id);
		return new Ajax();
	}

	@RequestMapping("/enrol/std/enrol/find")
	public Ajax findEnrol(int enrol_id) {
		return new Ajax(this.daoEnrol.findEnrol(enrol_id));
	}

	@RequestMapping("/enrol/std/enrol/score")
	public Ajax score(int enrol_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> enrolMap = this.daoEnrol.findEnrol(enrol_id);
		map.put("StdEnrol", enrolMap);
		map.put("SubjectArray",
				this.daoEnrolSubject.listSubject((int) enrolMap.get("std_id"), (int) enrolMap.get("aspect_id")));

		return new Ajax(map);
	}

	@RequestMapping("/enrol/std/enrol/pay")
	public void jumpEnrol(String channel_id, int enrol_id) {
		StdEnrol enrol = this.sEnrol.checkPayStatus(this.getStdReg(), enrol_id);
		String value = PayUtil.order(enrol.getSchool_id() + "", channel_id, enrol.getStd_id() + "",
				enrol.getFee_amount(), PayParamUtil.DefaultBusinessType, enrol.getEnrol_id() + "", null,
				enrol.getSchool_id() + "");
		this.writeText(value);
	}

	@RequestMapping("/enrol/std/enrol/ticket")
	public Ajax ticket(int enrol_id) {
		StdEnrol e = this.daoEnrol.find(enrol_id);
		if (StringHelper.isEmpty(e.getTicket_file())) {
			throw new BusinessException("准考证未生成，无法下载");

		}

		SchoolReg sr = this.schoolRegDao.find(e.getSchool_id());
		Date dt1 = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyzyy-MM-dd HH:mm:ss");
		Date dt2 = Date.from(sr.getTicket_end_time().atZone(ZoneId.systemDefault()).toInstant());
		if (sdf.format(dt1).compareTo(sdf.format(dt2)) > 0) {
			throw new BusinessException("准考证下载时间已过，不能下载准考证！");
		}

		// 记录
		this.daoLog.log(e.getSchool_id(), e.getStd_id(), StdLogType.DownloadTicket, null, e.getTicket_file());
		return new Ajax(SkillParamHelper.MateialWebPath + StdMateialType.StdTicket + "/" + e.getTicket_file());
	}

	@RequestMapping("/enrol/std/enrol/check")
	public Ajax check(int enrol_id) {
		StdEnrol enrol = this.sEnrol.findById(enrol_id);
		// //如果是交通职院，则需要审核照片信息
		// if(enrol.getSchool_id()==12752) {
		// StdMaterial stdMaterial =
		// this.stdMaterialDao.findMaterial(enrol.getStd_id(),StdMaterialType.NoCrownPhoto);
		// if(stdMaterial == null) {
		// throw new BusinessException("未上传免冠证件照片，请重新上传！");
		// }else {
		// if(StringHelper.isEmpty(stdMaterial.getVerify_status())) {
		// throw new BusinessException("资料未审核请耐心等待！");
		// }else if(stdMaterial.getVerify_status().equals("InActive")) {
		// throw new BusinessException("资料审核未通过，请重新上传清晰的免冠证件照！");
		// }
		// }
		// }
		return new Ajax(enrol);
	}

	@RequestMapping("/enrol/std/material/check")
	public Ajax checkMaterial(int enrol_id) {
		StdEnrol enrol = this.sEnrol.findByEnrolId(enrol_id);
		StdMaterial stdMaterial = this.stdMaterialDao.findMaterial(enrol.getStd_id(), StdMaterialType.NoCrownPhoto);
		return new Ajax(stdMaterial);
	}

	// http://127.0.0.1/sk/enrol/pay/channel/list.htm?std_id=117
	/*******************************
	 * 列出所有可用的渠道
	 */
	@RequestMapping("/enrol/std/enrol/channel/list")
	public Ajax listChannel() {
		List<PayChannelInfo> list = PayUtil.listMerantChannel(this.getSchoolReg().getSchool_id() + "");
		return new Ajax(list);
	}

	/***************************************
	 * 生成微信二维码 sk/enrol/std/enrol/weixin/qrcode/image.htm?enrol_id=12
	 */
	@RequestMapping("/enrol/std/enrol/weixin/qrcode/image")
	public void wxImage(int enrol_id) {
		StdEnrol enrol = this.sEnrol.checkPayStatus(this.getStdReg(), enrol_id);
		try {
			PayWeiXinChannelImpl impl = (PayWeiXinChannelImpl) PayUtil
					.getPayChannelImpl(this.getSchoolReg().getSchool_id() + "", WeiXinPayUtil.ChannelId);

			PayBill bill = WeiXinPayUtil.makePayBill(impl.getMerchant().getMerchant_id(),
					impl.getChannel().getChannel_id(), enrol.getFee_amount(), enrol.getStd_id() + "",
					enrol.getEnrol_id() + "");
			if (bill != null) {
				WeiXinPayUtil.makeQrCode(impl, bill.getBill_param(), this.getResponse().getOutputStream());
			}
			LogHelper.info("new bil：" + bill.getBill_id());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("未能正常生成支付二维码，请联系系统管理员！");
		}
	}

	public static void main(String[] args) {
		AnxinPayBillRequest entity = new AnxinPayBillRequest();
		entity.setBusiness_channel("jngkbmsyt");
		entity.setPay_channel("UnionPay");
		entity.setPay_mode("scan");
		String product_name = "支付费用";
		entity.setOrderno("1531000003");
		entity.setAmt(String.format("%.2f", new Object[] { Double.valueOf(10 / 100.0D) }));
		entity.setFeename("交通职院报名测试1");
		entity.setBack_notify_url("http://8190.hmsoft.cn/sk/pay/reply/anxinpay.htm");
		String json = JsonHelper.fromObject(entity);
		String value = JsonHelper.fromObject(entity) + "6136da74a2181bb7ba679949b62f0134";
		String md5 = SecureHelper.md5(value);
		HttpRequestEntity rq = new HttpRequestEntity();
		rq.setHttp_url("http://axf.hbctc.edu.cn:8081/paycenter/gateway_back");// gateway_web
		Map<String, Object> map = new LinkedHashMap();
		map.put("json", json);
		map.put("signature", md5.toLowerCase());
		rq.setRequestMap(map);
		String line = null;
		try {
			line = (String) HttpHelper.URLPost(rq).get(0);
			System.out.println(line);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (StringHelper.isEmpty(line)) {
			throw new BusinessException("无法访问.");
		}
	}

	/***************************************
	 * 生成安心付 sk/enrol/std/enrol/weixin/qrcode/image.htm?enrol_id=12
	 */
	@RequestMapping("/enrol/std/enrol/anxinpay/qrcode/image")
	public void anxinImage(int enrol_id) {
		StdEnrol enrol = this.sEnrol.checkPayStatus(this.getStdReg(), enrol_id);
		try {
			PayAnxinPayChannelImpl impl = (PayAnxinPayChannelImpl) PayUtil
					.getPayChannelImpl(this.getSchoolReg().getSchool_id() + "", PayChannel.AnxinPay);

			PayBill bill = AnxinPayUtil.makePayBill(impl.getMerchant().getMerchant_id(),
					impl.getChannel().getChannel_id(), enrol.getFee_amount(), enrol.getStd_id() + "",
					enrol.getEnrol_id() + "");
			if (bill != null) {
				AnxinPayUtil.makeQrCode(bill.getBill_param(), this.getResponse().getOutputStream());
			}
			LogHelper.info("new bill：" + bill.getBill_id());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("未能正常生成支付二维码，请联系系统管理员！");
		}
	}

	// /***************************************
	// * 扫描微信二维码
	// */
	// @RequestMapping("/enrol/std/enrol/weixin/qrcode/scan")
	// public void scan() throws Exception {
	// QrCodePushEntity push = HttpHelper.getRequestEntityWithXml(this.getRequest(),
	// QrCodePushEntity.class);
	// PayChannelAbstract impl = PayUtil.getPayChannelImpl(push.getMch_id(),
	// PayChannel.WeiXin);
	// QrCodePushEntity entity =
	// WeiXinPayUtil.checkQrCodeRequest(impl.getPayMerchantChannel(),
	// push, this.getResponse());
	// if (entity == null) {
	// return;
	// }
	// int enrol_id = 0;
	// try {
	// enrol_id = Integer.parseInt(entity.getBusiness_id());
	// } catch (Exception e) {
	// WeiXinPayUtil.writeScanError(impl.getPayMerchantChannel(), "提交参数错误，非有效的报考编号",
	// this.getResponse());
	// return;
	// }
	// StdEnrol enrol = this.sEnrol.checkPayStatus(enrol_id);
	// if(enrol!=null)
	// throw new BusinessException("hello");
	// PayBill bill = WeiXinPayUtil.makePayBill(impl.getMerchant().getMerchant_id(),
	// impl.getChannel().getChannel_id(), enrol.getFee_amount(), enrol.getStd_id() +
	// "",
	// enrol.getEnrol_id() + "");
	// if (bill == null) {
	// return;
	// }
	// WeiXinPayUtil.writeScanResult(impl.getPayMerchantChannel(),
	// bill.getChannel_no(),
	// this.getResponse());
	// }

	// 襄阳缴费初始化
	@RequestMapping("/enrol/std/enrol/xiangyang/initpay")
	public Ajax initPay(int enrol_id, String exam_type) {
		try {
			this.sEnrol.initPay(enrol_id, exam_type);
		} catch (BusinessException e) {
			return new Ajax(e.getMessage());
		}
		return new Ajax("");
	}

	// 襄阳缴费查询
	@RequestMapping("/enrol/std/enrol/xiangyang/check")
	public Ajax xyCheck(int enrol_id, String exam_type) {
		return new Ajax(this.sEnrol.xyCheck(enrol_id));
	}
}
