

package com.nantian.sc.cloud.pay.handler.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.nantian.sc.cloud.pay.entity.PayNotifyRecord;
import com.nantian.sc.cloud.pay.handler.PayNotifyCallbakHandler;
import com.nantian.sc.cloud.pay.service.PayNotifyRecordService;
import com.nantian.sc.cloud.pay.utils.PayConstants;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 *
 * @date 2019-06-27
 */
@Slf4j
public abstract class AbstractPayNotifyCallbakHandler implements PayNotifyCallbakHandler {
	/**
	 * 调用入口
	 *
	 * @param params
	 * @return
	 */
	@Override
	public String handle(Map<String, String> params) {

		// 初始化租户
		before(params);

		// 去重处理
		if (duplicateChecker(params)) {
			return null;
		}

		// 验签处理
		if (!verifyNotify(params)) {
			return null;
		}

		String result = parse(params);
		// 保存处理结果
		saveNotifyRecord(params, result);
		return result;
	}

	/**
	 * 保存记录
	 * @param params
	 * @param result
	 * @param record
	 * @param notifyId
	 * @param recordService
	 */
	void saveRecord(Map<String, String> params, String result, PayNotifyRecord record, String notifyId
			, PayNotifyRecordService recordService) {
		record.setNotifyId(notifyId);
		String orderNo = params.get(PayConstants.OUT_TRADE_NO);
		record.setOrderNo(orderNo);
		record.setRequest(MapUtil.join(params, StrUtil.DASHED, StrUtil.DASHED));
		record.setResponse(result);
		recordService.save(record);
	}
}
