package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayController;
import com.crm.pay.dto.PayDto;
import com.crm.pay.entity.FinanceDepositParameterEntity;
import com.crm.pay.entity.callback.UenjoyCallbackEntity;
import com.crm.pay.entity.qr.QrCodeAddEntity;
import com.crm.pay.service.UenjoyService;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.RequestSinglePointLimiter;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.model.constant.PayConstants;
import com.crm.rely.backend.model.entity.custom.info.CustomInfoEntity;
import com.crm.rely.backend.model.entity.finance.deposit.FinanceDepositAddEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @program: cwg-my-base
 * @description:
 * @author: houn
 * @create: 2021-09-08 18:58
 */
@RestController
@RequestMapping("/uenjoy")
public class UenjoyController extends BasePayController {

    @Autowired
    private UenjoyService service;

    /**
     * 支付
     *
     * @return 错误信息
     * @throws Exception
     */
    @RequestMapping("/pay")
    @RequestSinglePointLimiter
    public BaseResultDto pay(@RequestBody @Validated FinanceDepositParameterEntity entity,
                             CustomInfoEntity infoEntity) throws Exception {

        return payCall(entity.getLogin(), entity.getAmount(), infoEntity);
    }

    private BaseResultDto payCall(Long login,
                                  BigDecimal amount,
                                  CustomInfoEntity infoEntity) throws Exception {

        FinanceDepositAddEntity balanceSaveEntity = getFinanceDepositSaveEntity(login, amount, PayConstants.UENJOY_PAY_KEY, infoEntity);

        String url = service.pay(balanceSaveEntity);

        return BaseResultDto.success(Constants.SUCCESS,url);
    }

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

        service.callback(callbackEntity);

        return new BaseResultDto(0, "SUCCESS");
    }

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

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

        sendRedirect(response);
    }
}
