package com.ywt.outpatient.service.web;

import com.ywt.biz.common.util.Checker;
import com.ywt.gapi.ordercenter.*;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.domain.models.SubOrderInfo;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderCenterService {
    private final Logger logger = LoggerFactory.getLogger(OrderCenterService.class.getName());
    @Autowired
    private com.ywt.gapi.ordercenter.OrderCenterService orderCenterServiceBlockingStub;

    public ServiceResult wechatPayment(String body, String spbillCreateIp, String openid, int amount,
                                       int terminal, int orderId, int userId) {
        ServiceResult result = new ServiceResult();
        try {
            WechatPaymentRequest request = WechatPaymentRequest.newBuilder()
                    .setBody(body)
                    .setSpbillCreateIp(spbillCreateIp)
                    .setOpenid(openid)
                    .setAmount(amount)
                    .setTerminal(terminal)
                    .setOrderId(orderId)
                    .setUserId(userId)
                    .build();
            WechatPaymentResponse response = orderCenterServiceBlockingStub.wechatPayment(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                Map<String, Object> map = new HashMap<>();
                map.put("timeStamp", response.getTimeStamp());
                map.put("nonceStr", response.getNonceStr());
                map.put("package", response.getPackage());
                map.put("signType", response.getSignType());
                map.put("paySign", response.getPaySign());
                map.put("appId", response.getAppId());
                result.setData(map);
                return result.succeed("操作成功");
            }
            return result.failed(response.getInfo());
        } catch (Exception e) {
            logger.error("OrderCenterService#wechatPayment(): {}", e.getMessage(), e);
            return result.error(e.getMessage());
        }
    }

    public int getOrderType(int orderId) {
        GetOrderInfeResponse getOrderInfeResponse = orderCenterServiceBlockingStub.getOrderInfo(GetOrderInfoRequest.newBuilder().setOrderId(orderId).build());
        return getOrderInfeResponse.getOrderType();
    }

    public int getOrderTypeByOrderNo(String orderNo) {
        GetOrderInfoRequest request = GetOrderInfoRequest.newBuilder().setOrderNo(orderNo).build();
        GetOrderInfeResponse getOrderInfeResponse = orderCenterServiceBlockingStub.getOrderInfo(request);
        return getOrderInfeResponse.getOrderType();
    }

    public int getOrderIdByOrderNo(String orderNo) {
        GetOrderInfoRequest request = GetOrderInfoRequest.newBuilder().setOrderNo(orderNo).build();
        GetOrderInfeResponse getOrderInfeResponse = orderCenterServiceBlockingStub.getOrderInfo(request);
        return getOrderInfeResponse.getOrderId();
    }

    /**
     * 工行支付
     *
     * @param payCode         支付编号
     * @param spbillCreateIp 发起支付IP
     * @param openid         用户openid
     * @param amount         单位：分
     * @param terminal       发起支付终端
     * @param orderId        订单ID
     * @param userId         发起支付用户ID
     * @param payType        合并支付标识：1-单订单, 2-多订单合并支付，默认为1
     * @param subOrderList   子订单(用于多订单合并支付)
     * @return {@link ServiceResult}
     */
    public ServiceResult icbcPayment(String payCode, String spbillCreateIp, String openid, int amount,
                                     int terminal, int orderId, int userId, int payType, String body, List<SubOrderInfo> subOrderList) {
        ServiceResult result = new ServiceResult();
        try {
            if (payType == 2 && Checker.isNone(subOrderList)){
                return result.failed("请选择正确的支付方式");
            }
            List<ICBCPaymentRequest.SubOrder> orderList = new ArrayList<>();
            if (!Checker.isNone(subOrderList)){
                for (SubOrderInfo info : subOrderList) {
                    ICBCPaymentRequest.SubOrder order = ICBCPaymentRequest.SubOrder.newBuilder().setOrderId(info.getOrderId()).setAmount(info.getAmount()).build();
                    orderList.add(order);
                }
            }
            ICBCPaymentRequest request = ICBCPaymentRequest.newBuilder()
                    .setPayCode(payCode)
                    .setSpbillCreateIp(spbillCreateIp)
                    .setOpenid(openid)
                    .setAmount(amount)
                    .setTerminal(terminal)
                    .setOrderId(orderId)
                    .setUserId(userId)
                    .setPayType(payType)
                    .setBody(body)
                    .addAllSubOrder(orderList)
                    .build();
            ICBCPaymentResponse response = orderCenterServiceBlockingStub.icbcPayment(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                Map<String, Object> map = new HashMap<>();
                map.put("timeStamp", response.getTimeStamp());
                map.put("nonceStr", response.getNonceStr());
                map.put("package", response.getPackage());
                map.put("signType", response.getSignType());
                map.put("paySign", response.getPaySign());
                map.put("appId", response.getAppId());
                result.setData(map);
                return result.succeed("操作成功");
            }
            return result.failed(response.getInfo());
        } catch (Exception e) {
            logger.error("OrderCenterService#icbcPayment(): {}", e.getMessage(), e);
            return result.error(e.getMessage());
        }
    }

    public ServiceResult cleanPayLock(Integer orderId) {
        ServiceResult result = new ServiceResult();
        try {
            if (Checker.isNone(orderId) || orderId <= 0){
                return result.failed("订单id有误");
            }
            CleanPayLockRequest request = CleanPayLockRequest.newBuilder()
                    .setOrderId(orderId)
                    .build();
            CleanPayLockResponse response = orderCenterServiceBlockingStub.cleanPayLock(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                return result.succeed("操作成功");
            }
            return result.failed(response.getInfo());
        } catch (Exception e) {
            logger.error("OrderCenterService#cleanPayLock(): {}", e.getMessage(), e);
            return result.error(e.getMessage());
        }
    }

    public boolean checkIsPaying(Integer orderId) {
        try {
            if (Checker.isNone(orderId) || orderId <= 0){
                return false;
            }
            CheckIsPayingRequest request = CheckIsPayingRequest.newBuilder()
                    .setOrderId(orderId)
                    .build();
            CheckIsPayingResponse response = orderCenterServiceBlockingStub.checkIsPaying(request);
            if (response.getCode() == BaseResponse.SUCCEED) {
                return response.getPaying();
            }
            return false;
        } catch (Exception e) {
            logger.error("OrderCenterService#checkIsPaying(): {}", e.getMessage(), e);
            return false;
        }
    }
}
