package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.dto.g.GPayDto;
import com.crm.pay.entity.callback.GPayCallbackEntity;
import com.crm.pay.service.GPayService;
import com.crm.rely.backend.core.constant.Constants;
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.crm.rely.backend.core.exception.PayValidatedException;
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.io.IOException;
import java.math.BigDecimal;

/**
 * @description:
 * @author: houn
 * @create: 2021-05-31 14:58
 */
@RestController
@RequestMapping("/g")
public class GPayController extends BasePayCloseFunctionController {

    @Autowired
    private GPayService service;

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


        return payCall(login, amount, 0, entity, request, PayConstants.G_PAY_ZFB_ZYM_HH_KEY, infoEntity);
    }

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


        return payCall(login, amount, activity, entity, request, PayConstants.G_PAY_ZFB_ZYM_HH_KEY, infoEntity);
    }

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


        return payCall(login, amount, 0, entity, request, PayConstants.G_PAY_USDT_KEY, infoEntity);
    }

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


        return payCall(login, amount, activity, entity, request, PayConstants.G_PAY_USDT_KEY, infoEntity);
    }


    private BaseResultDto payCall(Long login,
                                  BigDecimal amount,
                                  int activity,
                                  FinanceDepositParameterEntity entity,
                                  HttpServletRequest request, String payType,
                                  CustomInfoEntity infoEntity) throws Exception {

//        if (service.verificationLimitQuantity(infoEntity.getId(),payType)) {
//            return BaseResultDto.error("the_quota_has_been_used_up_today_please_try_again_tomorrow");
//        }
        validated(login, amount);

        FinanceDepositAddEntity financeDepositSaveEntity = getFinanceDepositSaveEntity(login, amount,
                payType,
                payType, activity, entity, request);

        financeDepositSaveEntity.setIp(request.getHeader("CLIENT_IP"));
        String url = service.pay(financeDepositSaveEntity);
        PayDto payDto = new PayDto(1, url);
        return BaseResultDto.success(payDto);
    }

    /**
     * 异步回调
     *
     * @param request 用于获取回调数据
     * @return 返回成功给第三方系统
     * @throws Exception
     */
    @RequestMapping("/callback")
    public GPayDto callback(HttpServletRequest request) throws Exception {
        GPayCallbackEntity callbackEntity = getGPayCallbackEntity(request);
        String payType = null;
        if (callbackEntity == null || Strings.isNullOrEmpty(callbackEntity.getCompanyOrderNum())) {

            return new GPayDto("", "", 0, "body is null");
        }
        if (callbackEntity != null && callbackEntity.getDepositMode().equals("56")) {
            payType = PayConstants.G_PAY_USDT_KEY;
        }
        if (callbackEntity != null && callbackEntity.getDepositMode().equals("38")) {
            payType = PayConstants.G_PAY_ZFB_ZYM_HH_KEY;
        }
        GPayDto dto;
        try {
            dto = service.callback(callbackEntity, payType);
        } catch (Exception e) {
            dto = new GPayDto(callbackEntity.getCompanyOrderNum(), callbackEntity.getMownecumOrderNum(), 0,
                    Constants.SYSTEM_ERROR);
        }

        return dto;
    }


    /**
     * 同步页面 成功
     *
     * @param response 用于重定向页面
     * @throws IOException
     */
    @GetMapping(value = "/pickup")
    public void pickup(HttpServletResponse response) throws Exception, PayValidatedException {

        sendRedirect(response);
    }

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

        sendRedirect(response);
    }

    private GPayCallbackEntity getGPayCallbackEntity(HttpServletRequest request) {
        GPayCallbackEntity callbackEntity = new GPayCallbackEntity();
        callbackEntity.setPayTime(request.getParameter("pay_time"));
        callbackEntity.setBankId(request.getParameter("bank_id"));
        callbackEntity.setAmount(request.getParameter("amount"));
        callbackEntity.setCompanyOrderNum(request.getParameter("company_order_num"));
        callbackEntity.setMownecumOrderNum(request.getParameter("mownecum_order_num"));
        callbackEntity.setPayCardNum(request.getParameter("pay_card_num"));
        callbackEntity.setPayCardName(request.getParameter("pay_card_name"));
        callbackEntity.setChannel(request.getParameter("channel"));
        callbackEntity.setArea(request.getParameter("area"));
        callbackEntity.setFee(request.getParameter("fee"));
        callbackEntity.setTransactionCharge(request.getParameter("transaction_charge"));
        callbackEntity.setKey(request.getParameter("key"));
        callbackEntity.setDepositMode(request.getParameter("deposit_mode"));
        callbackEntity.setBaseInfo(request.getParameter("base_info"));
        callbackEntity.setOperatingTime(request.getParameter("operating_time"));

        return callbackEntity;
    }
}
