package com.sckw.payment.service;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.sckw.core.utils.OkHttpUtils;
import com.sckw.payment.api.model.dto.common.R;
import com.sckw.payment.model.constant.PayXwEnum;
import com.sckw.payment.model.dto.wallet.WithdrawRes;
import com.sckw.payment.model.dto.xw.WithdrawDto;
import com.sckw.payment.model.vo.UserPara;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * 转发中台接口
 *
 * @author xucaiqin
 * @date 2023-07-21 17:45:51
 */
@Service
@Slf4j
@RefreshScope
public class PayXwService {
    @Value("${xw.address}")
    private String xwAddress;

    private String jsonHttp(PayXwEnum payXwEnum, Object object) {
        String para = object instanceof JSONObject jsonObject ? jsonObject.toJSONString() : JSONObject.toJSONString(object);
        log.info("{}入参->{}", payXwEnum.getDesc(), para);
        OkHttpUtils okHttpUtils = OkHttpUtils.builder().url(xwAddress + payXwEnum.getAddr());
        okHttpUtils.addBodyJsonStr(para);
        String sync;
        try {
            sync = okHttpUtils.post(true).sync();
        } catch (Exception e) {
            log.error("新网服务异常", e.getCause());
            throw new RuntimeException("支付服务异常!");
        }
        log.info("{}返回值->{}", payXwEnum.getDesc(), sync);
        return sync;
    }

    /**
     * 创建用户
     *
     * @return
     */
    public Object beforeCreateUser(UserPara userPara) {
        String sync = jsonHttp(PayXwEnum.BEFORE_CREATE, userPara);
        return JSONObject.parseObject(sync, new TypeReference<>() {
        });
    }

    /**
     * 提现
     *
     * @return
     */
    public R<WithdrawRes> withDraw(WithdrawDto withdrawDto) {
        String sync = jsonHttp(PayXwEnum.WITHDRAW_TAKE, withdrawDto);
        return JSONObject.parseObject(sync, new TypeReference<>() {
        });
    }
}
