package com.sqx.modules.shopping.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.config.AliPayConstants;
import com.sqx.modules.shopping.dao.OrdersJpaRepository;
import com.sqx.modules.shopping.entity.SelfOrders;
import com.sqx.modules.shopping.service.SelfAliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SelfAliPayServiceImpl implements SelfAliPayService {
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private CommonInfoService commonRepository;

    @Override
    public boolean refund(Long ordersId) {
        try {
            SelfOrders orders = ordersJpaRepository.getOne(ordersId);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            model.setOutTradeNo(orders.getOrderNum()); //订单号
            model.setRefundAmount(orders.getPayMoney()+""); //退款金额
            request.setBizModel(model);
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                return true;
            } else {
                return false;
            }
        }catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return false;
    }
}
