package cn.hmsoft.pay.control;

import java.io.StringReader;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

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.application.web.AjaxControl;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.helper.http.HttpHelper;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.pay.constants.PayBillStatus;
import cn.hmsoft.pay.data.dao.PayBillDao;
import cn.hmsoft.pay.data.model.PayBill;
import cn.hmsoft.pay.impl.PayChannelAbstract;
import cn.hmsoft.pay.impl.alipay.AliPayOrderNoticeResponse;
import cn.hmsoft.pay.impl.alipay.AliPayOrderReturnResponse;
import cn.hmsoft.pay.impl.anxinpay.AnxinPayOrderNoticeResponse;
import cn.hmsoft.pay.impl.fudan.ReturnResponse;
import cn.hmsoft.pay.impl.weixin.entity.PayNoticeResponse;
import cn.hmsoft.pay.impl.weixin.entity.PayNoticeResult;
import cn.hmsoft.pay.util.PayUtil;

@RestController
public class PayReplyControl extends AjaxControl {

	@Autowired
	private PayBillDao daoBill;

	@RequestMapping("/pay/reply/weixin")
	public Ajax weixinReply(HttpServletRequest request) {
		String value = HttpHelper.getRequestString(request);
		if (StringHelper.isEmpty(value))
			return new Ajax();
		PayNoticeResponse entity = null;
		try {
			JAXBContext jc = JAXBContext.newInstance(PayNoticeResponse.class);
			Unmarshaller u = jc.createUnmarshaller();
			entity = (PayNoticeResponse) u.unmarshal(new StringReader(value));
		} catch (Exception e) {
			LogHelper.error(e);
		}
		if (entity == null)
			return new Ajax();
		if ("SUCCESS".equals(entity.getReturn_code()) && "SUCCESS".equals(entity.getResult_code())) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("XmlString", value);
			map.put("ResponseEntity", entity);
			PayUtil.reply(entity.getAttach(), request, map);
			HttpHelper.writeXmlString(this.getResponse(), new PayNoticeResult());
		}
		return new Ajax();

	}

	@RequestMapping("/pay/reply/upay")
	public void uPayRelpy(HttpServletRequest request) {
		Map<String, Object> map = PayChannelAbstract.getRequestMapWithObject(request);
		if (!"0000".equals(map.get("OrderStatus"))) {
			return;
		}
		PayUtil.reply(request.getParameter("MerResv"), request, map);
		this.writeText("SUCCESS");
	}

	@RequestMapping("/pay/reply/uacp")
	public void uAcpRelpy(HttpServletRequest request) {
		Map<String, Object> map = PayChannelAbstract.getRequestMapWithObject(request);
		if (!"00".equals(map.get("respCode"))) {
			this.writeText("request error");
			return;
		}
		PayUtil.reply(request.getParameter("reqReserved"), request, map);
		this.writeText("SUCCESS");
	}

	@RequestMapping("/pay/reply/anxinpay")
	public void anxinPayRelpy(HttpServletRequest request) {
		Map<String, Object> map = PayChannelAbstract.getRequestMapWithObject(request);
		//
		// signature：93ddb739898ff29e89daf1400a946301
		// json：{"type":"back","status":"00","union_order_no":"2019030413351000134","orderno":"AXP_HmPay_20190304133340_00000001","amt":"0.01","settledate":"20190304","paytime":"20190304133521","pay_channel_name":"\u5FAE\u4FE1\u652F\u4ED8","paychannel":"WxPay"}
		String json = map.get("json").toString();
		String signature = map.get("signature").toString();
		AnxinPayOrderNoticeResponse notice = JsonHelper.toObject(json, AnxinPayOrderNoticeResponse.class);

		if (notice == null || !"00".equals(notice.getStatus())) {
			this.writeText("request error");
			return;
		}
		// 查找订单
		PayBill b = this.daoBill.find("bill_no", notice.getOrderno());

		if (b == null) {
			LogHelper.error("error anxinpay reply .. bill not exists");
			this.writeText("request error");
			return;
		}
		// 验证签名
		PayChannelAbstract util = PayUtil.getPayChannelImpl(b.getMerchant_id(), b.getChannel_id());
		if (!SecureHelper.md5(json + util.getPayMerchantChannel().getBank_merchant_pass()).toLowerCase()
				.equals(signature)) {
			LogHelper.error("error anxinpay reply .. signature error");
			this.writeText("signature error");
			return;
		}
		this.writeText("{'respcode':'00','respdesc'}");
		PayUtil.reply(b.getBill_id() + "", request, map);
	}

	@RequestMapping("/pay/reply/alipay/return")
	public void returnAliPay(HttpServletRequest request, AliPayOrderReturnResponse alipay) {
		// 直接放弃 用回调
		// FrameAssertUtil.checkParam(alipay.getOut_trade_no());
		// PayBill bill = this.daoBill.find("bill_no", alipay.getOut_trade_no());
		// FrameAssertUtil.isNotNull(bill, "未找到指定的订单！");
		// Map<String, Object> paramMap = new HashMap<String, Object>();
		// paramMap.put("AliPayOrderReturnResponse", alipay);
		// PayUtil.reply(bill.getBill_id() + "", request, paramMap);
		this.writeAlert("支付宝流程完成，请返回页面查看支付结果");
	}

	/****************************
	 * 支付宝通知
	 */
	@RequestMapping("/pay/reply/alipay/notice")
	public void noticeAliPay(HttpServletRequest request, AliPayOrderNoticeResponse alipay) {

		if (!"TRADE_SUCCESS".equals(alipay.getTrade_status())) {
			this.writeText("success");
			return;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("AliPayOrderNoticeResponse", alipay);
		PayUtil.reply(alipay.getPassback_params(), request, map);
		try {
			this.getResponse().getOutputStream().println("success");
		} catch (Exception e) {

		}
	}

	/*****************************
	 * 查询订单是否成交
	 */
	@RequestMapping("/pay/reply/bill/status")
	public Ajax queryBillStatus(int bill_id) {
		PayBill bill = this.daoBill.findByBillId(bill_id);
		if (bill != null && PayBillStatus.Complete.equals(bill.getBill_status()))
			return new Ajax(true);

		return new Ajax(false);
	}

	/*****************************
	 * 查询订单是否成交
	 */
	@RequestMapping("/pay/reply/bill/info")
	public Ajax queryBill(int bill_id) {
		PayBill bill = this.daoBill.findByBillId(bill_id);
		return new Ajax(bill);
	}
	
	/**
	 * 页面调用
	 * @param request
	 * @param sign
	 * @param data
	 * @return
	 */
	@RequestMapping("/pay/reply/fudan")
	public Ajax fudanreplypage(HttpServletRequest request, String sign, String data) {
		fudanreply(request, sign,data);
		HttpHelper.writeString(getResponse(), "<script>alert(\'交费成功！\');window.location = '../../wechat/wechat.jsp?school_code=10593'</script>");
		return new Ajax();
	}
	
	/**
	 * 后台调用
	 * @param request
	 * @param sign
	 * @param data
	 * @return
	 */
	@RequestMapping("/pay/reply/fudan/back")
	public Ajax fudanreplyback(HttpServletRequest request, String sign, String data) {
		fudanreply(request, sign,data);
		HttpHelper.writeString(getResponse(), "1");
		return new Ajax();
	}

	private void fudanreply(HttpServletRequest request, String sign, String data) {
		ReturnResponse entity = null;
		try {
			JAXBContext jc = JAXBContext.newInstance(ReturnResponse.class);
			Unmarshaller u = jc.createUnmarshaller();
			entity = (ReturnResponse) u.unmarshal(new StringReader(data));
		} catch (Exception e) {
			LogHelper.error(e);
		}
		if (entity == null)
			return;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Paidtime", entity.getPaidtime());
		map.put("Trade_no", entity.getTrade_no());
		map.put("XmlString", data);
		map.put("sign", sign);
		PayBill b = this.daoBill.find("bill_no", entity.getBillno());
		PayUtil.reply(b.getBill_id() + "", request, map);
	}
	
	@RequestMapping("/pay/reply/jiapeng")
	public Ajax jiapeng(HttpServletRequest request) {
		String Sign = request.getParameter("Sign");
		String OrderNo = request.getParameter("OrderNo");
		String OrderNoCharge = request.getParameter("OrderNoCharge");//佳鹏内部订单编号
		String PayTime = request.getParameter("PayTime");
		String PayMent = request.getParameter("PayMent");
		LogHelper.info("Sign,OrderNo,PayTime,PayMent------->" + Sign + "," + OrderNo + "," + PayTime + "," + PayMent);
		if (StringHelper.isEmpty(OrderNo))
			return new Ajax();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Paidtime", LocalDateHelper.parseDateTime(PayTime));
		map.put("Trade_no", OrderNoCharge);//佳鹏
		PayBill b = this.daoBill.find("bill_no", OrderNo);
		//成功才去回调
		if (PayMent.equals("1")) {
			PayUtil.reply(b.getBill_id() + "", request, map);
		} else {
			LogHelper.error("PayMent返回失败" + PayMent);
		}
		/*if (StringHelper.isNotEmpty(CallBackUrl) && PayMent.equals("1")) {
			LogHelper.info("go to weixin..." + CallBackUrl);
			HttpHelper.writeString(getResponse(), "<script>alert(\'交费成功！\');window.location = '" +  CallBackUrl + "'</script>");
		}*/
		return new Ajax();
	}
	
	//启航支付-桂电
	@RequestMapping("/pay/reply/qihang")
	public void qihang(HttpServletRequest request) {
		System.out.println("qihang gd callback-----------");
		String orderNo = request.getParameter("ApplicationId");
		String sign = request.getParameter("Sign");
		//String PayTime = request.getParameter("PayTime");
		System.out.println("ApplicationId-----------" + orderNo);
		System.out.println("Sign-----------" + sign);
		if (StringHelper.isEmpty(orderNo))
			return;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Paidtime", LocalDateHelper.format(LocalDateTime.now()));
		map.put("Trade_no", orderNo);//启航的订单编号用我们传的orderNo
		PayBill b = this.daoBill.find("bill_no", orderNo);
		//成功才去回调
		PayUtil.reply(b.getBill_id() + "", request, map);
		if (StringHelper.isEmpty(sign)) {
			sign = "12341234321";//为空暂时写死
			System.out.println("Sign is empty..........");
		}
		String ret = "<Result><Success>true</Success><Message></Message><Sign>#Sign</Sign><!--签名--></Result>";
		ret = ret.replace("#Sign", sign);
		System.out.println("ret：" + ret);
		this.writeText(ret);
	}
	
	//启航支付-医科大
	@RequestMapping("/pay/reply/qihangykd")
	public void qihangYkd(HttpServletRequest request) {
		System.out.println("qihang ykd callback-----------");
		String orderNo = request.getParameter("ApplicationId");
		String sign = request.getParameter("Sign");
		//String PayTime = request.getParameter("PayTime");
		System.out.println("ApplicationId-----------" + orderNo);
		System.out.println("Sign-----------" + sign);
		if (StringHelper.isEmpty(orderNo))
			return;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Paidtime", LocalDateHelper.format(LocalDateTime.now()));
		map.put("Trade_no", orderNo);//启航的订单编号用我们传的orderNo
		PayBill b = this.daoBill.find("bill_no", orderNo);
		//成功才去回调
		PayUtil.reply(b.getBill_id() + "", request, map);
		if (StringHelper.isEmpty(sign)) {
			sign = "12341234321";//为空暂时写死
			System.out.println("Sign is empty..........");
		}
		String ret = "<Result><Success>true</Success><Message></Message><Sign>#Sign</Sign><!--签名--></Result>";
		ret = ret.replace("#Sign", sign);
		System.out.println("ret：" + ret);
		this.writeText(ret);
	}
}
