package org.springblade.payment.handle.handler;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import org.springblade.common.enums.PaymentScene;
import org.springblade.common.enums.ResCode;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.payment.handle.entity.HandleData;
import org.springblade.payment.handle.entity.Order;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.webSocket.WebSocketServer;
import org.springframework.util.Assert;

import java.math.BigDecimal;

/**
 * @author: lianghanqiang
 * @description: 用户需要调起微信支付
 * @since: 8/26/21 -- 6:54 PM
 */
@AllArgsConstructor
public class WxPayHandle implements BaseHandle {
	private IBillsService billsService;
	private WebSocketServer webSocketServer;

	/**
	 * 	未抵消的余额，发送订单信息到用户，用户根据订单信息调起微信支付
	 * */
	@Override
	public HandleData handle(BigDecimal remain, Order order, SuccessParams successParams) throws ServiceException {

		Bills bills = successParams.getBills();
		bills.setPayway(PaymentScene.MINI_PROGRAM.name());
		bills.setPrice(remain);

		//通知用户调起支付
		webSocketServer.sendInfo(order.getLoginUser().getId().toString(), JSON.toJSONString(bills));
		Assert.isTrue(billsService.saveOrUpdate(bills),()->{ throw new ServiceException(ResCode.INIT_ORDER_FAIL) ;});
		return HandleData.builder().isSuccess(Boolean.TRUE).successParams(successParams).remain(remain).build();
	}
}
