package org.springblade.modules.payment.plugin;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.PaymentType;
import org.springblade.common.enums.ResCode;
import org.springblade.common.exception.BizException;
import org.springblade.core.tool.api.R;
import org.springblade.modules.ldt.billrecord.entity.BillRecord;
import org.springblade.modules.ldt.billrecord.service.impl.BillRecordServiceImpl;
import org.springblade.modules.payment.entity.PayParam;
import org.springblade.modules.payment.entity.SuccessParams;
import org.springblade.modules.payment.service.IPaymentService;
import org.springblade.yeePay.entity.CreateCodeDto;
import org.springblade.yeePay.entity.InitOrderDto;
import org.springblade.yeePay.entity.PayGateWayDto;
import org.springblade.yeePay.service.YeePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;

/**
 * @author: lianghanqiang
 * @description: 易宝支付插件
 * @since: 7/29/21 -- 2:56 PM
 */
@Component
@Slf4j
public class YeePayPlugin implements Payment {

	@Autowired
	YeePayService yeePayService;
	@Autowired
	BillRecordServiceImpl billRecordService;
	@Autowired
	IPaymentService paymentService;

	@Override
	public R nativePay(PayParam payParam) {

		//查询订单状态
		BillRecord bill = getOrderDetail(payParam,billRecordService);
		Assert.notNull(bill,"订单查询失败，无此订单信息！");

		//封装回调参数
		SuccessParams successParams = SuccessParams
			.builder()
			.billId(Convert.toStr(bill.getId()))
			.orderType(OrderType.valueOf(bill.getType()).name())
			.build();
		PaymentCache.putSuccessParams(Convert.toStr(bill.getId()),successParams);

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String expireTime = simpleDateFormat.format(bill.getExpireTime());

		//填充订单信息，生成订单，返回支付信息
		return yeePayService.createCode(
			CreateCodeDto.builder()
				.amount(Double.valueOf(bill.getPayAmount()))
				.goodsName(bill.getBillsTitle())
				.orderId(bill.getId().toString())
				.notifyUrl(callbackUrl(PaymentType.YEE_PAY.name()))
				.expiredTime(expireTime)
				.build());
	}

	@Override
	public R payCode(PayParam payParam) {
		return R.data("我还没有实现，你等等");
	}

	@Override
	public R transfer(PayParam payParam) {
		//查询订单状态
		BillRecord bill = getOrderDetail(payParam,billRecordService);
		Assert.notNull(bill,"订单查询失败，无此订单信息！");

		//封装回调参数
		SuccessParams successParams = SuccessParams
			.builder()
			.billId(Convert.toStr(bill.getId()))
			.orderType(OrderType.valueOf(bill.getType()).name())
			.build();
		PaymentCache.putSuccessParams(Convert.toStr(bill.getId()),successParams);


		return yeePayService.payByGateWay(
			PayGateWayDto.builder()
				.goodsName(bill.getBillsTitle())
				.orderId(Convert.toStr(bill.getId()))
				.orderAmount(Double.valueOf(bill.getPayAmount()))
				.appId(bill.getAppId())
				.notifyUrl(callbackUrl(PaymentType.YEE_PAY.name()))
				.build()
		);
	}

	@Override
	public void callback(HttpServletRequest request) {

		log.info("易宝网关支付回调： map"+ JSON.toJSONString(request.getParameterMap()));

		JSONObject jsonObject = yeePayService.deCodeNotifyData(request.getParameterMap().get("cipherText")[0]);
		log.info("易宝网关支付解密回调密文："+jsonObject.toJSONString());

		SuccessParams successParams = PaymentCache.getSuccessParams(jsonObject.getString("orderId"));

		Assert.notNull(successParams,"订单回调参数数据获取失败！");

		successParams.setPlatformId(jsonObject.getString("uniqueOrderNo"));
		successParams.setPayChannel(jsonObject.getString("channel"));
		successParams.setStatus(
			"SUCCESS".equals(jsonObject.getString("status")) ?
			SuccessParams.PAY_STATUS_SUCCESS:
			SuccessParams.PAY_STATUS_FAIL);
		//处理付款后业务流程
		paymentService.success(successParams);
	}

	@Override
	public R miniProgram(PayParam payParam) {
		//查询订单状态
		BillRecord bill = getOrderDetail(payParam,billRecordService);
		Assert.notNull(bill,"订单查询失败，无此订单信息！");

		//封装回调参数
		SuccessParams successParams = SuccessParams
			.builder()
			.billId(Convert.toStr(bill.getId()))
			.orderType(OrderType.valueOf(bill.getType()).name())
			.build();
		PaymentCache.putSuccessParams(Convert.toStr(bill.getId()),successParams);

		return yeePayService.initOrder(
			InitOrderDto.builder()
				.payWay("MINI_PROGRAM")
				.channel("WECHAT")
				.scene("OFFLINE")
				.goodsName(bill.getBillsTitle())
				.orderId(Convert.toStr(bill.getId()))
				.orderAmount(Double.valueOf(bill.getPayAmount()))
				.appId(bill.getAppId())
				.userId(bill.getOpenId())
				.userIp("127.0.0.1")
				.notifyUrl(callbackUrl(PaymentType.YEE_PAY.name()))
				.build()
		);
	}

	public static void main(String[] args) {
		String s = "{\n" +
			"    \"channelOrderId\":\"4200001123202108069046794860\",\n" +
			"    \"orderId\":\"1423594166159466497\",\n" +
			"    \"bankOrderId\":\"5955072001210806\",\n" +
			"    \"paySuccessDate\":\"2021-08-06 18:38:19\",\n" +
			"    \"channel\":\"WECHAT\",\n" +
			"    \"payWay\":\"USER_SCAN\",\n" +
			"    \"uniqueOrderNo\":\"1013202108060000002490940644\",\n" +
			"    \"orderAmount\":\"0.10\",\n" +
			"    \"payAmount\":\"0.10\",\n" +
			"    \"payerInfo\":\"{\\\"bankCardNo\\\":\\\"\\\",\\\"bankId\\\":\\\"CFT\\\",\\\"cardType\\\":\\\"CFT\\\",\\\"mobilePhoneNo\\\":\\\"\\\",\\\"userID\\\":\\\"o19581JoLz7p2SjLLoQ6jBBLN7Ws\\\"}\",\n" +
			"    \"realPayAmount\":\"0.10\",\n" +
			"    \"parentMerchantNo\":\"10086062555\",\n" +
			"    \"merchantNo\":\"10086062555\",\n" +
			"    \"status\":\"SUCCESS\"\n" +
			"}";
		JSONObject jsonObject = JSON.parseObject(s);
		System.out.println(jsonObject.getString("uniqueOrderNo"));

	}
}
