/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.community.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ijpay.core.utils.DateTimeZoneUtil;
import com.ijpay.wxpay.model.v3.Amount;
import com.ijpay.wxpay.model.v3.UnifiedOrderModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springblade.community.entity.PlatformBills;
import org.springblade.community.mapper.PlatformBillsMapper;
import org.springblade.community.pay.wx.config.WxPayV3Config;
import org.springblade.community.pay.wx.event.PayNotifyEvent;
import org.springblade.community.pay.wx.exception.WxPayException;
import org.springblade.community.pay.wx.util.WxPayV3Util;
import org.springblade.community.service.IPlatformBillsService;
import org.springblade.community.vo.PlatformBillsVO;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * 园区平台账单 服务实现类
 *
 * @author BladeX
 * @since 2021-09-14
 */
@Service
@Slf4j
public class PlatformBillsServiceImpl extends BaseServiceImpl<PlatformBillsMapper, PlatformBills> implements IPlatformBillsService {
	@Autowired
	private HttpServletRequest request;

	@Override
	public IPage<PlatformBillsVO> selectPlatformBillsPage(IPage<PlatformBillsVO> page, PlatformBillsVO platformBills) {
		return page.setRecords(baseMapper.selectPlatformBillsPage(page, platformBills));
	}

	/**
	 * 生成账单并且返回微信支付链接
	 * @param platformBills
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(rollbackFor = WxPayException.class)
	public JSON saveBills(PlatformBills platformBills) throws Exception {
		//断言不能为null
		Assert.notNull(platformBills);

		//设置状态为待支付
		platformBills.setPayStatus(1);
		//先保存账单
		super.save(platformBills);

		//获取微信支付配置
		WxPayV3Config wxPayConfig = WxPayV3Util.getWxPayConfig();

		//设置订单金额
		Amount amount = new Amount();
		amount.setTotal(platformBills.getPrice().multiply(new BigDecimal(100)).intValue());

		//请求native下单
		return WxPayV3Util.createWxPayOfNative(WxPayV3Util.buildV3UnifiedOrderModel()
			.setOut_trade_no(platformBills.getId().toString())
			.setAmount(amount)
			.setTime_expire(DateTimeZoneUtil.dateToTimeZone(System.currentTimeMillis() + wxPayConfig.getExpire())));
	}

	/**
	 * 微信支付完成事件回调
	 * @param wxPayNotifyEvent
	 */
	@EventListener
	public void payNotify(PayNotifyEvent<String> wxPayNotifyEvent) {
		//判断是否成功
		if(StringUtils.isNotBlank(wxPayNotifyEvent.getObject())){
			//成功逻辑

			//转化JSON
			UnifiedOrderModel unifiedOrderModel = JSON.parseObject(wxPayNotifyEvent.getObject()).toJavaObject(UnifiedOrderModel.class);

			//获取订单号
			String out_trade_no = unifiedOrderModel.getOut_trade_no();
			//获取订单信息
			PlatformBills platformBills = this.getById(out_trade_no);
			if(platformBills==null){
				log.error("没有查询到{}订单",out_trade_no);
				return;
			}

			//设置状态为支付完成
			platformBills.setPayStatus(2);

			//更新订单信息
			this.updateById(platformBills);
		}else{
			//退款逻辑
		}
	}

}
