package com.liquidnet.service.platform.controller.refund;

import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dto.param.RefundCallbackParam;
import com.liquidnet.service.platform.service.refund.OrderRefundsCallbackServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 退款回掉
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-06-11 6:10 下午
 */
@Api(tags = "前端-refundCallBack")
@RestController
@RequestMapping("refund")
public class OrderRefundCallbackController {

    @Autowired
    private OrderRefundsCallbackServiceImpl orderRefundsCallbackServiceImpl;

    @PostMapping("callback")
    @ApiOperation("退款回调")
    public String refundCallback(RefundCallbackParam refundCallbackParam) {
        String result = orderRefundsCallbackServiceImpl.refundCallback(refundCallbackParam);
        return result;
    }

    @PostMapping("automaticRefund")
    @ApiOperation("用户自动退款")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "from", required = true, dataType = "String", name = "orderRefundsId", value = "orderRefundsId", example = "0")
    })
    public ResponseDto<String> automaticRefund(@RequestParam("orderRefundsId") @NotBlank(message = "退款id不能为空") String orderRefundsId) {
        //延迟5秒执行
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(() -> {
            orderRefundsCallbackServiceImpl.automaticRefund(orderRefundsId);
        }, 5, TimeUnit.SECONDS);
        return ResponseDto.success("success");
    }

    @GetMapping(value = "failRefund")
    @ApiOperation(value = "退款失败定时处理")
    public ResponseDto<Boolean> performanceSubscribePush() {
        try {
            orderRefundsCallbackServiceImpl.failRefund();
            return ResponseDto.success(true);
        } catch (Exception e) {
            return ResponseDto.success(false);
        }
    }

    @GetMapping("alipayActiveCallback")
    @ApiOperation("支付宝主动查询退款结果")
    public ResponseDto<String> alipayActiveCallback() {
        return orderRefundsCallbackServiceImpl.alipayActiveCallback();
    }

    @GetMapping("overtimeRefund")
    @ApiOperation("超时支付自动退款")
    public ResponseDto<String> overtimeRefund() {
        return orderRefundsCallbackServiceImpl.overtimeRefund();
    }
}
