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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.pay.dto.finance.withdraw.automatic.FinanceWithdrawNepayDto;
import com.crm.pay.entity.callback.NePayCallbackEntity;
import com.crm.pay.entity.property.NePayBankPropertyEntity;
import com.crm.pay.entity.property.NePayPropertyEntity;
import com.crm.pay.entity.property.NePayWithdrawPropertyEntity;
import com.crm.pay.service.FinanceDepositService;
import com.crm.pay.service.NePayService;
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.entity.finance.deposit.FinanceDepositAddEntity;
import com.crm.pay.entity.FinanceDepositCallbackUpdateEntity;
import com.crm.rely.backend.model.entity.finance.deposit.FinanceMerchantDepositAddEntity;
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.FinanceWithdrawNepayEntity;
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.SysRemitChannelTable;
import com.crm.rely.backend.model.pojo.table.SysRemittanceChannelTable;
import com.crm.rely.backend.util.HttpUtil;
import com.crm.rely.backend.util.MD5Util;
import com.crm.rely.backend.util.MapUtil;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Service
public class NePayServiceImpl extends BasePayServiceImpl implements NePayService {

    @Autowired
    private FinanceDepositService financeDepositService;

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

        balanceSaveEntity.setCurrency(channel.getCurrency());
        balanceSaveEntity.setTransformCurrency(channel.getTransformCurrency());

        FinanceDepositTable balanceTable = financeDepositService.save(balanceSaveEntity, channel);

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String pay(FinanceMerchantDepositAddEntity balanceSaveEntity) throws Exception {
        //通道配置
        SysRemittanceChannelTable channel = getPayChannel(balanceSaveEntity.getPayType());
        //通道配置实体
        NePayPropertyEntity propertyEntity = getPayProperty(channel, NePayPropertyEntity.class);

        balanceSaveEntity.setCurrency(channel.getCurrency());
        balanceSaveEntity.setTransformCurrency(channel.getTransformCurrency());

        FinanceDepositTable balanceTable = financeDepositService.save(balanceSaveEntity, channel);

        String orderNo = balanceTable.getSerial() + "_" + balanceTable.getLogin();
        Map<String, String> map = new LinkedHashMap<>();
        String secretKey = "";

        for (NePayBankPropertyEntity bank : propertyEntity.getBanks()) {
            if (balanceSaveEntity.getBankCode().equals(bank.getCode())) {
                map.put("channel_code", bank.getBankCode()); //通道
                map.put("username", bank.getUsername());//商户号
                secretKey = bank.getSecretkey();
                break;
            }
        }
        map.put("amount", String.format("%.2f", balanceTable.getTransformAmount().doubleValue()));
        //⾦额 (⼩数点后取2位)
        map.put("order_number", orderNo);                               //商户订单号
        map.put("notify_url", propertyEntity.getNotifyUrl());           //异步通知URL
        map.put("return_url", propertyEntity.getReturnUrl());           //跳转URL
        map.put("client_ip", balanceSaveEntity.getIp());                //会员 IP
        map.put("real_name", balanceSaveEntity.getName());                   //实名 (可选)

        String url = getUrl(propertyEntity, map, secretKey);
        balanceTable.setFormUrl(url);
        
        return url;
    }

    /**
     * 回调处理数据
     *
     * @param callbackEntity
     * @throws ServiceException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String callback(NePayCallbackEntity callbackEntity, String payType) throws Exception {
        log.info(String.format("callback data:%s", JSON.toJSONString(callbackEntity)));
        if (200 != callbackEntity.getHttpStatusCode() && 201 != callbackEntity.getHttpStatusCode()) {
            return Constants.FAIL;
        }

        //获取配置
        NePayPropertyEntity propertyEntity = getPayProperty(payType, false, NePayPropertyEntity.class);

        //验证传输数据
        NePayCallbackEntity callDataEntity = JSON.parseObject(callbackEntity.getData(), NePayCallbackEntity.class);
        Map<String, String> map = new LinkedHashMap<>();
        String secretKey = "";
//        if (callDataEntity.getUsername().equals(propertyEntity.getAliUsername())) {
//            secretKey = propertyEntity.getAliSecretkey();
//            map.put("username", propertyEntity.getAliUsername());
//        } else if (callDataEntity.getUsername().equals(propertyEntity.getUnionUsername())) {
//            secretKey = propertyEntity.getUnionSecretkey();
//            map.put("username", propertyEntity.getUnionUsername());
//        } else {
//            return Constants.FAIL;
//        }

        for (NePayBankPropertyEntity bank : propertyEntity.getBanks()) {
            if (callDataEntity.getUsername().equals(bank.getUsername())) {
                secretKey = bank.getSecretkey();
                map.put("username", bank.getUsername());
                break;
            }
        }

        boolean flag = validate(callDataEntity, secretKey);
        if (!flag) {
            return Constants.FAIL;
        }

        int status = PayConstants.CALLBACE_PROCESSING_STATUS;
        if (4 == callDataEntity.getStatus() || 5 == callDataEntity.getStatus()) {
            status = PayConstants.CALLBACE_SUCCESS_STATUS;
        } else if (6 == callDataEntity.getStatus() || 8 == callDataEntity.getStatus()) {
            status = PayConstants.CALLBACE_FAIL_STATUS;
        }

        map.put("order_number", callDataEntity.getOrderNumber());        //商户订单号
        String sign = getSign(secretKey, map);
        map.put("sign", sign);                                            //签名

        Connection.Response response = HttpUtil.post(propertyEntity.getQueryUrl(), map);//查询订单是否和回调数据一致
        log.info(String.format("url:%s,json:%s,body:%s", propertyEntity.getQueryUrl(), JSON.toJSON(map),
                response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (requestEntity == null || (requestEntity.get("http_status_code") != null && (Integer) requestEntity.get(
                "http_status_code") != 200 && (Integer) requestEntity.get("http_status_code") != 201)) {
            log.error("Payment platform is abnormal, please try again later or contact customer service.");
            return Constants.FAIL;
        }
        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        sign = getSign(secretKey, map);
        if (!sign.equals(resultSign)) {//校验签名
            log.error("Payment platform is abnormal, please try again later or contact customer service.");
            return Constants.FAIL;
        }
        if (callDataEntity.getStatus() != (Integer) jsonData.get("status") || !callDataEntity.getOrderNumber().equals(jsonData.get("order_number").toString()) || !callDataEntity.getSystemOrderNumber().equals(jsonData.get("system_order_number").toString()) || !callDataEntity.getUsername().equals(jsonData.get("username").toString())) {
            return Constants.FAIL;
        }

        FinanceDepositCallbackUpdateEntity balanceCallbackUpdateEntity =
                getFinanceDepositCallbackUpdateEntity(callDataEntity.getOrderNumber(),
                        callDataEntity.getSystemOrderNumber(),
                        status, callbackEntity);
        BigDecimal amount = new BigDecimal(callDataEntity.getAmount());
        balanceCallbackUpdateEntity.setTransformAmount(amount);

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

    /**
     * 获取支付url
     *
     * @param balanceTable
     * @return
     * @throws ServiceException
     */
    private String getUrl(NePayPropertyEntity propertyEntity, FinanceDepositTable balanceTable,
                          FinanceDepositAddEntity balanceSaveEntity) throws ServiceException, IOException,
            PayValidatedException {
        String orderNo = balanceTable.getSerial() + "_" + balanceTable.getLogin();
        Map<String, String> map = new LinkedHashMap<>();
        String secretKey = "";

        for (NePayBankPropertyEntity bank : propertyEntity.getBanks()) {
            if (balanceSaveEntity.getBankCode().equals(bank.getCode())) {
                map.put("channel_code", bank.getBankCode()); //通道
                map.put("username", bank.getUsername());//商户号
                secretKey = bank.getSecretkey();
                break;
            }
        }
        map.put("amount", String.format("%.2f", balanceTable.getTransformAmount().doubleValue()));
        //⾦额 (⼩数点后取2位)
        map.put("order_number", orderNo);                               //商户订单号
        map.put("notify_url", propertyEntity.getNotifyUrl());           //异步通知URL
        map.put("return_url", propertyEntity.getReturnUrl());           //跳转URL
        map.put("client_ip", balanceSaveEntity.getIp());                //会员 IP
        map.put("real_name", balanceTable.getName());                   //实名 (可选)
//        String sign = getSign(secretKey, map);
//        map.put("sign", sign);                                          //签名
//
//        Connection.Response response = HttpUtil.post(propertyEntity.getBaseUrl(), map);
//        log.info(String.format("url:%s,json:%s,body:%s", propertyEntity.getBaseUrl(), JSON.toJSON(map),
//                response.body()));
//
//        JSONObject requestEntity = JSON.parseObject(response.body());
//        if (requestEntity == null || (requestEntity.get("http_status_code") != null && (Integer) requestEntity.get(
//                "http_status_code") != 200 && (Integer) requestEntity.get("http_status_code") != 201)) {
//            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact
//            customer" +
//                    " service.");
//        }
//
//        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
//        map.clear();
//        String resultSign = null;
//        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
//            if ("sign".equals(mapjson.getKey())) {
//                resultSign = String.valueOf(mapjson.getValue());
//            } else {
//                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
//                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
//                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
//                    }
//                }
//            }
//        }
//
//        sign = getSign(secretKey, map);
//        if (!sign.equals(resultSign)) {
//            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact
//            customer" +
//                    " service.");
//        }
//
//        String url = String.valueOf(jsonData.get("casher_url"));
//        log.info(String.format("支付请求,请求orderNo:%s,请求url:%s", map.get("order_number"), url));
//        return url;

        return getUrl(propertyEntity, map, secretKey);
    }


    /**
     * 获取支付url
     *
     * @param
     * @return
     * @throws ServiceException
     */
    private String getUrl(NePayPropertyEntity propertyEntity, Map<String, String> map, String secretKey) throws ServiceException, IOException,
            PayValidatedException {

        String sign = getSign(secretKey, map);
        map.put("sign", sign);                                          //签名

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

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

        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        sign = getSign(secretKey, map);
        if (!sign.equals(resultSign)) {
            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact customer" +
                    " service.");
        }

        String url = String.valueOf(jsonData.get("casher_url"));
        log.info(String.format("支付请求,请求orderNo:%s,请求url:%s", map.get("order_number"), url));
        return url;
    }

    /**
     * 验证回调参数是否被篡改
     *
     * @param callDataEntity
     * @return
     * @throws ServiceException
     */
    private boolean validate(NePayCallbackEntity callDataEntity, String secretKey) throws Exception {

        String _sign = callDataEntity.getSign();

        String sign = getSign(secretKey, callDataEntity);

        log.info(String.format("order no:%scallback result sign compare--callback sign:%s, encryption sign result:%s"
                , callDataEntity.getOrderNumber(), _sign, sign));
        return sign.equals(_sign);
    }

    /**
     * 支付请求加密sign
     *
     * @param secretKey
     * @return
     * @throws ServiceException
     */
    private String getSign(String secretKey, Map<String, String> map) {

        String signString = MapUtil.getStringSortByKey(map, false, true) + "&secret_key=" + secretKey;
        String sign = MD5Util.getMD5(signString);
        String order = map.get("order_number");
        if (Strings.isNullOrEmpty(order)) {
            log.info(String.format("ace pay response--sign string:%s,sign:%s", signString, sign));
        } else {
            log.info(String.format("orderNo:%s,sign string:%s,sign:%s", order, signString, sign));
        }

        return sign;
    }

    /**
     * 回调请求加密sign
     *
     * @param secretKey
     * @param callDataEntity
     * @return
     * @throws ServiceException
     */
    private String getSign(String secretKey, NePayCallbackEntity callDataEntity) {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("username", callDataEntity.getUsername());
        map.put("amount", callDataEntity.getAmount());
        map.put("order_number", callDataEntity.getOrderNumber());
        map.put("system_order_number", callDataEntity.getSystemOrderNumber());
        map.put("status", String.valueOf(callDataEntity.getStatus()));
        String signString = MapUtil.getStringSortByKey(map, false, true) + "&secret_key=" + secretKey;
        System.out.println(signString);
        String sign = MD5Util.getMD5(signString);

        log.info(String.format("回调结果加密处理--请求orderNo:%s,sign string:%s,sign:%s", callDataEntity.getOrderNumber(),
                signString,
                sign));

        return sign;
    }

    @Override
    public FinanceWithdrawNepayDto 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(PayConstants.NE_PAY_KEY_REMIT);

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

        FinanceWithdrawNepayDto dto = new FinanceWithdrawNepayDto();
        dto.setAmount(withdrawDto.getTransformAmount() == null ? null :
                withdrawDto.getTransformAmount().setScale(2, BigDecimal.ROUND_DOWN));
        dto.setBankCardHolderName(withdrawDto.getBankUname());
        dto.setBankCardNumber(withdrawDto.getBankCardNum());
        dto.setBankName(withdrawDto.getBankName());

        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(FinanceWithdrawNepayEntity 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());

        NePayWithdrawPropertyEntity propertyEntity = getWithdrawProperty(PayConstants.NE_PAY_KEY_REMIT,
                NePayWithdrawPropertyEntity.class);

        payout(entity, propertyEntity);

        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 null;
    }

    private void payout(FinanceWithdrawNepayEntity entity, NePayWithdrawPropertyEntity propertyEntity) throws Exception {
        Map<String, String> map = new LinkedHashMap<>();

        map.put("username", propertyEntity.getUsername());              //商户号
        map.put("amount", String.format("%.2f", entity.getAmount().doubleValue()));   //⾦额 (⼩数点后取2位)
        map.put("order_number", entity.getSerial());                    //商户订单号
        map.put("bank_card_holder_name", entity.getBankCardHolderName());
        map.put("bank_card_number", entity.getBankCardNumber());
        map.put("bank_name", entity.getBankName());
        map.put("bank_province", Strings.isNullOrEmpty(entity.getBankProvince()) ? "" : entity.getBankProvince());
        map.put("bank_city", Strings.isNullOrEmpty(entity.getBankCity()) ? "" : entity.getBankCity());
        if (entity.getWithdrawInfoType() == null || entity.getWithdrawInfoType().equals(1)) {
            map.put("notify_url", propertyEntity.getNotifyUrl());
        } else {
            map.put("notify_url", propertyEntity.getAgentNotifyUrl());
        }

        String sign = getSign(propertyEntity.getSecretkey(), map);
        map.put("sign",sign);

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

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

        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        sign = getSign(propertyEntity.getSecretkey(), map);
        if (!sign.equals(resultSign)) {
            throw new PayValidatedException("Payment platform is abnormal, please try again later or contact customer" +
                    " service.");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String withdrawCallback(Integer withdrawType, NePayCallbackEntity callbackEntity) throws Exception {
        log.info(String.format("callback data:%s", JSON.toJSONString(callbackEntity)));
        if (200 != callbackEntity.getHttpStatusCode() && 201 != callbackEntity.getHttpStatusCode()) {
            return Constants.FAIL;
        }
        if (Strings.isNullOrEmpty(callbackEntity.getSign())) {
            return Constants.FAIL;
        }
        //获取配置
        NePayWithdrawPropertyEntity payProperty = getWithdrawProperty(PayConstants.NE_PAY_KEY_REMIT,
                NePayWithdrawPropertyEntity.class);

        //验证传输数据
        NePayCallbackEntity callDataEntity = JSON.parseObject(callbackEntity.getData(), NePayCallbackEntity.class);

        boolean flag = validate(callDataEntity, payProperty.getSecretkey());
        if (!flag) {
            return Constants.FAIL;
        }

        Map<String, String> map = new LinkedHashMap<>();
        map.put("order_number", callDataEntity.getOrderNumber());        //商户订单号
        String sign = getSign(payProperty.getSecretkey(), map);
        map.put("sign", sign);                                            //签名

        Connection.Response response = HttpUtil.post(payProperty.getQueryUrl(), map);
        log.info(String.format("url:%s,json:%s,body:%s", payProperty.getQueryUrl(), JSON.toJSON(map),
                response.body()));

        JSONObject requestEntity = JSON.parseObject(response.body());
        if (requestEntity == null || (requestEntity.get("http_status_code") != null && (Integer) requestEntity.get("http_status_code") != 200 && (Integer) requestEntity.get("http_status_code") != 201)) {
            log.error("Payment platform is abnormal, please try again later or contact customer service.");
            return Constants.FAIL;
        }
        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        sign = getSign(payProperty.getSecretkey(), map);
        if (!sign.equals(resultSign)) {//校验签名
            log.error("Payment platform is abnormal, please try again later or contact customer service.");
            return Constants.FAIL;
        }
        if (callDataEntity.getStatus() != jsonData.getInteger("status") || !callDataEntity.getOrderNumber().equals(jsonData.get("order_number").toString()) || !callDataEntity.getSystemOrderNumber().equals(jsonData.get("system_order_number").toString()) || !callDataEntity.getUsername().equals(jsonData.get("username").toString())) {
            return Constants.FAIL;
        }

        FinanceWithdrawApproveChannelEntity financeWithdrawApproveChannelEntity =
                new FinanceWithdrawApproveChannelEntity();
        financeWithdrawApproveChannelEntity.setChannelSerial(callbackEntity.getSystemOrderNumber());
        if (4 == callDataEntity.getStatus() || 5 == callDataEntity.getStatus()) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_SUCCESS_STATUS);
        } else if (6 == callDataEntity.getStatus() || 8 == callDataEntity.getStatus()) {
            financeWithdrawApproveChannelEntity.setCallbackStatus(PayConstants.CALLBACE_FAIL_STATUS);
        }

        /**
         * 更新数据
         */

        if (withdrawType == null || withdrawType.equals(1)) {
            financeWithdrawService.approve(financeWithdrawApproveChannelEntity);

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

        return Constants.SUCCESS;
    }

    public static void main(String[] args) throws IOException {
        //{"username":"CWG02","amount":"289.00","order_number":"PW260318180922615803","bank_card_holder_name":"三 张","bank_card_number":"123324354534523423","bank_name":"asrsrt5hy","bank_province":"","bank_city":"","notify_url":"https://ad.44a5c8109e4.com//nepay/withdraw/callback","sign":"3d5653d7bc7022c7e111cb03569ec73f"}

        Map<String, String> map = new LinkedHashMap<>();
        map.put("username", "CWG02");              //商户号
        map.put("amount", "1000.00");   //⾦额 (⼩数点后取2位)
        map.put("order_number", "20250101215452345");                    //商户订单号
        map.put("notify_url", "/nepay/callback");           //异步通知URL
        map.put("bank_card_holder_name", "陈振渊");
        map.put("bank_card_number", "6222082008001077419");
        map.put("bank_name", "中国工商银行");
        map.put("bank_province", null);
        map.put("bank_city", null);

        /*String signString = MapUtil.getStringSortByKey(map, false, false) + "&secret_key" +
                "=DWhiyLr1PkPfeLU5WsK2wojxJ7w5sE1i";
        String sign = MD5Util.getMD5(signString);
        map.put("sign", sign); //签名

        String data = JSON.toJSONString(map);
        System.out.println("request:" + data);
        Connection.Response response = HttpUtil.post("https://api.nepaycn.com/api/v1/third-party/agency-withdraws"
                , data);

        JSONObject requestEntity = JSON.parseObject(response.body());
        System.out.println(requestEntity.toJSONString());*/
//
//        //        System.out.println("response:"+response.body());
//        String body = "{\"amount\":\"1000.00\",\"casher_url\":\"https:\\/\\/api.nepaycn" +
//                ".com\\/api\\/v1\\/cashier\\/GX2025020618562056912\",\"confirmed_at\":\"\"," +
//                "\"created_at\":\"2025-02-06T18:56:20+08:00\",\"note\":\"\",\"notify_url\":\"\\/nepay\\/callback\"," +
//                "\"order_number\":\"2025010121545211\",\"receiver_account\":\"\",\"receiver_bank_branch\":\"\"," +
//                "\"receiver_bank_name\":\"\",\"receiver_name\":\"\",\"return_url\":\"https:\\/\\/web.com\\/\"," +
//                "\"status\":11,\"system_order_number\":\"GX2025020618562056912\",\"username\":\"CWG01\"," +
//                "\"sign\":\"05f3d04ece6e7c6d446bdabb45dfaae3\"}";

        //JSONObject jsonData = JSON.parseObject(body);

        // map.put("username","CWG01");                                                            //商户号
        //map.put("order_number", "2025010121545211");                               //商户订单号

        /*map.put("username", "CWG01");
        map.put("amount", "1000.0");
        map.put("order_number", "PD20250206194420748450_1");
        map.put("system_order_number", "GX2025020619442356984");
        map.put("status", "11");

        String signString = MapUtil.getStringSortByKey(map, false,true) +
        "&secret_key=eBjZGYLbiR8nMaewrkrkCyDcGcz8mK7H";
        System.out.println(signString);
        String sign = MD5Util.getMD5(signString);
        map.put("sign", sign); //签名
        System.out.println(sign);*/
        /*String data = JSON.toJSONString(map);
        System.out.println("request:"+data);
        Connection.Response response = HttpUtil.post("https://api.nepaycn
        .com/api/v1/third-party/transaction-queries", data);

        JSONObject requestEntity = JSON.parseObject(response.body());
        System.out.println(requestEntity.toJSONString());
        JSONObject jsonData = JSON.parseObject(requestEntity.get("data").toString());

        Integer status= (Integer)jsonData.get("status");
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if(!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()){
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        String signString1 = MapUtil.getStringSortByKey(map, false,true) +
        "&secret_key=eBjZGYLbiR8nMaewrkrkCyDcGcz8mK7H";
        String sign1 = MD5Util.getMD5(signString1);
        if (!sign1.equals(resultSign)) {
            //throw new PayValidatedException("Payment platform is abnormal, please try again later or contact
            customer service.");
        }
        System.out.println(sign1+"-"+resultSign);*/

        /*System.out.println(AESUtil.decrypt(
                "XlIx3qDSLMyG4f3qIRuRc+UpwtmR80uQL5L0arq8TyK6kyrPB+HrLAiz1l0rzFyt7CKkpBJ7RymF67HttHbDvleUQJJDE2U+bK09pPHR1fxkdBJuyyPmiDG+7s+euXhDtmrq+3aKtaVxPl+KYglstwbx9C2cezgTXUPSuGvv7hH59L+ZjYAwguGM98e1g1JlrSLaNVfvX9YNKNkqPQm4i9SMCltyXkEMgvBZ59GoZK6g23JuOzx1rAv4OsC6/3g9Schnmep+WYhQlVJQG8XluMXuZRoVga605ZZ6CSYlpNw1vOmgYof1fC7oVANeijIycBhwIWe1ebrgqj8YPTtHKDC8NnKy4UMOU/haeNT8e7UuBVIYpwrmR83Xp/P1iWxkOKtS71i60cKuU5IMiqAcd+K1EqlxbyPgfDIkpHPnG8zAtMpXeImhmSqtO586jZ+1IYiQG5d8yVW0MnrKGvF8tF7flzehpCR479vh6OM804Bs9ucNNYp5vuWLkVDtUSW257Z9gdIQ1DrkJ8tJOQXM5N3w2W88hU7o9J5SIpKuK4A+s7I0mPXqIy3LqWYT6CIp1eJdhMebxN4bAU+Bj1Qt92z25w01inm+5YuRUO1RJbbntn2B0hDUOuQny0k5BczkCojEb4UWpg6tBeASKko9LfiSGQHfJz0KMNA0hNwqYBY=\n",
                "bfa5559109f94c78af615bcf00d52060"
        ));
        System.out.println(AESUtil.encrypt("{\n" +
                "\"withdrawUrl\":\"https://api.nepaycn.com/api/v1/third-party/agency-withdraws\",\n" +
                "\"queryUrl\":\"https://api.nepaycn.com/api/v1/third-party/withdraw-querie\",\n" +
                "\"notifyUrl\":\"https://ad.44a5c8109e4.com//nepay/withdraw/callback\",\n" +
                "\"agentNotifyUrl\":\"https://ad.44a5c8109e4.com//nepay/agent/withdraw/callback\",\n" +
                "\"username\":\"CWG02\",\n" +
                "\"bankCode\":\"BANK_CARD\",\n" +
                "\"secretkey\":\"DWhiyLr1PkPfeLU5WsK2wojxJ7w5sE1i\"\n" +
                "}", "bfa5559109f94c78af615bcf00d52060"));*/

        String body = "{\"data\":{\"amount\":\"1000.00\",\"bank_card_number\":\"6222082008001077419\",\"fee\":\"5.00\",\"order_number\":\"20250101215452345\",\"sign\":\"33e5b0adb77d0d691761851311b60795\",\"created_at\":\"2026-03-19T10:50:54+08:00\",\"bank_province\":\"\",\"system_order_number\":\"GX20260319105054730800\",\"notify_url\":\"/nepay/callback\",\"bank_card_holder_name\":\"陈振渊\",\"bank_name\":\"中国工商银行\",\"confirmed_at\":\"\",\"bank_city\":\"\",\"status\":11,\"username\":\"CWG02\"},\"http_status_code\":201,\"message\":\"提交成功\"}";

        JSONObject requestEntity = JSON.parseObject(body);
        JSONObject jsonData = JSONObject.parseObject(requestEntity.get("data").toString());
        map.clear();
        String resultSign = null;
        for (Map.Entry<String, Object> mapjson : jsonData.entrySet()) {
            if ("sign".equals(mapjson.getKey())) {
                resultSign = String.valueOf(mapjson.getValue());
            } else {
                if (!"0".equals(String.valueOf(mapjson.getValue()))) {
                    if (!"confirmed_at".equals(mapjson.getKey()) || null != mapjson.getValue()) {
                        map.put(mapjson.getKey(), String.valueOf(mapjson.getValue()));
                    }
                }
            }
        }

        System.out.println(resultSign);
        String signString = MapUtil.getStringSortByKey(map, false, true) + "&secret_key=DWhiyLr1PkPfeLU5WsK2wojxJ7w5sE1i";
        String sign = MD5Util.getMD5(signString);
        System.out.println(sign);

    }

}
