package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.entity.b2bin.B2BinPayCurrencyEntity;
import com.crm.pay.entity.b2bin.B2BinPaySignEntity;
import com.crm.pay.entity.b2bin.B2BinPayTransactionEntity;
import com.crm.pay.entity.callback.B2BinCallbackEntity;
import com.crm.pay.service.B2BinService;
import com.crm.rely.backend.model.constant.PayConstants;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.pay.dto.PayDto;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoEntity;
import com.crm.rely.backend.model.entity.finance.deposit.FinanceDepositAddEntity;
import com.crm.pay.entity.FinanceDepositParameterEntity;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;


@RestController
@RequestMapping("/b2bin")
public class B2BinPayController extends BasePayCloseFunctionController {

    @Autowired
    private B2BinService service;


    /**
     * 支付
     *
     * @param login  入金账号
     * @param amount 入金金额
     * @param amount 入金金额
     * @return 错误信息
     * @throws Exception
     */
    @RequestMapping("/pay/{login}/{amount}/{bankCode}/{activity}")
    public BaseResultDto pay(@PathVariable("login") Long login, @PathVariable("amount") BigDecimal amount,
                             @PathVariable("bankCode") String bankCode,
                             @PathVariable("activity") int activity,
                             @RequestBody FinanceDepositParameterEntity entity,
                             CustomInfoEntity infoEntity, HttpServletRequest request) throws Exception {

        return payCall(login, amount, bankCode, activity, entity, infoEntity, request);
    }

    @RequestMapping("/pay/{login}/{amount}/{bankCode}")
    public BaseResultDto pay(@PathVariable("login") Long login,
                             @PathVariable("amount") BigDecimal amount,
                             @PathVariable("bankCode") String bankCode,
                             @RequestBody FinanceDepositParameterEntity entity,
                             CustomInfoEntity infoEntity, HttpServletRequest request) throws Exception {

        return payCall(login, amount, bankCode, 0, entity, infoEntity, request);
    }

    private BaseResultDto payCall(Long login,
                                  BigDecimal amount,
                                  String bankCode,
                                  int activity,
                                  FinanceDepositParameterEntity entity,
                             CustomInfoEntity infoEntity, HttpServletRequest request) throws Exception {
        validated(login, amount);
        FinanceDepositAddEntity balanceSaveEntity = getFinanceDepositSaveEntity(login, amount,
                bankCode, PayConstants.B2BIN_PAY_TYPE_KEY, activity, entity, request);
        String url = service.pay(balanceSaveEntity);
        PayDto payDto = new PayDto(1, url);
        return BaseResultDto.success(payDto);
    }

    /**
     * 异步回调
     *
     * @param request 获取回调数据
     * @return 返回成功给第三方系统
     * @throws Exception
     */
    @RequestMapping(value = "/callback", produces = "text/html")
    public String callback(HttpServletRequest request) throws Exception {

        B2BinCallbackEntity callback = getCallback(request);
//        String content = "{\"actual_amount\":\"293933397000\",\"address\":\"1Bn1N3nj7Rzp1gfEjfRT6B6Ei2Fzpk5HY3\",\"amount\":\"293933397000\",\"callback_url\":\"https://pay.cwgsvg.com/b2bin/callback\",\"created\":\"2020-11-02
//        12:05:13\",\"error_url\":\"https://my.cwgsvg.com/b2bin/pickup\",\"expired\":\"\",\"id\":\"509556\",\"pow\":\"8\",\"sign\":{\"hash\":\"$2y$10$XbGTb5AmEH48/n/FlqpjBOWrf7qTIZKSqFu81/h/xYr7X5CjleLRi\",\"time\":\"Mon
//        Nov 02 2020 17:46:34 GMT+0000\"},\"status\":\"2\",\"success_url\":\"https://my.cwgsvg.com/b2bin/pickup\",\"tracking_id\":\"PD202011030420241757_20002\",\"transactions\":[{\"amount\":\"293933397000\",\"bill_id\":\"509556\",\"created\":\"2020-11-02
//        12:21:27\",\"currency\":{\"alpha\":\"USDT\",\"iso\":2005},\"id\":\"297858\",\"pow\":\"8\",\"status\":\"1\",\"transaction\":\"45a44e8f13554289b1e9ce64180d6bf6458349910fd4f261b45b306917eaf99b\",\"transfer_amount\":\"290994063030\",\"transfer_currency\":{\"alpha\":\"USDT\",\"iso\":2005},\"transfer_pow\":\"8\",\"transfer_rate\":\"100000000\",\"transfer_rate_pow\":\"8\",\"type\":\"0\"}],\"url\":\"https://gw.b2binpay.com/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJCMkJDcnlwdG9QYXkiLCJzdWIiOjUwOTU1NiwiaWF0IjoxNjA0MzE4NzEzfQ.QGEEv4BCB0KSPKrPy9DdnPqV5O6luO_vnU3mcWJB7CU\"}";
//        B2BinCallbackEntity callback = JSON.parseObject(content, B2BinCallbackEntity.class);
        service.callback(callback);

        return PayConstants.B2BIN_PAY_SUCCESS_RESULT;
    }


    @GetMapping(value = "/pickup")
    public void pickup(HttpServletResponse response) throws Exception {
        sendRedirect(response);
    }

    @GetMapping(value = "/error")
    public void error(HttpServletResponse response) throws Exception {

        sendRedirect(response);
    }

    /**
     * 在form-data中获取回调数据
     *
     * @param request 用于获取form-data中的数据
     * @return 返回回调数据构建的实体
     */
    private B2BinCallbackEntity getCallback(HttpServletRequest request) {

        B2BinCallbackEntity callbackEntity = new B2BinCallbackEntity();

        callbackEntity.setId(request.getParameter("id"));
        callbackEntity.setUrl(request.getParameter("url"));
        callbackEntity.setAddress(request.getParameter("address"));
        callbackEntity.setCreated(request.getParameter("created"));
        callbackEntity.setExpired(request.getParameter("expired"));
        callbackEntity.setStatus(request.getParameter("status"));
        callbackEntity.setTracking_id(request.getParameter("tracking_id"));
        callbackEntity.setCallback_url(request.getParameter("callback_url"));
        callbackEntity.setSuccess_url(request.getParameter("success_url"));
        callbackEntity.setError_url(request.getParameter("error_url"));
        callbackEntity.setAmount(request.getParameter("amount"));
        callbackEntity.setActual_amount(request.getParameter("actual_amount"));
        callbackEntity.setPow(request.getParameter("pow"));
        callbackEntity.setMessage(request.getParameter("message"));
        List<B2BinPayTransactionEntity> transactions = new LinkedList<>();
        int num = 0;
        while (true) {

            String id = request.getParameter("transactions[" + num + "][id]");
            if (Strings.isNullOrEmpty(id)) {
                break;
            }
            B2BinPayTransactionEntity b2BinPayTransactionEntity = new B2BinPayTransactionEntity();

            b2BinPayTransactionEntity.setId(id);
            b2BinPayTransactionEntity.setBill_id(request.getParameter("transactions[" + num + "][bill_id]"));
            b2BinPayTransactionEntity.setCreated(request.getParameter("transactions[" + num + "][created]"));
            b2BinPayTransactionEntity.setAmount(request.getParameter("transactions[" + num + "][amount]"));
            b2BinPayTransactionEntity.setPow(request.getParameter("transactions[" + num + "][pow]"));
            b2BinPayTransactionEntity.setStatus(request.getParameter("transactions[" + num + "][status]"));
            b2BinPayTransactionEntity.setTransaction(request.getParameter("transactions[" + num + "][transaction]"));
            b2BinPayTransactionEntity.setType(request.getParameter("transactions[" + num + "][type]"));
            b2BinPayTransactionEntity.setTransfer_amount(request.getParameter("transactions[" + num +
                    "][transfer_amount]"));
            b2BinPayTransactionEntity.setTransfer_pow(request.getParameter("transactions[" + num + "][transfer_pow]"));
            b2BinPayTransactionEntity.setTransfer_rate(request.getParameter("transactions[" + num + "][transfer_rate" +
                    "]"));
            b2BinPayTransactionEntity.setTransfer_rate_pow(request.getParameter("transactions[" + num +
                    "][transfer_rate_pow]"));

            B2BinPayCurrencyEntity b2BinPayCurrencyEntity = new B2BinPayCurrencyEntity();
            b2BinPayCurrencyEntity.setAlpha(request.getParameter("transactions[" + num + "][currency][alpha]"));
            b2BinPayCurrencyEntity.setIso(Integer.parseInt(request.getParameter("transactions[" + num + "][currency" +
                    "][iso]")));
            b2BinPayTransactionEntity.setCurrency(b2BinPayCurrencyEntity);

            B2BinPayCurrencyEntity transfer_currency = new B2BinPayCurrencyEntity();
            transfer_currency.setAlpha(request.getParameter("transactions[" + num + "][transfer_currency][alpha]"));
            transfer_currency.setIso(Integer.parseInt(request.getParameter("transactions[" + num +
                    "][transfer_currency][iso]")));
            b2BinPayTransactionEntity.setTransfer_currency(transfer_currency);
            transactions.add(b2BinPayTransactionEntity);
            num++;
        }

        callbackEntity.setTransactions(transactions);

        B2BinPaySignEntity b2BinPaySignEntity = new B2BinPaySignEntity();
        b2BinPaySignEntity.setTime(request.getParameter("sign[time]"));
        b2BinPaySignEntity.setHash(request.getParameter("sign[hash]"));
        callbackEntity.setSign(b2BinPaySignEntity);
        B2BinPayCurrencyEntity b2BinPayCurrencyEntity = new B2BinPayCurrencyEntity();
        b2BinPayCurrencyEntity.setAlpha(request.getParameter("currency[alpha]"));
        b2BinPayCurrencyEntity.setIso(Integer.parseInt(request.getParameter("currency[iso]")));
        callbackEntity.setSign(b2BinPaySignEntity);

        return callbackEntity;
    }
}
