package com.ywt.outpatient.service.web;

import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.order.GetWxPaymentRequest;
import com.ywt.gapi.order.GetWxPaymentResponse;
import com.ywt.gapi.order.OrderService;
import com.ywt.outpatient.service.rpc.common.ServiceResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentService {
    private static Logger logger = LoggerFactory.getLogger(PaymentService.class);

    @Autowired
    OrderService orderServiceBlockingStub;

    /**
     * 获取微信支付信息（服务商）
     *
     * @param orderId
     * @param userId
     * @param openId
     * @param ip
     * @param terminal
     * @param amount        支付金额
     * @param insuranceType 社保类型
     * @return
     */
    public ServiceResult getWxPaymentInfo(
            int orderId, int userId, String openId, String ip, int terminal, int amount, int insuranceType) {
        ServiceResult serviceResult = new ServiceResult();

        try {
            GetWxPaymentRequest req = GetWxPaymentRequest.newBuilder()
                    .setIp(ip)
                    .setOrderId(orderId)
                    .setUserId(userId)
                    .setOpenId(openId)
                    .setTerminal(terminal)
                    .setAmount(amount)
                    .setInsuranceType(insuranceType)
                    .build();
            GetWxPaymentResponse res = orderServiceBlockingStub.getWxPayment(req);
            Result result = res.getResult();

            if (result.getCode() == ResultCode.SUCCEED) {
                Map<String, Object> map = new HashMap<>();
                map.put("timeStamp", res.getTimeStamp());
                map.put("nonceStr", res.getNonceStr());
                map.put("package", res.getPackage());
                map.put("signType", res.getSignType());
                map.put("paySign", res.getPaySign());
                map.put("appId", res.getAppId());

                serviceResult.setData(map);
                return serviceResult.succeed();
            }

            return serviceResult.failed(result.getInfo());
        } catch (Exception e) {
            logger.error("getWxPaymentInfo(): {}", e.getMessage(), e);
            return serviceResult.error(e.getMessage());
        }
    }
}
