package com.crm.pay.controller.pay;

import com.alibaba.fastjson.JSON;
import com.crm.pay.controller.base.BasePayCloseFunctionController;
import com.crm.pay.entity.callback.stic.SticPayCallbackEntity;
import com.crm.pay.entity.callback.stic.SticPayParametersCallbackEntity;
import com.crm.pay.service.SticPayService;
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;

/**
 * @description:
 * @author: houn
 * @create: 2020-12-12 14:58
 */
@RestController
@RequestMapping("/stic")
public class SticPayController extends BasePayCloseFunctionController {

    @Autowired
    private SticPayService service;

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


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

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


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


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

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

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

    /**
     * 异步回调
     *
     * @param callback 用于获取回调数据
     * @return 返回成功给第三方系统
     * @throws Exception
     */
    @RequestMapping(value = "/callback", produces = "text/html")
    public String callback(
            String callback,
            HttpServletResponse response) throws Exception {
        String result;


        if (Strings.isNullOrEmpty(callback)) {
            result = PayConstants.STIC_FAIL_RESULT;
        } else {
            SticPayCallbackEntity callbackEntity = getCallbackEntity(callback);

            if (!(callbackEntity.getCode() != null && callbackEntity.getCode().equals(0) && "Success".equals(callbackEntity.getMessage()))) {
                service.callback(callbackEntity);
            }

            result = PayConstants.STIC_SUCCESS_RESULT;
        }

        sendRedirect(response);

        return result;
    }


    /**
     * 同步页面 成功
     *
     * @param response 用于重定向页面
     * @throws IOException
     */
    @GetMapping(value = "/pickup")
    public void pickup(String callback, HttpServletResponse response) throws Exception, PayValidatedException {
        if (!Strings.isNullOrEmpty(callback)) {
            SticPayCallbackEntity callbackEntity = getCallbackEntity(callback);
            if ((callbackEntity.getCode() != null && !callbackEntity.getCode().equals(0) && !"Success".equals(callbackEntity.getMessage()))) {
                service.callback(callbackEntity);
            }
        }

        sendRedirect(response);
    }

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

        sendRedirect(response);
    }

    private SticPayCallbackEntity getCallbackEntity(String callback) {
        SticPayCallbackEntity callbackEntity = JSON.parseObject(callback, SticPayCallbackEntity.class);
        SticPayParametersCallbackEntity sticPayParametersCallbackEntity =
                JSON.parseObject(callbackEntity.getParameters(), SticPayParametersCallbackEntity.class);
        callbackEntity.setPayParametersCallbackEntity(sticPayParametersCallbackEntity);

        return callbackEntity;
    }
}
