/*
 *      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.ldt.mall.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yeepay.yop.sdk.service.common.response.YopResponse;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.PaymentCache;
import org.springblade.common.constant.CallbackServeUrl;
import org.springblade.common.enums.AppConstant;
import org.springblade.common.enums.OrderType;
import org.springblade.common.enums.PaymentScene;
import org.springblade.common.enums.PaymentType;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.ldt.bills.entity.Bills;
import org.springblade.ldt.bills.service.IBillsService;
import org.springblade.ldt.mall.dto.MallBankRechargeOrderDto;
import org.springblade.ldt.mall.entity.Mall;
import org.springblade.ldt.mall.mapper.MallMapper;
import org.springblade.ldt.mall.service.IMallService;
import org.springblade.ldt.mall.vo.MallVO;
import org.springblade.payment.entity.SuccessParams;
import org.springblade.yeePay.common.YeePayConst;
import org.springblade.yeePay.common.YeepayApiConstant;
import org.springblade.yeePay.entity.saas.account.OnlineBankRechargeOrderDto;
import org.springblade.yeePay.service.YeepaySaasService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 服务实现类
 *
 * @author BladeX
 * @since 2021-09-23
 */
@AllArgsConstructor
@Service
public class MallServiceImpl extends BaseServiceImpl<MallMapper, Mall> implements IMallService {

	private YeepaySaasService yeepaySaasService;
	private YeePayConst yeePayConst;
	private IBillsService billsService;

	@Override
	public IPage<MallVO> selectMallPage(IPage<MallVO> page, MallVO mall) {
		return page.setRecords(baseMapper.selectMallPage(page, mall));
	}

	@Override
	public JSONObject recharge(MallBankRechargeOrderDto bankRechargeOrderDto, BladeUser bladeUser) {

		Mall mall = getOne(Wrappers.<Mall>lambdaQuery().select(Mall::getMerchantNo).eq(Mall::getTenantId, bladeUser.getTenantId()));

		//保存转账信息
		Bills bills = new Bills();
		bills.setPointNum(BigDecimal.ZERO);
		bills.setFee(BigDecimal.ZERO);
		bills.setPointFee(BigDecimal.ZERO);
		bills.setBalanceNum(BigDecimal.ZERO);
		bills.setPrice(bankRechargeOrderDto.getAmount());
		bills.setTotalPrice(bankRechargeOrderDto.getAmount());
		bills.setCost(bankRechargeOrderDto.getAmount());
		bills.setPayPlugin(PaymentType.YEE_PAY.name());
		bills.setTitle("商场充值");
		bills.setPayStatus(AppConstant.BillPayStatus.待付款.name());
		bills.setPayScene(PaymentScene.RECHARGE.name());
		bills.setType(OrderType.MALL_RECHARGE.name());
		bills.setDiscount(BigDecimal.ONE);
		bills.setPayId(bladeUser.getUserId());
		bills.setTenantId(bills.getTenantId());
		bills.setMallId(mall.getId());
		bills.setBillDesc(bankRechargeOrderDto.getRemark());
		billsService.saveOrUpdate(bills);

		return bankRechargeOrder(bills, mall, bankRechargeOrderDto.getBankCode());

	}

	/**
	 * @param :
	 * @Return void
	 * @Author July
	 * @Description 充值-银行汇款下单
	 * @Date 2021/10/22 13:48
	 */
	private JSONObject bankRechargeOrder(Bills bills, Mall mall, String bankCode) {
		String requestNo = IdUtil.simpleUUID();

		OnlineBankRechargeOrderDto dto = OnlineBankRechargeOrderDto.builder()
			.parentMerchantNo(yeePayConst.getPlatformServiceNo())
			.merchantNo(mall.getMerchantNo())
			.requestNo(requestNo)
			.payType(YeepayApiConstant.payType.B2B)
			.remark(bills.getBillDesc())
			.notifyUrl(CallbackServeUrl.CALL_BACK_SERVE_URL + "/withdraw/callback/YEE_PAY_WITHDRAW")
			.returnUrl(yeePayConst.getRechargeReturnUrl())
			.amount(bills.getPrice())
			.bankCode(bankCode)
			.build();

		YopResponse yopResponse = yeepaySaasService.onlineBankRechargeOrder(dto);
		JSONObject res = JSON.parseObject(yopResponse.getStringResult());
		if (!Objects.equals(res.getString("status"), "INIT")) {
			bills.setPayStatus(AppConstant.BillPayStatus.取消付款.name());
			bills.setBillDesc(res.getString("returnMsg"));
			billsService.saveOrUpdate(bills);
			throw new ServiceException(res.getString("returnMsg"));
		}

		//支付参数
		SuccessParams successParams = SuccessParams.builder()
			.orderType(OrderType.MALL_RECHARGE.name())
			.status(AppConstant.BillPayStatus.待付款.name())
			.bills(bills)
			.res(res)
			.build();

		PaymentCache.putSuccessParams(Convert.toStr(requestNo), successParams);
		return res;
	}

}
