package com.crm.pay.controller.pay;

import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.service.PraxisService;
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.google.common.base.Strings;
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.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: houn
 * @create: 2024-05-24 14:58
 */
@RestController
@RequestMapping("/praxis")
public class PraxisController extends BasePayCloseFunctionController {

    @Autowired
    private PraxisService service;

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

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

    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.PRAXIS_PAY_KEY, activity, entity, request);

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

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

        String sign = request.getHeader("Gt-Authentication");
        if (Strings.isNullOrEmpty(sign)) {
            Map<String, Object> mapResult = new HashMap<>(4);

            mapResult.put("timestamp", new Date().getTime() / 1000);
            mapResult.put("status", 1);
            mapResult.put("version", "1.3");
            mapResult.put("description", "fail");
            response.setStatus(400);
            return mapResult;
        }
        callbackEntity.put("sign", sign);

        Map<String, Object> result = service.callback(callbackEntity);
        if (result.get("status").toString().equals("1")) {
            response.setStatus(400);
        } else {
            response.setStatus(200);
        }
        return result;
    }


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

        sendRedirect(response);
    }

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

        sendRedirect(response);
    }
}
