package com.ai.da.controller;

import com.ai.da.common.response.Response;
import com.ai.da.common.utils.DateUtil;
import com.ai.da.common.utils.RedisUtil;
import com.ai.da.common.utils.SendEmailUtil;
import com.ai.da.mapper.primary.entity.ProductCoupons;
import com.ai.da.model.dto.CreateCouponDTO;
import com.ai.da.model.dto.ProductPurchaseDTO;
import com.ai.da.model.dto.QueryCouponsPageDTO;
import com.ai.da.model.vo.CheckCouponsVO;
import com.ai.da.service.StripeService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.paypal.http.HttpResponse;
import com.paypal.payments.Refund;
import com.stripe.exception.StripeException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Api(tags = "Stripe模块")
@Slf4j
@RestController
@RequestMapping("/api/stripe")
//@ApiIgnore
public class StripeController {

    @Resource
    private StripeService stripeService;
    @Resource
    private RedisUtil redisUtil;

    @ApiOperation("创建支付链接")
    @PostMapping("/createOrder")
    public Response<String> pay(@Valid @RequestBody ProductPurchaseDTO productPurchaseDTO, HttpServletRequest request) {
        return Response.success(stripeService.pay(productPurchaseDTO, request));
    }

    @Value("${stripe.webhook.fail.reminder}")
    private String webhookReminderFlag;

    @ApiOperation("支付通知")
    @PostMapping("/trade/notify")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try{
            Boolean result =  stripeService.notify(request);
            if (result){
                response.setStatus(HttpServletResponse.SC_OK);
            }else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }catch (Exception e){
            log.error("Stripe Controller层异常捕捉, {}", e.getMessage());
            e.printStackTrace();
            String key_1 = RedisUtil.STRIPE_EXCEPTION_LOG + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_HH);
            String key_2 = key_1 + ":" + DateUtil.dateToStr(new Date(), DateUtil.YYYY_MM_DD_hh_mm_ss);
            String stackTrace = stripeService.getStackTrace(e, 10);
            redisUtil.addToString(key_2, stackTrace);
            Long size = redisUtil.getSize(key_1);
            // 给我发送邮件
            if (webhookReminderFlag.equals("1") && size == 3){
                SendEmailUtil.commonExceptionReminder("Stripe Webhook 回调", new String[]{"xupei3360@163.com"});
            }
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation("申请退款")
    @GetMapping("/trade/refund/{orderNo}/{reason}")
    public Response<HttpResponse<Refund>> refund(@PathVariable String orderNo, @PathVariable String reason) throws IOException {
        String response = stripeService.refund(null,orderNo,reason);
        if (response.equals("退款成功")){
            return Response.success();
        }else {
            return Response.fail("Request for refund failed.");
        }
    }

    @ApiOperation("获取订阅")
    @GetMapping("/getSubscription")
    public Response<List<String>> getSubscription(@RequestParam String name, @RequestParam String email) {
        try {
            return Response.success(stripeService.getSubscriptionIds(name, email));
        } catch (StripeException e) {
            throw new RuntimeException(e);
        }
    }

    @ApiOperation("取消订阅")
    @GetMapping("/cancelSubscription")
    public Response<String> cancelSubscription(@RequestParam String subscriptionId, @RequestParam(required = false) String reason) {
        stripeService.cancelSubscription(subscriptionId, reason);
        return Response.success("success");
    }

    @ApiOperation("创建推广码")
    @PostMapping("/createCoupon")
    public Response<String> createCoupon(@Valid @RequestBody CreateCouponDTO createCouponDTO){
        return Response.success(stripeService.createCoupon(createCouponDTO));
    }

    @ApiOperation("检查推广码")
    @GetMapping("/checkCoupon")
    public Response<CheckCouponsVO> checkCoupon(@RequestParam String promotionCode, @RequestParam Long price){
        return Response.success(stripeService.checkProductCoupon(promotionCode, price));
    }

    @ApiOperation("获取所有推广码")
    @PostMapping("/getAllCoupons")
    public Response<IPage<ProductCoupons>> getAllCoupons(@RequestBody QueryCouponsPageDTO queryCouponsPageDTO){
        return Response.success(stripeService.getAllCoupons(queryCouponsPageDTO));
    }

    @ApiOperation("检索优惠券")
    @GetMapping("/retrieveCoupon")
    public Response<String> retrieveCoupon(@RequestParam String couponId){
        return Response.success(stripeService.retrieveCoupon(couponId));
    }

    @ApiOperation("检索推广码")
    @GetMapping("/retrievePromotionCode")
    public Response<String> retrievePromotionCode(@RequestParam String retrievePromotionCode){
        return Response.success(stripeService.retrievePromotionCode(retrievePromotionCode));
    }

    @ApiOperation("更新推广码信息")
    @GetMapping("/updatePromCodeInfo")
    public Response<ProductCoupons> updateCouponsInfo(@RequestParam Long id, @RequestParam(required = false) String paidCommission,
                                                      @RequestParam(required = false) String cooperator,
                                                      @RequestParam(required = false) String remark,
                                                      @RequestParam(required = false) Long startTime){
        return Response.success(stripeService.updateCouponsInfo(id, paidCommission, cooperator, remark, startTime));
    }

    @ApiOperation("删除推广码")
    @GetMapping("/deletePromCode")
    public Response<String> deleteCoupon(@RequestParam Long id){
        stripeService.deleteCoupon(id);
        return Response.success("success");
    }

    /*@ApiOperation("临时 取消订阅")
    @GetMapping("/cancelSubscriptionTemp")
    public Response<String> cancelSubscriptionTemp(@RequestParam String subscriptionId) {
        stripeService.cancelSubscriptionTemp(subscriptionId);
        return Response.success("success");
    }

    @ApiOperation("创建订阅 临时")
    @GetMapping("/createSubscriptionTemp")
    public Response<String> createSubscriptionTemp(@RequestParam String name, @RequestParam String email) {
        return Response.success(stripeService.createSubscriptionTemp(name, email));
    }

    @ApiOperation("修改用户默认支付方式 临时")
    @GetMapping("/changeCustomerPayment")
    public Response<String> changeCustomerPayment(@RequestParam String name, @RequestParam String email) {
        return Response.success(stripeService.changeCustomerPayment(name, email));
    }

    @ApiOperation("临时 发送续订失败邮件")
    @GetMapping("/sendRenewalFailEmail")
    public Response<Boolean> sendRenewalFailEmail(@RequestParam String invoiceId, @RequestParam String subscriptionId, @RequestParam String orderNo) {
        return Response.success(stripeService.sendRenewalFailEmail(invoiceId, subscriptionId,orderNo));
    }

    @ApiOperation("临时 查询指定用户绑定的付款方式")
    @GetMapping("/getCustomerPaymentMethod")
    public Response<List<Map<String,String>>> getCustomerPaymentMethod(@RequestParam String name, @RequestParam String email) {
        return Response.success(stripeService.getCustomerPaymentMethod(name, email));
    }

    @ApiOperation("临时 解绑指定用户绑定的所有付款方式")
    @GetMapping("/detachCustomerAllPaymentMethod")
    public Response<String> detachCustomerAllPaymentMethod(@RequestParam String name, @RequestParam String email) {
        return Response.success(stripeService.detachCustomerAllPaymentMethod(name, email));
    }*/


}
