package com.crm.pay.controller.pay;

import com.alibaba.fastjson.JSON;
import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.entity.callback.korapay.checkout.KoraCheckoutCallbackEntity;
import com.crm.pay.service.KorapayCheckoutService;
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 lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * @description:
 * @author: houn
 * @create: 2023-05-12 14:58
 */
@Log4j
@RestController
@RequestMapping("/korapay/checkout")
public class KorapayCheckoutController extends BasePayCloseFunctionController {

    @Autowired
    private KorapayCheckoutService service;

    /**
     * 支付
     *
     * @param login  入金账号
     * @param amount 入金金额
     * @return 错误信息
     * @throws Exception
     */
    @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);
    }

    @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);
    }


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

        FinanceDepositAddEntity financeDepositSaveEntity = getFinanceDepositSaveEntity(login, amount,
                bankCode,
                PayConstants.KORAPAY_CHECKOUT_PAY, activity, entity, request);

        String url = service.pay(financeDepositSaveEntity);

        PayDto payDto = new PayDto(1, url);
        return BaseResultDto.success(payDto);
    }

    /**
     * 异步回调
     *
     * @param wehbookData 用于获取回调数据
     * @return 返回成功给第三方系统
     * @throws Exception
     */
//    @RequestMapping("/callback")
//    public void callback(@RequestBody String webhookData, HttpServletRequest request,
//                         HttpServletResponse response) throws Exception {
//
//        String signature = request.getHeader("x-korapay-signature");
//        if (Strings.isNullOrEmpty(webhookData) || Strings.isNullOrEmpty(signature)) {
//            response.setStatus(400);
//            throw new ServiceException(Constants.FAIL);
//        }
//        try {
//
//            KoraCheckoutCallbackEntity callbackEntity = JSON.parseObject(webhookData, KoraCheckoutCallbackEntity
//            .class);
//            if (callbackEntity == null || Strings.isNullOrEmpty(callbackEntity.getEvent()) || callbackEntity
//            .getData() == null) {
//                throw new ServiceException(Constants.FAIL);
//            }
//
//            boolean flag = service.validate(webhookData, signature);
//
//            if (!flag) {
//                throw new ServiceException(Constants.FAIL);
//            }
//
//            service.callback(callbackEntity);
//        } catch (ServiceException e) {
//            log.error(e.getMessage());
//            response.setStatus(400);
//            throw new ServiceException(e.getMessage());
//        }
//    }

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

        sendRedirect(response);
    }

    @RequestMapping(value = "/pickup/{serial}")
    public void pickupSerial(@PathVariable("serial") String serial, HttpServletResponse response) throws Exception,
            PayValidatedException {
        log.info("pickupSerial");
        service.callbackSerial(serial);
        sendRedirect(response);
    }

    @RequestMapping(value = "/callback/{serial}")
    public void callbackSerial(@PathVariable("serial") String serial,
                               @RequestBody KoraCheckoutCallbackEntity callbackEntity,
                               HttpServletResponse response) throws Exception, PayValidatedException {
        log.info("callbackSerial:" + JSON.toJSONString(callbackEntity));
        service.callbackSerial(serial);
        sendRedirect(response);
    }

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

        sendRedirect(response);
    }
}
