package com.crm.pay.service.impl.pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.pay.dto.finance.withdraw.automatic.FinanceWithdrawPay3payDto;
import com.crm.pay.entity.FinanceDepositCallbackValidateUpdateEntity;
import com.crm.pay.entity.callback.Pay3PayCallbackEntity;
import com.crm.pay.entity.property.Pay3PayPropertyEntity;
import com.crm.pay.entity.property.Pay3PayTypePropertyEntity;
import com.crm.pay.entity.property.Pay3PayWithdrawPropertyEntity;
import com.crm.pay.service.FinanceDepositService;
import com.crm.pay.service.Pay3PayService;
import com.crm.pay.service.SysChannelBankService;
import com.crm.pay.service.impl.base.BasePayServiceImpl;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.model.constant.PayConstants;
import com.crm.rely.backend.model.dto.finance.withdraw.FinanceWithdrawDto;
import com.crm.rely.backend.model.dto.sys.remittance.channel.bank.SysChannelBankDto;
import com.crm.rely.backend.model.entity.finance.deposit.FinanceDepositAddEntity;
import com.crm.pay.entity.FinanceDepositCallbackUpdateEntity;
import com.crm.pay.entity.finance.withdraw.FinanceWithdrawApproveChannelEntity;
import com.crm.pay.entity.finance.withdraw.FinanceWithdrawApproveChannelSubmitEntity;
import com.crm.pay.entity.finance.withdraw.automatic.FinanceWithdrawInfoEntity;
import com.crm.pay.entity.finance.withdraw.automatic.FinanceWithdrawPay3payEntity;
import com.crm.rely.backend.core.exception.PayValidatedException;
import com.crm.rely.backend.core.exception.ServiceException;
import com.crm.rely.backend.model.pojo.table.FinanceDepositTable;
import com.crm.rely.backend.model.pojo.table.FinanceWithdrawTable;
import com.crm.rely.backend.model.pojo.table.SysRemitChannelTable;
import com.crm.rely.backend.model.pojo.table.SysRemittanceChannelTable;
import com.crm.rely.backend.util.HAMCSHA256Util;
import com.crm.rely.backend.util.HttpUtil;
import com.google.common.base.Strings;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.jsoup.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.SecretKey;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class Pay3PayServiceImpl extends BasePayServiceImpl implements Pay3PayService {

    private final static String CALLBACK_MQ = "PAY3_CALLBACK_MQ";
    @Autowired
    private FinanceDepositService financeDepositService;
    @Autowired
    private SysChannelBankService sysChannelBankService;

    public static Claims parseJwt(String payload, String secret) {
        SecretKey key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(payload)
                .getPayload();
    }

    public static String getToken(String clientId, String apiSecret, String url) throws Exception {
        Map<String, String> heardMap = new LinkedHashMap<>();
        heardMap.put("api-secret", apiSecret);
        heardMap.put("client-id", clientId);

        log.info("url:" + url);
        log.info("resuest--client-id:" + clientId + ",api-secret:" + apiSecret);
        Connection.Response tokenResponse = HttpUtil.get(url, heardMap);
        String tokensStr = tokenResponse.body();
        log.info("respose--code:" + tokenResponse.statusCode() + ",body:" + tokensStr);

        JSONObject jsonObject = JSONObject.parseObject(tokensStr);
        String accessToken = jsonObject.getString("accessToken");
        return accessToken;
    }

    public static void main(String[] args) throws Exception {

        System.out.println(JSON.parseObject(new String(Base64.decodeBase64(
                "eyJkYXRhIjp7InN0YXR1cyI6IlNVQ0NFU1MiLCJvcmRlcklkIjoiIiwibWVzc2FnZSI6IlRyYW5zYWN0aW9uIGNvbXBsZXRlZCBzdWNjZXNzZnVsbHkiLCJyZXF1ZXN0SWQiOiJQRDIwMjYwMzI3MTAxNzIyODc1ODQ1XzY2Nzg5MzEyIiwicmVjZWlwdCI6InR4blJlY2VpcHQifX0="))));

//        String c = "";
//        Claims claims = parseJwt(c, "8LBT5Qw14rGU5ktvYmFUmU1g7dmEVvbKyPn2fzRQHexqzUNBmP");
//        System.out.println(claims);
//        claims = parseJwt(c, "L0TI7wKYrREbSbm2zfolSf2q3ytn4Ct85YBjdB6fFmq8rOCn8L");
//        System.out.println(claims);
        String clientId = "1116e757-5de5-4ab1-aa83-0f409d3ea6d0";
        String apiSecret = "L0TI7wKYrREbSbm2zfolSf2q3ytn4Ct85YBjdB6fFmq8rOCn8L";
        String urlToken = "https://api.prod.pay3.app/v1/auth/access-token";
        String urlQuery = "https://api.prod.pay3.app/v1/client/crypto-orders?requestId=%s&clientId=%s";
        String requestId = "PD20260327101722875845_66789312";
        String accessToken = getToken(clientId, apiSecret,
                urlToken);
        Map<String, String> heardMap = new LinkedHashMap<>();
        ;
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("access-token", accessToken);

        String url = String.format(urlQuery, requestId, clientId);
        Connection.Response response = HttpUtil.get(url, heardMap);
        log.info(String.format("url:%s,body:%s", url, response.body()));

        /*SecretKey key = Keys.hmacShaKeyFor("JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG".getBytes
        (StandardCharsets.UTF_8));
        JwtBuilder jwtBuilder = Jwts.builder().setId("234").setSubject("234")
                .setIssuedAt(new Date())
                .signWith(key);
        System.out.println(jwtBuilder.compact());*/

        //String token = "eyJhbGciOiJIUzM4NCJ9
        // .eyJkYXRhIjp7Im9yZGVyVHlwZSI6IkNSWVBUTyIsIm9yZGVySWQiOiIzMmJmMDMyNi1mMTRkLTRhOWItYjI0Zi1lODUxMGNkMDA5NGQiLCJvcmRlclN0YXR1cyI6IkNPTVBMRVRFRCIsInBheW1lbnRTdGF0dXMiOiJDT01QTEVURUQifSwicmVxdWVzdElkIjoiUEQyMDI1MDYxMTE0MDYyMzQwOTg0M182Njc1Mzg1MSIsInR5cGUiOiJwYXkzLXNkay10cmFuc2FjdGlvbi1zdGF0dXMifQ.V6e8MmkHRMuFm8utzdl33qFkr6Jd-DjY-WAPbJTYRRbK-gkscM_2Ry8_vBGZZJFr";
        /* String token = "eyJhbGciOiJIUzM4NCJ9.eyJqdGkiOiIyMzQiLCJzdWIiOiIyMzQiLCJpYXQiOjE3NDk2OTY5Mzd9
       .znZgyT3T4S2Ox1-N9FMZFRB4gesUGO0zqXHXMdVUpe46UNysOO8zsBcTkBOpSxWs";
        Claims claims = parseJwt(token,"JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG");
        System.out.println(claims);
        System.out.println(claims.get("jti").toString());
        JSONObject js = JSON.parseObject(claims.toString());
        System.out.println(js.toJSONString());*/

        /*String data =
        "eyJkYXRhIjp7InN0YXR1cyI6IkVSUk9SIiwib3JkZXJJZCI6IjhiZDZiMjI5LTFhMTAtNGRhYS05Yjk1LTRkOGI0ODUxZDkzZCIsIm1lc3NhZ2UiOiJUcmFuc2FjdGlvbiBmYWlsZWQiLCJyZXF1ZXN0SWQiOiJQRDIwMjUwNTI2MTkwNDUzNjkzMzk0XzY2NjAwNTcyIiwicmVjZWlwdCI6bnVsbH19";
        byte[] decodedBytes = Base64.decodeBase64(data);
        String decodedString= new String(decodedBytes);
        System.out.println(JSON.toJSONString(decodedString));
        Pay3PayCallbackEntity callbackEntity = JSON.parseObject(new String(Base64.decodeBase64(data)),
        Pay3PayCallbackEntity.class);
        System.out.println(JSON.toJSONString(callbackEntity));*/

        /*Claims claims = parseJwt("eyJhbGciOiJIUzM4NCJ9" +
                "
                .eyJkYXRhIjp7Im9yZGVyVHlwZSI6IkNSWVBUTyIsIm9yZGVySWQiOiIzMmJmMDMyNi1mMTRkLTRhOWItYjI0Zi1lODUxMGNkMDA5NGQiLCJvcmRlclN0YXR1cyI6IkNPTVBMRVRFRCIsInBheW1lbnRTdGF0dXMiOiJDT01QTEVURUQifSwicmVxdWVzdElkIjoiUEQyMDI1MDYxMTE0MDYyMzQwOTg0M182Njc1Mzg1MSIsInR5cGUiOiJwYXkzLXNkay10cmFuc2FjdGlvbi1zdGF0dXMifQ.V6e8MmkHRMuFm8utzdl33qFkr6Jd-DjY-WAPbJTYRRbK-gkscM_2Ry8_vBGZZJFr", "8LBT5Qw14rGU5ktvYmFUmU1g7dmEVvbKyPn2fzRQHexqzUNBmP");
        String requestId = claims.get("requestId").toString();
        String type = claims.get("type").toString();
        Pay3PayCallbackEntity callbackEntity = JSON.parseObject(JSON.toJSONString(claims.get("data")).toString(),
                Pay3PayCallbackEntity.class);
        System.out.println(callbackEntity);*/

        //13809488-ef5a-4e0e-9fe2-5b7e1acfaf33  3824b79d-713e-4c45-aec9-4c94dc0c2d50
        // 13809488-ef5a-4e0e-9fe2-5b7e1acfaf33
//        Pay3PayPropertyEntity payProperty = new Pay3PayPropertyEntity();
//        payProperty.setApiSecret("JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG");
//        payProperty.setBaseUrl("https://api.pprod.pay3.app");
//        payProperty.setTokenUrl("/v1/auth/access-token");
//
//        String accessToken = getToken("53ddec43-b5db-4813-a936-b443cfb81bd6", payProperty.getApiSecret(),
//                payProperty.getBaseUrl() + payProperty.getTokenUrl());
//
//        Map<String, String> map = new LinkedHashMap<>();
//        ;
//        map.put("requestId", "D20250521171506585468_666005723306");
//        map.put("address", "0xE088b93315A78a7d5335156F1eeb8eEEb1bB399B");
//        map.put("currency", "usdc_amoy");
//        map.put("amount", "1.00");
//        map.put("clientId", "53ddec43-b5db-4813-a936-b443cfb81bd6");
//        map.put("mode", "returnUrl");
//        map.put("callbackUrl", "https://testpay.6cd7e0f0b52.com/pay3pay/withdraw/callback");
//        map.put("sponsorFee", "true");
//
//        String signStr = "address=0xE088b93315A78a7d5335156F1eeb8eEEb1bB399B&currency=usdc_amoy&amount=1" +
//                ".00&requestId=D20250521171506585468_666005723306";
//        String signature = HAMCSHA256Util.HMACSHA256(signStr, "JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG");
//        System.out.println(JSON.toJSON(map));
//        System.out.println("signature:" + signature);
//
//        Map<String, String> heardMap = new LinkedHashMap<>();
//        ;
//        heardMap.put("Accept", "application/json");
//        heardMap.put("Content-Type", "application/json");
//        heardMap.put("signature", signature);
//        heardMap.put("access-token", accessToken);
//        //Connection.Response response = HttpUtil.post("https://api.pprod.pay3.app/v1/client/crypto-checkout/create-order",
//        // heardMap, map);
//        Connection.Response response = HttpUtil.post("https://api.pprod.pay3.app/v1/client/crypto-payout/create-order"
//                , heardMap, map);
//        System.out.println("respose--code:" + response.statusCode() + ",body:" + response.body());

        /* String url = String.format("https://api.pprod.pay3.app/v1/client/crypto-orders?requestId=%s&clientId=%s",
        "1747732342427",payProperty.getClientId());
        System.out.println(url);
        Connection.Response response = HttpUtil.get(url,heardMap);
        System.out.println("respose--code:"+response.statusCode()+",body:"+response.body());*/


        /*String con = "{\n" +
                "    \"apiSecret\":\"JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG\",\n" +
                "    \"tokenUrl\":\"/v1/auth/access-token\",\n" +
                "    \"checkoutOrderUrl\":\"/v1/client/crypto-checkout/create-order\",\n" +
                "    \"queryOrdeUrl\":\"/v1/client/crypto-orders?requestId=%s&clientId=%s\",\n" +
                "    \"callbackUrl\":\"https://testpay.6cd7e0f0b52.com/pay3pay/callback\",\n" +
                "    \"baseUrl\":\"https://api.pprod.pay3.app\",\n" +
                "    \"payType\":[\n" +
                "        {\n" +
                "            \"bankCode\":\"PAY3_USDT_ETHEREUM\",\n" +
                "            \"currency\":\"usdt_ethereum\",\n" +
                "            \"clientId\":\"13809488-ef5a-4e0e-9fe2-5b7e1acfaf33\",\n" +
                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"bankCode\":\"PAY3_USDC_ETHEREUM\",\n" +
                "            \"currency\":\"usdc_ethereum\",\n" +
                "            \"clientId\":\"13809488-ef5a-4e0e-9fe2-5b7e1acfaf33\",\n" +
                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"bankCode\":\"PAY3_USDT_POLYGON\",\n" +
                "            \"currency\":\"usdt_polygon\",\n" +
                "            \"clientId\":\"3824b79d-713e-4c45-aec9-4c94dc0c2d50\",\n" +
                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"bankCode\":\"PAY3_USDT_ETHEREUM\",\n" +
                "            \"currency\":\"usdc_polygon\",\n" +
                "            \"clientId\":\"3824b79d-713e-4c45-aec9-4c94dc0c2d50\",\n" +
                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";*/

//        String con = "{\n" +
//                "    \"apiSecret\":\"JPbpzhG6Mx9vDAXJ3pQFgEPBVT3tnCq9PWYFJsrjZUnmcAATTG\",\n" +
//                "    \"tokenUrl\":\"/v1/auth/access-token\",\n" +
//                "    \"payoutOrderUrl\":\"/v1/client/crypto-payout/create-order\",\n" +
//                "    \"queryOrderUrl\":\"/v1/client/crypto-orders?requestId=%s&clientId=%s\",\n" +
//                "    \"callbackUrl\":\"https://testpay.6cd7e0f0b52.com/pay3pay/withdraw/callback\",\n" +
//                "    \"agentCallbackUrl\":\"https://testpay.6cd7e0f0b52.com/pay3pay/agent/withdraw/callback\",\n" +
//                "    \"baseUrl\":\"https://api.pprod.pay3.app\",\n" +
//                "    \"payType\":[\n" +
//                "        {\n" +
//                "            \"currency\":\"usdc_amoy\",\n" +
//                "            \"clientId\":\"53ddec43-b5db-4813-a936-b443cfb81bd6\",\n" +
//                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
//                "        },\n" +
//                "        {\n" +
//                "            \"currency\":\"usdc_sepolia\",\n" +
//                "            \"clientId\":\"53ddec43-b5db-4813-a936-b443cfb81bd6\",\n" +
//                "            \"address\":\"0xe7C12Ab35885D726e75Bf88124ec4360bb369c38\"\n" +
//                "        }\n" +
//                "    ]\n" +
//                "  }";
        //System.out.println(AESUtil.encrypt(con, "bfa5559109f94c78af615bcf00d52060"));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String pay(FinanceDepositAddEntity balanceSaveEntity) throws Exception {
        //通道配置
        SysRemittanceChannelTable channel = getPayChannel(PayConstants.PAY3_PAY_KEY);
        //通道配置实体
        Pay3PayPropertyEntity payProperty = getPayProperty(channel, Pay3PayPropertyEntity.class);

        balanceSaveEntity.setCurrency(channel.getCurrency());
        balanceSaveEntity.setTransformCurrency(channel.getTransformCurrency());
        balanceSaveEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_PROCESSING_STATUS);
        balanceSaveEntity.setCallbackValidateMq(CALLBACK_MQ);
        FinanceDepositTable balanceTable = financeDepositService.save(balanceSaveEntity, channel);

        String url = getUrl(payProperty, balanceTable, balanceSaveEntity);
        balanceTable.setFormUrl(url);
        
        return url;
    }

    @JmsListener(destination = CALLBACK_MQ)
    @Transactional(rollbackFor = Exception.class)
    public void callbackValidate(String content) throws Exception {
        log.info(String.format("PAY3_CALLBACK_MQ,content:%s", content));
        FinanceDepositTable table = JSON.parseObject(content, FinanceDepositTable.class);
        if (table == null) {
            log.error("PAY3_CALLBACK_MQ,callbackEntity is null");
            return;
        }


        FinanceDepositCallbackValidateUpdateEntity financeDepositCallbackValidateUpdateEntity =
                new FinanceDepositCallbackValidateUpdateEntity();

        financeDepositCallbackValidateUpdateEntity.setId(table.getId());
        financeDepositCallbackValidateUpdateEntity.setSerial(table.getSerial());


        if (Strings.isNullOrEmpty(table.getCallbackData())) {
            financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
            financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
            log.error("pay3pay callbackValidate error,callbackData is null");
            return;
        }

        //获取配置
        Pay3PayPropertyEntity payProperty = getPayProperty(table.getPayType(), false,
                Pay3PayPropertyEntity.class);


        Pay3PayCallbackEntity callbackEntity = JSON.parseObject(table.getCallbackData(), Pay3PayCallbackEntity.class);
        Claims claims = null;
        try {
            claims = parseJwt(callbackEntity.getPayload(), payProperty.getApiSecret());
        } catch (Exception e) {
            financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
            financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
            log.error(String.format("pay3pay callbackValidate error,%s", e.getMessage()));
            return;
        }
        try {

            String requestId = claims.get("requestId").toString();
            String type = claims.get("type").toString();
            Pay3PayCallbackEntity callDataEntity = JSON.parseObject(JSON.toJSONString(claims.get("data")).toString(),
                    Pay3PayCallbackEntity.class);
            log.info(String.format(" callbackValidate pay3pay callback data:%s", JSON.toJSONString(callDataEntity)));


            if (Strings.isNullOrEmpty(requestId) || !"pay3-sdk-transaction-status".equals(type)) {
                financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
                financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
                log.error(String.format("pay3pay callbackValidate error,requestId:%s,type:%s", requestId, type));
                return;
            }

            String clientId = null;
            List<Pay3PayTypePropertyEntity> typeList = payProperty.getPayType();
            for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
                if (table.getBankCode().equals(payTypePropertyEntity.getBankCode())) {
                    clientId = payTypePropertyEntity.getClientId();
                    break;
                }
            }
            String accessToken = getToken(clientId, payProperty.getApiSecret(),
                    payProperty.getBaseUrl() + payProperty.getTokenUrl());
            Map<String, String> heardMap = new LinkedHashMap<>();

            heardMap.put("Accept", "application/json");
            heardMap.put("Content-Type", "application/json");
            heardMap.put("access-token", accessToken);

            String url = String.format(payProperty.getBaseUrl() + payProperty.getQueryOrdeUrlr(), requestId, clientId);
            Connection.Response response = HttpUtil.get(url, heardMap);
            log.info(String.format("url:%s,body:%s", url, response.body()));

            JSONObject requestEntity = JSON.parseObject(response.body());
            if (200 != response.statusCode() || requestEntity == null || requestEntity.size() == 0) {
                financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
                financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
                log.error(String.format("pay3pay callbackValidate error,status:%s,body:%s", response.statusCode(),
                        response.body()));
                return;
            }
            JSONObject jsonData = JSONArray.parseArray(requestEntity.getString("data")).getJSONObject(0);
            if (jsonData == null) {
                financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
                financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
                log.error(String.format("pay3pay callbackValidate error,data:%s", requestEntity.toJSONString()));
                return;
            }

            if ("COMPLETED".equals(jsonData.getString("orderStatus")) && "COMPLETED".equals(callDataEntity.getOrderStatus())) {
                financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_SUCCESS_STATUS);
                financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
                return;
            } else if ("FAILED".equals(jsonData.getString("orderStatus")) || "ABANDONED".equals(jsonData.getString(
                    "orderStatus"))) {
                financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
                financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
                log.error(String.format("pay3pay callbackValidate error,data:%s", requestEntity.toJSONString()));

            }
        } catch (Exception e) {
            financeDepositCallbackValidateUpdateEntity.setCallbackValidate(PayConstants.CALLBACE_VALIDATE_FAIL_STATUS);
            financeDepositService.updateCallbackValidate(financeDepositCallbackValidateUpdateEntity);
            log.error(String.format("pay3pay callbackValidate error,%s", e.getMessage()));
        }


    }
    /**
     * 回调处理数据
     *
     * @param callbackEntity
     * @throws ServiceException
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public String callback(Pay3PayCallbackEntity callbackEntity) throws Exception {
//        log.info(String.format("pay3pay callback  :%s", JSON.toJSONString(callbackEntity)));
//
//        //获取配置
//        Pay3PayPropertyEntity payProperty = getPayProperty(PayConstants.PAY3_PAY_KEY, Pay3PayPropertyEntity.class);
//        JSONObject dataJson = JSON.parseObject(new String(Base64.decodeBase64(callbackEntity.getData())));
//        log.info(String.format("pay3pay callback dataDecode:%s", dataJson.toString()));
//
//        Pay3PayCallbackEntity callDataEntity = JSON.parseObject(dataJson.getString("data"),
//                Pay3PayCallbackEntity.class);
//        if (Strings.isNullOrEmpty(callDataEntity.getRequestId())) {
//            return Constants.FAIL;
//        }
//
//        //验证传输数据
//        int status = PayConstants.CALLBACE_PROCESSING_STATUS;
//        if ("SUCCESS".equals(callDataEntity.getStatus())) {
//            status = PayConstants.CALLBACE_SUCCESS_STATUS;
//        } else if ("ERROR".equals(callDataEntity.getStatus())) {
//            status = PayConstants.CALLBACE_FAIL_STATUS;
//        }
//
//        String clientId = null;
//        FinanceDepositTable table = financeDepositService.getBySerial(callDataEntity.getRequestId().split("_")[0]);
//        List<Pay3PayTypePropertyEntity> typeList = payProperty.getPayType();
//        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
//            if (table.getBankCode().equals(payTypePropertyEntity.getBankCode())) {
//                clientId = payTypePropertyEntity.getClientId();
//                break;
//            }
//        }
//
//        String accessToken = getToken(clientId, payProperty.getApiSecret(),
//                payProperty.getBaseUrl() + payProperty.getTokenUrl());
//        Map<String, String> heardMap = new LinkedHashMap<>();
//        heardMap.put("Accept", "application/json");
//        heardMap.put("Content-Type", "application/json");
//        heardMap.put("access-token", accessToken);
//
//        String url = String.format(payProperty.getBaseUrl() + payProperty.getQueryOrdeUrlr(),
//                callDataEntity.getRequestId(), clientId);
//        Connection.Response response = HttpUtil.get(url, heardMap);
//        log.info(String.format("url:%s,body:%s", url, response.body()));
//
//        JSONObject requestEntity = JSON.parseObject(response.body());
//        if (200 != response.statusCode() || requestEntity == null || requestEntity.size() == 0) {
//            return Constants.FAIL;
//        }
//        JSONObject jsonData = JSONArray.parseArray(requestEntity.getString("data")).getJSONObject(0);
//        if (jsonData == null) {
//            return Constants.FAIL;
//        }
//        if (!callDataEntity.getOrderId().equals(jsonData.getString("orderId")) || !callDataEntity.getRequestId()
//        .equals(jsonData.getString("requestId"))) {
//            return Constants.FAIL;
//        }
//
//        if (!"COMPLETED".equals(jsonData.getString("orderStatus"))) {
//            return Constants.FAIL;
//        }
//
//        FinanceDepositCallbackUpdateEntity balanceCallbackUpdateEntity =
//                getFinanceDepositCallbackUpdateEntity(callDataEntity.getRequestId(), callDataEntity.getOrderId(),
//                        status, callbackEntity);
//        balanceCallbackUpdateEntity.setNote(callDataEntity.getStatus());
//        balanceCallbackUpdateEntity.setTransformAmount(jsonData.getString("receivedAmount") == null ? null :
//                new BigDecimal(jsonData.getString("receivedAmount")));
//
//        /**
//         * 更新数据
//         */
//        financeDepositService.updateCallback(balanceCallbackUpdateEntity);
//        return Constants.SUCCESS;
//    }

    /**
     * 回调处理数据
     *
     * @param callbackEntity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String callbackPost(Pay3PayCallbackEntity callbackEntity) throws Exception {
        log.info(String.format("pay3pay callback data:%s", JSON.toJSONString(callbackEntity)));

//        //获取配置
        Pay3PayPropertyEntity payProperty = getPayProperty(PayConstants.PAY3_PAY_KEY, false,
                Pay3PayPropertyEntity.class);

//        String p = "";
//        //获取配置
//        Pay3PayPropertyEntity payProperty = JSON.parseObject(AESUtil.decrypt(p, "bfa5559109f94c78af615bcf00d52060"),
//                Pay3PayPropertyEntity.class);


        Claims claims = parseJwt(callbackEntity.getPayload(), payProperty.getApiSecret());
        String requestId = claims.get("requestId").toString();
        String type = claims.get("type").toString();
        Pay3PayCallbackEntity callDataEntity = JSON.parseObject(JSON.toJSONString(claims.get("data")).toString(),
                Pay3PayCallbackEntity.class);
        log.info(String.format("pay3pay callback data:%s", JSON.toJSONString(callDataEntity)));
        if (Strings.isNullOrEmpty(requestId) || !"pay3-sdk-transaction-status".equals(type)) {
            return Constants.FAIL;
        }


//        if ("COMPLETED".equals(callDataEntity.getOrderStatus())) {
//            status = PayConstants.CALLBACE_SUCCESS_STATUS;
//        } else if ("FAILED".equals(callDataEntity.getOrderStatus()) || "ABANDONED".equals(callDataEntity
//        .getOrderStatus())) {
//            status = PayConstants.CALLBACE_FAIL_STATUS;
//        }

        String clientId = null;
        FinanceDepositTable table = financeDepositService.getBySerial(requestId.split("_")[0]);
        List<Pay3PayTypePropertyEntity> typeList = payProperty.getPayType();
        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
            if (table.getBankCode().equals(payTypePropertyEntity.getBankCode())) {
                clientId = payTypePropertyEntity.getClientId();
                break;
            }
        }

        String accessToken = getToken(clientId, payProperty.getApiSecret(),
                payProperty.getBaseUrl() + payProperty.getTokenUrl());
        Map<String, String> heardMap = new LinkedHashMap<>();

        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("access-token", accessToken);

        String url = String.format(payProperty.getBaseUrl() + payProperty.getQueryOrdeUrlr(), requestId, clientId);
        Connection.Response response = HttpUtil.get(url, heardMap);
        log.info(String.format("url:%s,body:%s", url, response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (200 != response.statusCode() || requestEntity == null || requestEntity.size() == 0) {
            return Constants.FAIL;
        }
        JSONObject jsonData = JSONArray.parseArray(requestEntity.getString("data")).getJSONObject(0);
        if (jsonData == null) {
            return Constants.FAIL;
        }
        if (!callDataEntity.getOrderStatus().equals(jsonData.getString("orderStatus")) || !callDataEntity.getOrderId().equals(jsonData.getString("orderId"))
                || !requestId.equals(jsonData.getString("requestId"))) {
            return Constants.FAIL;
        }
//        String ip = IPUtil.getIp();
//        if (!Strings.isNullOrEmpty(ip)) {
//            return Constants.FAIL;
//        }
//        if (!"54.161.82.209".equals(ip)) {
//            return Constants.FAIL;
//        }

        int status = PayConstants.CALLBACE_PROCESSING_STATUS;
        if ("COMPLETED".equals(jsonData.getString("orderStatus")) && "COMPLETED".equals(callDataEntity.getOrderStatus())) {
            status = PayConstants.CALLBACE_SUCCESS_STATUS;
        } else if ("FAILED".equals(jsonData.getString("orderStatus")) || "ABANDONED".equals(jsonData.getString(
                "orderStatus"))) {
            status = PayConstants.CALLBACE_FAIL_STATUS;
        }

        FinanceDepositCallbackUpdateEntity balanceCallbackUpdateEntity =
                getFinanceDepositCallbackUpdateEntity(requestId, callDataEntity.getOrderId(),
                        status, callbackEntity);
        balanceCallbackUpdateEntity.setNote(callbackEntity.getOrderStatus());
        balanceCallbackUpdateEntity.setTransformAmount(jsonData.getString("receivedAmount") == null ? null :
                new BigDecimal(jsonData.getString("receivedAmount")));

        /**
         * 更新数据
         */
        financeDepositService.updateCallback(balanceCallbackUpdateEntity);
        return Constants.SUCCESS;
    }

    /**
     * 获取支付url
     *
     * @param balanceTable
     * @return
     * @throws ServiceException
     */
    private String getUrl(Pay3PayPropertyEntity propertyEntity, FinanceDepositTable balanceTable,
                          FinanceDepositAddEntity balanceSaveEntity) throws Exception {
        String orderNo = balanceTable.getSerial() + "_" + balanceTable.getLogin();

        Map<String, String> map = new LinkedHashMap<>();
        map.put("requestId", orderNo);
        map.put("amount", String.format("%.2f", balanceTable.getTransformAmount().doubleValue()));
        map.put("mode", "returnUrl");
        map.put("callbackUrl", propertyEntity.getCallbackUrlUrl());
        List<Pay3PayTypePropertyEntity> typeList = propertyEntity.getPayType();
        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
            if (balanceSaveEntity.getBankCode().equals(payTypePropertyEntity.getBankCode())) {
                map.put("currency", payTypePropertyEntity.getCurrency());
                map.put("address", payTypePropertyEntity.getAddress());
                map.put("clientId", payTypePropertyEntity.getClientId());
                break;
            }
        }

        String accessToken = getToken(map.get("clientId"), propertyEntity.getApiSecret(),
                propertyEntity.getBaseUrl() + propertyEntity.getTokenUrl());

        String signature = getSign(propertyEntity.getApiSecret(), map);
        Map<String, String> heardMap = new LinkedHashMap<>();
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("signature", signature);
        heardMap.put("access-token", accessToken);

        Connection.Response response =
                HttpUtil.post(propertyEntity.getBaseUrl() + propertyEntity.getCheckoutOrderUrl(), heardMap, map);
        log.info(String.format("url:%s,json:%s,body:%s",
                propertyEntity.getBaseUrl() + propertyEntity.getCheckoutOrderUrl(), JSON.toJSON(map), response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (200 != response.statusCode() || requestEntity == null) {
            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact customer" +
                    " service.");
        }

        String url = requestEntity.getString("url");
        if (Strings.isNullOrEmpty(url)) {
            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact customer" +
                    " service.");
        }
        log.info(String.format("支付请求,请求orderNo:%s,请求url:%s", map.get("requestId"), url));

        return url;
    }

    @Override
    public FinanceWithdrawPay3payDto withdrawInfo(FinanceWithdrawInfoEntity entity) throws Exception {
        FinanceWithdrawDto withdrawDto = null;
        if (entity.getWithdrawInfoType() == null || entity.getWithdrawInfoType().equals(1)) {
            withdrawDto = financeWithdrawService.searchSingle(entity.getId());

        } else {
            //withdrawDto = financeAgentWithdrawService.searchSingle(entity.getId());
        }

        entity.setPayType(entity.getPayType());

        SysRemitChannelTable withdrawChannel = getWithdrawChannel(entity.getPayType());

        FinanceWithdrawPay3payDto dto = new FinanceWithdrawPay3payDto();
        dto.setAmount(withdrawDto.getTransformAmount() == null ? null :
                withdrawDto.getTransformAmount().setScale(2, BigDecimal.ROUND_DOWN));
        dto.setCurrency(withdrawDto.getBankCode());
        dto.setAddress(withdrawDto.getAddress());
        List<SysChannelBankDto> channelBank = sysChannelBankService.getByChannelCode(entity.getPayType(), 1);
        Map<String, String> currencyMap = new HashMap();
        for (SysChannelBankDto channelBankDto : channelBank) {
            currencyMap.put(channelBankDto.getName(), channelBankDto.getCode());
        }
        dto.setCurrencySelect(currencyMap);

        dto.setId(withdrawDto.getId());
        dto.setWithdrawUrl(withdrawChannel.getWithdrawUrl());
        dto.setSerial(withdrawDto.getSerial());
        dto.setPayType(entity.getPayType());

        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String withdraw(FinanceWithdrawPay3payEntity entity) throws Exception {
        FinanceWithdrawDto withdrawDto = null;
        if (entity.getWithdrawInfoType() == null || entity.getWithdrawInfoType().equals(1)) {
            withdrawDto = financeWithdrawService.searchSingle(entity.getId());

        } else {
            //withdrawDto = financeAgentWithdrawService.searchSingle(entity.getId());
        }
        entity.setCId(withdrawDto.getCId());
        entity.setSerial(withdrawDto.getSerial());
        entity.setLogin(withdrawDto.getLogin());

        Pay3PayWithdrawPropertyEntity withdrawProperty = getWithdrawProperty(entity.getPayType(),
                Pay3PayWithdrawPropertyEntity.class);

        String url = payout(entity, withdrawProperty);

        FinanceWithdrawApproveChannelSubmitEntity financeWithdrawApproveChannelSubmitEntity =
                new FinanceWithdrawApproveChannelSubmitEntity();
        financeWithdrawApproveChannelSubmitEntity.setSubmitStatus(PayConstants.PASSED_STATUS);
        financeWithdrawApproveChannelSubmitEntity.setId(entity.getId());
        financeWithdrawApproveChannelSubmitEntity.setActualPayType(entity.getPayType());
        if (entity.getWithdrawInfoType() == null || entity.getWithdrawInfoType().equals(1)) {
            financeWithdrawService.approve(financeWithdrawApproveChannelSubmitEntity);

        } else {
            //financeAgentWithdrawService.approve(financeWithdrawApproveChannelSubmitEntity);
        }

        return url;
    }

    private String payout(FinanceWithdrawPay3payEntity entity, Pay3PayWithdrawPropertyEntity propertyEntity) throws Exception {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("requestId", entity.getSerial());

        map.put("address", entity.getAddress());
        map.put("currency", entity.getCurrency());
        map.put("amount", String.format("%.2f", entity.getAmount().doubleValue()));
        map.put("mode", "returnUrl");
        map.put("sponsorFee", "true");
        List<Pay3PayTypePropertyEntity> typeList = propertyEntity.getPayType();
        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
            if (entity.getCurrency().equals(payTypePropertyEntity.getCurrency())) {
                map.put("currency", payTypePropertyEntity.getCurrency());

                map.put("clientId", payTypePropertyEntity.getClientId());
                break;
            }
        }
        if (entity.getWithdrawInfoType() == null || entity.getWithdrawInfoType().equals(1)) {
            map.put("callbackUrl", propertyEntity.getCallbackUrl());
        } else {
            map.put("callbackUrl", propertyEntity.getAgentCallbackUrl());
        }

        String accessToken = getToken(map.get("clientId"), propertyEntity.getApiSecret(),
                propertyEntity.getBaseUrl() + propertyEntity.getTokenUrl());

        String signature = getSign(propertyEntity.getApiSecret(), map);
        Map<String, String> heardMap = new LinkedHashMap<>();
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("signature", signature);
        heardMap.put("access-token", accessToken);

        Connection.Response response = HttpUtil.post(propertyEntity.getBaseUrl() + propertyEntity.getPayoutOrderUrl()
                , heardMap, map);
        log.info(String.format("url:%s,json:%s,body:%s",
                propertyEntity.getBaseUrl() + propertyEntity.getPayoutOrderUrl(), JSON.toJSON(map), response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (200 != response.statusCode() || requestEntity == null) {
            if (Strings.isNullOrEmpty(requestEntity.getString("error"))) {
                throw new PayValidatedException("Payment platform is abnormal, please try again later or contact " +
                        "customer service.");
            } else {
                JSONObject errorJs = JSON.parseObject(requestEntity.getString("error"));
                throw new PayValidatedException(errorJs.getString("message"));
            }
        }

        String url = requestEntity.getString("url");
        if (Strings.isNullOrEmpty(url)) {
            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact customer" +
                    " service.");
        }

        return url;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String withdrawCallbackGet(Integer withdrawType, Pay3PayCallbackEntity callbackEntity) throws Exception {
        log.info(String.format("pay3pay withdraw callback data:%s", JSON.toJSONString(callbackEntity)));

        JSONObject dataJson = JSON.parseObject(new String(Base64.decodeBase64(callbackEntity.getData())));
        log.info(String.format("pay3pay withdraw callback dataDecode:%s", dataJson.toString()));

        Pay3PayCallbackEntity callDataEntity = JSON.parseObject(dataJson.getString("data"),
                Pay3PayCallbackEntity.class);
        if (Strings.isNullOrEmpty(callDataEntity.getRequestId())) {
            return Constants.FAIL;
        }

        String clientId = null;
        String serial = callDataEntity.getRequestId().split("_")[0];
        String remitCode = null;
        String bankCode = null;
        if (withdrawType == null || withdrawType.equals(1)) {
            FinanceWithdrawTable table = financeWithdrawService.getBySerial(serial);
            if (table == null) {
                throw ServiceException.exception();
            }
            remitCode = table.getRemitChannelCode();
            bankCode = table.getBankCode();
        } else {
           /* FinanceAgentWithdrawTable table = financeAgentWithdrawService.getBySerial(serial);
            if (table == null) {
                throw ServiceException.exception();
            }
            remitCode = table.getRemitChannelCode();
            bankCode = table.getBankCode();*/
        }

        //获取配置
        Pay3PayWithdrawPropertyEntity payProperty = getWithdrawProperty(remitCode,
                Pay3PayWithdrawPropertyEntity.class);

        List<Pay3PayTypePropertyEntity> typeList = payProperty.getPayType();
        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
            if (bankCode != null && bankCode.equals(payTypePropertyEntity.getCurrency())) {
                clientId = payTypePropertyEntity.getClientId();
                break;
            }
        }

        String accessToken = getToken(clientId, payProperty.getApiSecret(),
                payProperty.getBaseUrl() + payProperty.getTokenUrl());
        Map<String, String> heardMap = new LinkedHashMap<>();
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("access-token", accessToken);

        String url = String.format(payProperty.getBaseUrl() + payProperty.getQueryOrderUrl(),
                callDataEntity.getRequestId(), clientId);
        Connection.Response response = HttpUtil.get(url, heardMap);
        log.info(String.format("url:%s,body:%s", url, response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (200 != response.statusCode() || requestEntity == null || requestEntity.size() == 0) {
            return Constants.FAIL;
        }
        JSONObject jsonData = JSONArray.parseArray(requestEntity.getString("data")).getJSONObject(0);
        if (jsonData == null) {
            return Constants.FAIL;
        }
        if (!callDataEntity.getRequestId().equals(jsonData.getString("requestId"))) {
            return Constants.FAIL;
        }

        FinanceWithdrawApproveChannelEntity financeWithdrawApproveChannelEntity =
                new FinanceWithdrawApproveChannelEntity();
        financeWithdrawApproveChannelEntity.setChannelSerial(callDataEntity.getOrderId());

        if ("SUCCESS".equals(callDataEntity.getStatus())) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_SUCCESS_STATUS);
        } else if ("ERROR".equals(callDataEntity.getStatus())) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_FAIL_STATUS);
        } else {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_PROCESSING_STATUS);
        }
        financeWithdrawApproveChannelEntity.setSerial(callDataEntity.getRequestId());

        /**
         * 更新数据
         */
        if (withdrawType == null || withdrawType.equals(1)) {
            financeWithdrawService.approve(financeWithdrawApproveChannelEntity);

        } else {
            //financeAgentWithdrawService.channel(financeWithdrawApproveChannelEntity);
        }

        return Constants.SUCCESS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String withdrawCallbackPost(Integer withdrawType, Pay3PayCallbackEntity callbackEntity) throws Exception {
        log.info(String.format("pay3pay withdraw callback data:%s", JSON.toJSONString(callbackEntity)));

        //获取配置
        Pay3PayWithdrawPropertyEntity payProperty = getWithdrawProperty(PayConstants.PAY3_PAY_TYPE_REMIT,
                Pay3PayWithdrawPropertyEntity.class);

        Claims claims = parseJwt(callbackEntity.getPayload(), payProperty.getApiSecret());
        String requestId = claims.get("requestId").toString();
        String type = claims.get("type").toString();
        Pay3PayCallbackEntity callDataEntity = JSON.parseObject(JSON.toJSONString(claims.get("data")).toString(),
                Pay3PayCallbackEntity.class);
        log.info(String.format("pay3pay withdraw callback data:%s", JSON.toJSONString(callDataEntity)));
        if (Strings.isNullOrEmpty(requestId) || !"pay3-sdk-transaction-status".equals(type)) {
            return Constants.FAIL;
        }

        String clientId = null;
        FinanceWithdrawTable table = financeWithdrawService.getBySerial(requestId);
        List<Pay3PayTypePropertyEntity> typeList = payProperty.getPayType();
        for (Pay3PayTypePropertyEntity payTypePropertyEntity : typeList) {
            if (table.getBankCode().equals(payTypePropertyEntity.getCurrency())) {
                clientId = payTypePropertyEntity.getClientId();
                break;
            }
        }

        String accessToken = getToken(clientId, payProperty.getApiSecret(),
                payProperty.getBaseUrl() + payProperty.getTokenUrl());
        Map<String, String> heardMap = new LinkedHashMap<>();
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        heardMap.put("access-token", accessToken);

        String url = String.format(payProperty.getBaseUrl() + payProperty.getQueryOrderUrl(), requestId, clientId);
        Connection.Response response = HttpUtil.get(url, heardMap);
        log.info(String.format("url:%s,body:%s", url, response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (200 != response.statusCode() || requestEntity == null || requestEntity.size() == 0) {
            return Constants.FAIL;
        }
        JSONObject jsonData = JSONArray.parseArray(requestEntity.getString("data")).getJSONObject(0);
        if (jsonData == null) {
            return Constants.FAIL;
        }
        if (!callDataEntity.getOrderStatus().equals(jsonData.getString("orderStatus")) || !callDataEntity.getOrderId().equals(jsonData.getString("orderId"))
                || callDataEntity.getOrderType().equals(jsonData.getString("orderType")) || !requestId.equals(jsonData.getString("requestId"))) {
            return Constants.FAIL;
        }

        FinanceWithdrawApproveChannelEntity financeWithdrawApproveChannelEntity =
                new FinanceWithdrawApproveChannelEntity();
        financeWithdrawApproveChannelEntity.setChannelSerial(callDataEntity.getOrderId());

        if ("COMPLETED".equals(callDataEntity.getOrderStatus())) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_SUCCESS_STATUS);
        } else if ("FAILED".equals(callDataEntity.getOrderStatus()) || "ABANDONED".equals(callDataEntity.getOrderStatus())) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_FAIL_STATUS);
        } else {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_PROCESSING_STATUS);
        }
        financeWithdrawApproveChannelEntity.setSerial(requestId);

        /**
         * 更新数据
         */
        if (withdrawType == null || withdrawType.equals(1)) {
            financeWithdrawService.approve(financeWithdrawApproveChannelEntity);

        } else {
            //financeAgentWithdrawService.channel(financeWithdrawApproveChannelEntity);
        }

        return Constants.SUCCESS;
    }

    /*public static JSONObject getpaymentMethod(Pay3PayPropertyEntity payProperty) throws Exception {
        Map<String, String> heardMap = new LinkedHashMap<>();;
        heardMap.put("Accept", "application/json");
        heardMap.put("Content-Type", "application/json");
        log.info("https://api.pprod.pay3.app/v2/client/payment-methods?clientId=13809488-ef5a-4e0e-9fe2-5b7e1acfaf33
        &type=CHECKOUT");
        Connection.Response response = HttpUtil.get("https://api.pprod.pay3
        .app/v2/client/payment-methods?clientId=13809488-ef5a-4e0e-9fe2-5b7e1acfaf33&type=CHECKOUT",heardMap);
        String methodStr= response.body();
        log.info("respose--code:"+response.statusCode()+",body:"+methodStr);
        JSONObject methodJs= JSONObject.parseObject(methodStr);
        JSONArray typeObjects = JSONArray.parseArray(methodJs.getString("PaymentMethods"));

        return typeObjects.getJSONObject(0);
    }*/

    /**
     * 签名sign
     *
     * @param secretKey
     * @return
     * @throws ServiceException
     */
    private String getSign(String secretKey, Map<String, String> map) {
        String signString =
                "address=" + map.get("address") + "&currency=" + map.get("currency") + "&amount=" + map.get("amount") + "&requestId=" + map.get("requestId");
        String signature = HAMCSHA256Util.HMACSHA256(signString, secretKey);
        log.info(String.format("签名:%s,sign string:%s,sign:%s", map.get("requestId"), signString, signature));

        return signature;
    }

}