package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayController;
import com.crm.pay.entity.FinanceDepositParameterEntity;
import com.crm.pay.service.XPayService;
import com.crm.rely.backend.core.constant.Constants;
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.web.bind.annotation.*;

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

@RestController
@RequestMapping("/xpay")
public class XPayController extends BasePayController {

    @Autowired
    private XPayService service;

    @RequestMapping("/pay")
    public BaseResultDto pay(
            @RequestBody FinanceDepositParameterEntity entity,
            CustomInfoEntity infoEntity, HttpServletRequest request) throws Exception {


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

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

        FinanceDepositAddEntity balanceSaveEntity = getFinanceDepositSaveEntity(login, amount,
                PayConstants.XPAY_PAY_TYPE, infoEntity);
        String url = service.pay(balanceSaveEntity);

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

    /**
     * 异步回调
     *
     * @param callbackEntity
     * @return 返回成功给第三方系统
     * @throws Exception
     */
    @PostMapping("/callback")
    public BaseResultDto callback(@RequestBody Map<String, String> 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);
    }
}
