package com.bizzan.bitrade.service;

import com.bizzan.bitrade.entity.Coin;
import com.spark.bipay.constant.CoinType;
import com.spark.bipay.entity.Address;
import com.spark.bipay.entity.SupportCoin;
import com.spark.bipay.entity.Trade;
import com.spark.bipay.entity.Transaction;
import com.spark.bipay.http.ResponseMessage;
import com.spark.bipay.http.client.BiPayClient;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class BiPayService {
	@Autowired
	private CoinService coinService;
    @Autowired
    private BiPayClient biPayClient;
    @Value("${server.host}")
    private String host;
    @Value("#{'${bipay.supported-coins}'.split(',')}")
    private List<String> supportedCoins;

    public boolean isSupportedCoin(String coinName) {
        return supportedCoins != null && supportedCoins.contains(coinName);
    }

    /**
     * 创建币种地址
     *
     * @param coinType
     * @param alias
     * @param walletId
     * @returns
     */
    public Address createCoinAddress(CoinType coinType, String alias, String walletId) {
        String callbackUrl = host + "/bipay/notify";
        log.info("[Udun-BiPayService] 步骤1-创建地址 入参 coinType={}, alias={}, walletId={}, callbackUrl={}", coinType, alias, walletId, callbackUrl);
        try {
            ResponseMessage<Address> resp = biPayClient.createCoinAddress(coinType.getCode(), callbackUrl, alias, walletId);
            log.info("[Udun-BiPayService] 步骤2-创建地址 结果 code={}, message={}, address={}", resp.getCode(), resp.getMessage(), resp.getData() != null ? resp.getData().getAddress() : null);
            return resp.getData();
        } catch (Exception e) {
            log.error("[Udun-BiPayService] 创建地址异常", e);
        }
        return null;
    }

    /**
     * 提币
     * @param orderId
     * @param amount
     * @param coinType
     * @param subCoinType
     * @param address
     * @param memo
     * @return
     */
    public ResponseMessage<String> transfer(String orderId, BigDecimal amount, CoinType coinType, String subCoinType, String address, String memo) {
        String callbackUrl = host + "/bipay/notify";
        log.info("[Udun-BiPayService] 步骤1-提币 入参 orderId={}, amount={}, coinType={}, subCoinType={}, address={}, memo={}", orderId, amount, coinType, subCoinType, address, memo);
        try {
            ResponseMessage<String> resp = biPayClient.transfer(orderId, amount, coinType.getCode(), subCoinType, address, callbackUrl, memo);
            log.info("[Udun-BiPayService] 步骤2-提币 结果 code={}, message={}, data={}", resp.getCode(), resp.getMessage(), resp.getData());
            return resp;
        } catch (Exception e) {
            log.error("[Udun-BiPayService] 提币异常", e);
        }
        return ResponseMessage.error("提交转币失败");
    }

    /**
     * 代付
     * @param orderId
     * @param amount
     * @param coinType
     * @param subCoinType
     * @param address
     * @param memo
     * @return
     */
    public ResponseMessage<String> autoTransfer(String orderId, BigDecimal amount, CoinType coinType, String subCoinType, String address, String memo) {
        String callbackUrl = host + "/bipay/notify";
        log.info("[Udun-BiPayService] 步骤1-代付 入参 orderId={}, amount={}, coinType={}, subCoinType={}, address={}, memo={}", orderId, amount, coinType, subCoinType, address, memo);
        try {
            ResponseMessage<String> resp = biPayClient.autoTransfer(orderId, amount, coinType.getCode(), subCoinType, address, callbackUrl, memo);
            log.info("[Udun-BiPayService] 步骤2-代付 结果 code={}, message={}, data={}", resp.getCode(), resp.getMessage(), resp.getData());
            return resp;
        } catch (Exception e) {
            log.error("[Udun-BiPayService] 代付异常", e);
        }
        return ResponseMessage.error("提交转币失败");
    }

    public List<Transaction> queryTransaction() throws Exception {
        log.info("[Udun-BiPayService] 步骤1-查询交易 入参(空)");
        List<Transaction> list = biPayClient.queryTransaction("", "", "", null, "", "", "");
        log.info("[Udun-BiPayService] 步骤2-查询交易 结果 count={}", list != null ? list.size() : 0);
        return list;
    }

    /**
     * 校验地址合法性
     * @param mainCoinType
     * @param address
     * @return
     * @throws Exception
     */
    public boolean checkAddress(String mainCoinType, String address) throws Exception {
        log.info("[Udun-BiPayService] 校验地址 入参 mainCoinType={}, address={}", mainCoinType, address);
        boolean result = biPayClient.checkAddress(mainCoinType, address);
        log.info("[Udun-BiPayService] 校验地址 结果 isInternal={}", result);
        return result;
    }

    /**
     * 查询支持币种
     * @param showBalance
     * @return
     * @throws Exception
     */
    public List<SupportCoin> getSupportCoin(Boolean showBalance) throws Exception {
        log.info("[Udun-BiPayService] 获取支持币种 入参 showBalance={}", showBalance);
        List<SupportCoin> list = biPayClient.getSupportCoin(showBalance);
        log.info("[Udun-BiPayService] 获取支持币种 结果 count={}", list != null ? list.size() : 0);
        return list;
    }

    public Coin convert2Coin(Trade trade) {
    	String coinName = "";
    	if(trade.getMainCoinType().equals("60") && trade.getCoinType().equals("60"))
    		coinName = "ETH";
    	else if(trade.getMainCoinType().equals("60") && trade.getCoinType().equals("0xdac17f958d2ee523a2206206994597c13d831ec7"))
    		coinName = "EUSDT";
    	else if(trade.getMainCoinType().equals("195") && trade.getCoinType().equals("195"))
    		coinName = "TRX";
    	else if(trade.getMainCoinType().equals("195") && trade.getCoinType().equals("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"))
    		coinName = "TUSDT";
    	else if(trade.getMainCoinType().equals("2510"))
    		coinName = "USDT-BEP20";
    	
    	if(!coinName.equals(""))
    		return coinService.findByUnit(coinName);
    	else
    		return null;
    }
}
