package cn.hmsoft.pay.impl;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.helper.LocalDateHelper;
import cn.hmsoft.helper.SecureHelper;
import cn.hmsoft.helper.StringHelper;
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;

/******************************
 * 
 * @启航支付--医科大
 */
public class PayQiHangYkdChannelImpl extends PayChannelAbstract {
	
	@Override
	protected boolean init() throws Exception {
		if (StringHelper.isEmpty(this.channel.getPay_url())) {
			return error("支付网关未配置");
		}
		return true;
	}

	@Override
	public String makeBillNo(PayBill bill) {
		String v = StringHelper.leftPadding(bill.getBusiness_id(), 8, '0');
		return "YKD" + bill.getBusiness_type() + LocalDateHelper.formatLongNoSplit(LocalDateTime.now()) + v;
	}

	@Override
	public PayBill processReply(PayBillDao daoBill, PayBill bill, HttpServletRequest request,
			Map<String, Object> paramMap) {
		LogHelper.info("qihang ykd reply-------------->");		
		String paidtime = (String) paramMap.get("Paidtime");
		String trade_no = (String) paramMap.get("Trade_no");
		LocalDateTime reply_time = LocalDateTime.now();
		LocalDateTime pay_time = null;
		try {
			pay_time = LocalDateHelper.parseDateTime(paidtime,
					LocalDateHelper.LongDateFormatter);
		} catch (Exception e) {

		}
		bill.setPay_time(pay_time);
		bill.setReply_time(reply_time);
		bill.setBill_status(PayBillStatus.Complete);
		// 首次成交 更新订单
		try {
			daoBill.completeBill(bill.getBill_id(), pay_time, reply_time, trade_no);
			return bill;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private String getBaseXml() {
		StringBuilder param = new StringBuilder();
		param.append("<Result>");
		param.append("<BatchId>#BatchId</BatchId>");
		param.append("<ApplicationId>#ApplicationId</ApplicationId>");
		param.append("<StudentNo>#StudentNo</StudentNo>");
		param.append("<StudentName>#StudentName</StudentName>");
		param.append("<PayAmount>#PayAmount</PayAmount>");
		param.append("<ReturnUrl>#ReturnUrl</ReturnUrl>");
		param.append("<UrlReferrer>#UrlReferrer</UrlReferrer>");
		param.append("<PayAmountReadOnly>true</PayAmountReadOnly>");
		param.append("<Items>");
		param.append("<Item>");
		param.append("<Id>#Id</Id>");
		param.append("<Number>#Number</Number>");
		param.append("<Title>#Title</Title>");
		param.append("<Amount>#Amount</Amount>");
		param.append("</Item>");
		param.append("</Items>");
		param.append("<Sign>#Sign</Sign>");
		param.append("</Result>");
		return param.toString();
	}
	
	@Override
	public Map<String, String> makeRequestAttr(PayBill bill) {
		LinkedHashMap<String, String> paramMap = StringHelper.toMap(bill.getBill_param());
		String enrol_id = paramMap.get("enrol_id");
		String ticket_no = paramMap.get("ticket_no");
		String cert_id = paramMap.get("cert_id");
		String std_name = paramMap.get("std_name");
		String batch_id = paramMap.get("batch_id");
		String order_no = bill.getBill_no();//订单号要传过去
		String xmlStr = this.getBaseXml();
		xmlStr = xmlStr.replace("#BatchId", batch_id)
				.replace("#ApplicationId", order_no)
				.replace("#StudentNo", cert_id)
				.replace("#StudentName", std_name)
				.replace("#PayAmount",  "" + bill.getBill_amount() / 100.0)//
				.replace("#ReturnUrl", payMerchantChannel.getNotice_url())
				.replace("#UrlReferrer", payMerchantChannel.getPage_url() + "?school_code=" + paramMap.get("school_code"))
				.replace("#Id", enrol_id)
				.replace("#Number", enrol_id)
				.replace("#Title", "学费")
				.replace("#Amount",  "" + bill.getBill_amount() / 100.0);//
		LogHelper.info("qihang支付请求xml：" + xmlStr);
		String data = null;
		try {
			data = Base64.getEncoder().encodeToString(xmlStr.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<>();
		map.put("Xml", data);
		return map;
	}

	private String buildString(Map<String, String> map) {
		String signPre = "";
		int i = 0;
		for (String key : map.keySet()) {
			if (map.get(key) != null) {
				if (i == 0) {
					signPre = signPre + key + "=" + map.get(key);
				} else {
					signPre = signPre + "&" + key + "=" + map.get(key);
				}
			}
			i++;
		}
		return signPre;
	}

	@Override
	public PayBill queryBill(PayBillDao daoBill, PayBill bill) {
		return bill;
	}
}
