package cn.hmsoft.pay.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
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 PayJiaPengChannelImpl 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 "JP" + bill.getBusiness_type() + LocalDateHelper.formatLongNoSplit(LocalDateTime.now()) + v;
	}

	@Override
	public PayBill processReply(PayBillDao daoBill, PayBill bill, HttpServletRequest request,
			Map<String, Object> paramMap) {
		LogHelper.info("jiapeng 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();
			//this.logReply(bill, BillProcessResult.DatabaseError, "", request);
			return null;
		}
	}
	
	@Override
	public String makeRequestString(PayBill bill) {
		System.out.println(bill.getBill_param());
		LinkedHashMap<String, String> paramMap = StringHelper.toMap(bill.getBill_param());
		String PayMoney = new BigDecimal(bill.getBill_amount().toString()).divide(new BigDecimal("100")).setScale(2).toPlainString();//元
		String ItemName = "报名费";
		String ChargeMode = "weixin";
		String OrderNo = bill.getBill_no();
		String Timestamp = LocalDateHelper.formatLongNoSplit(LocalDateTime.now());
		String NotityUrl = payMerchantChannel.getNotice_url();
		String CallBackUrl = payMerchantChannel.getPage_url() + "?school_code=" + paramMap.get("school_code");//跳回衔接微信端
		String cert = payMerchantChannel.getPublic_key_path();

		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("BSchoolCode", paramMap.get("b_school_code"));//衔接学校代码
		map.put("CallBackUrl", CallBackUrl);//根据school_code拼
		map.put("ChargeMode", ChargeMode);
		map.put("EnrolTime", paramMap.get("enrol_time"));
		map.put("IDCode", paramMap.get("cert_id"));
		map.put("ItemName", ItemName);
		map.put("MajorCode", paramMap.get("major_code"));
		map.put("MajorName", paramMap.get("major_name"));//专业名称
		map.put("NotityUrl", NotityUrl);
		map.put("OrderNo", OrderNo);//订单编号
		map.put("PayMoney", PayMoney + "");//缴费金额
		map.put("PayTime", bill.getPay_time() != null ? LocalDateHelper.format(bill.getPay_time()) : LocalDateHelper.format(LocalDateTime.now()));
		map.put("Phone", paramMap.get("std_mobile"));
		map.put("StudentName", paramMap.get("std_name"));
		map.put("Term", paramMap.get("term"));
		map.put("TicketNo", paramMap.get("ticket_no"));//准考证号
		map.put("Timestamp", Timestamp);
		map.put("YearCode", paramMap.get("year_code"));
		
		String params = buildString(map);
		String Sign = SecureHelper.md5((params + cert)).toLowerCase();
		map.put("Sign", Sign);
		return JsonHelper.fromObjectWithChar(map);
	}
	
	@Override
	public Map<String, String> makeRequestAttr(PayBill bill) {
		//String feeid = merchantParamMap.get("feeid");
		
		return null;
	}

	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;
	}

	//private static String QUERY_URL = "http://cwjf.gxu.edu.cn/payment/portal/Query_PayQuery.action";//未参数化，只支持西大
	@Override
	public PayBill queryBill(PayBillDao daoBill, PayBill bill) {
		return bill;
	}
}
