package com.crm.pay.controller.pay;

import com.alibaba.fastjson.JSON;
import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.dto.ozow.OowWebhookDto;
import com.crm.pay.entity.callback.ozow.OzowCallbackEntity;
import com.crm.pay.entity.callback.ozow.OzowPayoutCallbackEntity;
import com.crm.pay.entity.callback.ozow.OzowPayoutWebhookEntity;
import com.crm.pay.service.OzowService;
import com.crm.rely.backend.core.constant.FeignClientAnnotation;
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.pay.entity.finance.withdraw.automatic.FinanceWithdrawInfoEntity;
import com.crm.pay.entity.finance.withdraw.automatic.FinanceWithdrawOzowEntity;
import com.crm.rely.backend.core.exception.PayValidatedException;
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: 2024-10-31 14:58
 */
@Log4j
@RestController
@RequestMapping("/ozow")
public class OzowController extends BasePayCloseFunctionController {

    private final static String ACCESS_TOKEN = "39565f54200b66fa6158b4113f7a14a1";
    @Autowired
    private OzowService 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.OZOW_PAY_TYPE, activity, entity, request);

        String url = service.pay(financeDepositSaveEntity);
        PayDto payDto = new PayDto(1, url);
        return BaseResultDto.success(payDto);
    }

    @RequestMapping("/withdraw/info")
    @FeignClientAnnotation
    public BaseResultDto withdrawInfo(@RequestBody FinanceWithdrawInfoEntity entity) throws Exception {
        return BaseResultDto.success(service.withdrawInfo(entity));
    }

    @RequestMapping("/withdraw")
    @FeignClientAnnotation
    public BaseResultDto withdraw(@RequestBody FinanceWithdrawOzowEntity entity) throws Exception {

        service.withdraw(entity);
        return BaseResultDto.success();
    }

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

        service.callback(callbackEntity);
    }

    @PostMapping("/payout/callback")
    public void withdrawCallback(@RequestBody String callbackString) throws Exception {
        OzowPayoutCallbackEntity callbackEntity = JSON.parseObject(callbackString, OzowPayoutCallbackEntity.class);
        log.info("Ozow withdrawCallback:" + callbackString);

        if (callbackEntity == null || Strings.isNullOrEmpty(callbackEntity.getPayoutId())) {
            return;
        }

        service.withdrawCallback(1, callbackEntity);
    }

    @PostMapping("/agent/payout/callback")
    public void agentWithdrawCallback(@RequestBody String callbackString) throws Exception {
        OzowPayoutCallbackEntity callbackEntity = JSON.parseObject(callbackString, OzowPayoutCallbackEntity.class);
        log.info("Ozow withdrawCallback:" + callbackString);

        if (callbackEntity == null || Strings.isNullOrEmpty(callbackEntity.getPayoutId())) {
            return;
        }
        service.withdrawCallback(2, callbackEntity);
    }

    @RequestMapping("/webhook")
    public OowWebhookDto webhook(@RequestBody OzowPayoutWebhookEntity callbackEntity, HttpServletRequest request) throws Exception {
        String accessToken = request.getHeader("AccessToken");

        log.info("Ozow accessToken:" + accessToken);
        log.info("Ozow accessToken:" + ACCESS_TOKEN.equals(accessToken));
/**
 * {
 *   "PayoutId": "00000000-0000-0000-0000-000000000000",
 *   "IsVerified": true,
 *   "AccountNumberDecryptionKey": "C@OQN8oW9I8DSuKS$jfd",
 *   "Reason": ""
 * }
 */
        String aesKey = service.webhook(callbackEntity);

        OowWebhookDto dto = new OowWebhookDto();
        if (Strings.isNullOrEmpty(aesKey)) {
            dto.setVerified(false);
            dto.setAccountNumberDecryptionKey(null);
        } else {
            dto.setVerified(true);
            dto.setAccountNumberDecryptionKey(aesKey);
        }
        dto.setReason(null);
        dto.setPayoutId(callbackEntity.getPayoutId());

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