package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.dto.korapay.KorapayDto;
import com.crm.pay.entity.korapay.KorapayAvsEntity;
import com.crm.pay.entity.korapay.KorapayOtpEntity;
import com.crm.pay.entity.korapay.KorapayPhoneEntity;
import com.crm.pay.entity.korapay.KorapayPinEntity;
import com.crm.pay.service.KorapayService;
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.crm.rely.backend.core.exception.ServiceException;
import com.google.common.base.Strings;
import lombok.extern.log4j.Log4j;
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: 2023-05-12 14:58
 */
@Log4j
@RestController
@RequestMapping("/korapay")
public class KorapayController extends BasePayCloseFunctionController {

    @Autowired
    private KorapayService service;

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


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

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


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


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

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

        KorapayDto requestPayDataDto = service.pay(financeDepositSaveEntity);
        PayDto payDto = getPay(requestPayDataDto);

        return BaseResultDto.success(payDto);
    }

    /**
     * 异步回调
     *
     * @param wehbookData 用于获取回调数据
     * @return 返回成功给第三方系统
     * @throws Exception
     */
    @RequestMapping("/callback")
    public void callback(@RequestBody String wehbookData, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {

        String signature = request.getHeader("x-korapay-signature");
        if (Strings.isNullOrEmpty(wehbookData) || Strings.isNullOrEmpty(signature)) {
            response.setStatus(400);
            throw new ServiceException(Constants.FAIL);
        }
        try {
            service.callback(wehbookData, signature);
        } catch (ServiceException e) {
            log.error(e.getMessage());
            response.setStatus(400);
            throw new ServiceException(e.getMessage());
        }
    }

    @RequestMapping("/pin/{serial}")
    public BaseResultDto pin(@PathVariable("serial") String serial, @RequestBody KorapayPinEntity entity) throws Exception {
        entity.setSerial(serial);
        KorapayDto requestPayDataDto = service.pin(entity);
        PayDto payDto = getPay(requestPayDataDto);
        return BaseResultDto.success(payDto);
    }

    @RequestMapping("/otp/{serial}")
    public BaseResultDto otp(@PathVariable("serial") String serial, @RequestBody KorapayOtpEntity entity) throws Exception {
        entity.setSerial(serial);
        KorapayDto requestPayDataDto = service.otp(entity);
        PayDto payDto = getPay(requestPayDataDto);
        return BaseResultDto.success(payDto);
    }

    @RequestMapping("/avs/{serial}")
    public BaseResultDto avs(@PathVariable("serial") String serial, @RequestBody KorapayAvsEntity entity) throws Exception {
        entity.setSerial(serial);
        KorapayDto requestPayDataDto = service.avs(entity);
        PayDto payDto = getPay(requestPayDataDto);
        return BaseResultDto.success(payDto);
    }

    @RequestMapping("/phone/{serial}")
    public BaseResultDto phone(@PathVariable("serial") String serial, @RequestBody KorapayPhoneEntity entity) throws Exception {
        entity.setSerial(serial);

        KorapayDto requestPayDataDto = service.phone(entity);
        PayDto payDto = getPay(requestPayDataDto);
        return BaseResultDto.success(payDto);
    }

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

        sendRedirect(response);
    }

    @GetMapping(value = "/callback/{serial}")
    public void callbackSerial(@PathVariable("serial") String serial,
                               HttpServletResponse response) throws Exception, PayValidatedException {

        service.callbackSerial(serial);
        sendRedirect(response);
    }

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

        sendRedirect(response);
    }

    private PayDto getPay(KorapayDto requestPayDataDto) {
        PayDto payDto;
        if (PayConstants.KORAPAY_PROCESSING_STATUS.equals(requestPayDataDto.getStatus())) {
            switch (requestPayDataDto.getAuthModel()) {
                case PayConstants.KORAPAY_PAY_PIN:
                    payDto = new PayDto(3, "/korapay/pin/" + requestPayDataDto.getSerial());
                    break;
                case PayConstants.KORAPAY_PAY_OTP:
                    payDto = new PayDto(4, "/korapay/otp/" + requestPayDataDto.getSerial());
                    break;
                case PayConstants.KORAPAY_PAY_3DS:
                    payDto = new PayDto(5, requestPayDataDto.getRedirectUrl());
                    break;
                case PayConstants.KORAPAY_PAY_AVS:
                    payDto = new PayDto(6, "/korapay/avs/" + requestPayDataDto.getSerial());
                    break;
                case PayConstants.KORAPAY_PAY_PHONE:
                    payDto = new PayDto(7, "/korapay/phone/" + requestPayDataDto.getSerial());
                    break;
                default:
                    payDto = new PayDto(8, "/korapay/pickup");
                    break;
            }
        } else {
            payDto = new PayDto(8, "/korapay/pickup");
        }
        return payDto;
    }
}
