package com.izouma.nineth.web;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.service.WxPayService;
import com.izouma.nineth.config.AlipayProperties;
import com.izouma.nineth.config.GeneralProperties;
import com.izouma.nineth.domain.UserFundAccount;
import com.izouma.nineth.dto.pay.UniformNotifyRequest;
import com.izouma.nineth.dto.pay.UniformNotifyResult;
import com.izouma.nineth.enums.InviteeQualificationsType;
import com.izouma.nineth.service.*;
import com.izouma.nineth.service.pay.UniformPayUtil;
import com.izouma.nineth.utils.HttpServletUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Controller
@RequestMapping("/notify")
@AllArgsConstructor
public class OrderNotifyController {

    private final AlipayProperties              alipayProperties;
    private final OrderService                  orderService;
    private final WxPayService                  wxPayService;
    private final AssetService                  assetService;
    private final GiftOrderService              giftOrderService;
    private final RedisTemplate<String, Object> redisTemplate;

    private final GeneralProperties             generalProperties;
    private final PaymentInfoService paymentInfoService;

    private final UniformPayUtil uniformPayUtil;

    private RechargeOrderService rechargeOrderService;

    private WithdrawApplyService withdrawApplyService;

    private UserFundAccountService userFundAccountService;

    private UserFundAccountNotifyAdapter userFundAccountNotifyAdapter;

    private UserFundAccountForLianlianpayService userFundAccountForLianlianpayService;

    private ActivityInviteService activityInviteService;
    /**
     *
     * 统一的支付通知
     * @param orderNo
     * @return
     */
    @PostMapping("/uniform/payNotify/{orderNo}")
    @ResponseBody
    public Object uniformOrderNotify(@PathVariable String orderNo,
                                     @RequestBody String requestBody, HttpServletRequest request){
        log.info("统一支付通知,orderNo:{}, 接收数据：{} ", orderNo, requestBody);

        try {
            Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);

            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = uniformPayUtil.notify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("统一支付通知error, orderNo：" +  orderNo, e);
        }

        return "";
    }

    /**
     * 统一支付退款结果通知
     * @param orderNo
     * @param requestBody
     * @return
     */
    @PostMapping("/uniform/refundNotify/{orderNo}")
    @ResponseBody
    public Object uniformRefundNotify(@PathVariable String orderNo,
                                      @RequestBody(required = false) String requestBody, HttpServletRequest request){
        log.info("统一退款通知: orderNo:{}, 接收数据：{} ", orderNo, requestBody);

        try {
            Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);

            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = uniformPayUtil.refundNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("统一退款通知error,orderNo：" +  orderNo, e);
        }

        return "";
    }

    /**
     * 统一支付转账结果通知
     * @param tradeNo
     * @param requestBody
     * @return
     */
    @PostMapping("/uniform/transferNotify/{tradeNo}")
    @ResponseBody
    public Object uniformTransferNotify(@PathVariable String tradeNo,
                                        @RequestBody(required = false) String requestBody, HttpServletRequest request){
        log.info("统一转账通知: tradeNo:{}, 接收数据：{} ", tradeNo, requestBody);

        try {
            Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);
            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(tradeNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = uniformPayUtil.transferNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("统一转账通知error,tradeNo：" +  tradeNo, e);
        }

        return "";
    }


    /**
     * 续费结果通知
     * @return
     */
    @PostMapping("/renewNotify/{orderNo}")
    @ResponseBody
    public String renewNotify(@PathVariable String orderNo, @RequestBody String requestBody, HttpServletRequest request){
        log.info("收到续费结果通知, orderNo:{}, 接收数据：{}" , orderNo,  requestBody);
        try{
            Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);
            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = userFundAccountNotifyAdapter.renewNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("续费通知error,orderNo：" +  orderNo, e);
        }
        return "";
    }


    /**
     * 充值结果通知
     * @return
     */
    @PostMapping("/rechargeNotify/{orderNo}")
    @ResponseBody
    public String rechargeNotify(@PathVariable String orderNo, @RequestBody String requestBody, HttpServletRequest request){
        log.info("收到充值结果通知, orderNo:{}, 接收数据：{}" , orderNo,  requestBody);
        try{
            Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);
            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = userFundAccountNotifyAdapter.rechargeNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("充值通知error,orderNo：" +  orderNo, e);
        }
        return "";
    }


    /**
     * 提现结果通知
     * @return
     */
    @PostMapping("/withdrawNotify/{orderNo}")
    @ResponseBody
    public String withdrawNotify(@PathVariable String orderNo, @RequestBody String requestBody, HttpServletRequest request){
        log.info("收到提现结果通知, orderNo: {}, 接收数据：{}" , orderNo,  requestBody);
        try {
            Map<String, String> requestHeaders = HttpServletUtil.getHeaders(request);
            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = userFundAccountNotifyAdapter.withdrawNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("提现通知error,orderNo：" +  orderNo, e);
        }

        return "";
    }

    /**
     * 解绑卡结果通知
     * @return
     */
    @PostMapping("/bindCardNotify/{orderNo}")
    @ResponseBody
    public String unbindCardNotify(@PathVariable String orderNo, @RequestBody String requestBody, HttpServletRequest request){
        log.info("收到解绑卡结果通知, orderNo: {}, 接收数据：{}" , orderNo,  requestBody);
        try {
            Map<String, String> requestHeaders = HttpServletUtil.getHeaders(request);
            UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                    .orderNo(orderNo).requestBody(requestBody)
                    .requestHeaders(requestHeaders)
                    .build();
            UniformNotifyResult result = userFundAccountNotifyAdapter.bindCardNotify(notifyRequest);
            return result.getContent();
        } catch (Exception e) {
            log.error("解绑卡通知error,orderNo：" +  orderNo, e);
        }

        return "";
    }

    /**
     * 连连账户注册结果通知
     * @return
     */
    @PostMapping("/lianlianAccountNotify/{orderNo}")
    @ResponseBody
    public String lianlianAccountNotify(@PathVariable String orderNo, @RequestBody String requestBody,
                                        HttpServletRequest request){
        log.info("收到连连付注册结果通知, orderNo: {}, 接收数据：{}" , orderNo,  requestBody);
        Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);

        UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                .orderNo(orderNo).requestBody(requestBody)
                .requestHeaders(requestHeaders)
                .build();
        try{
            UserFundAccount lianlianAccount = userFundAccountForLianlianpayService.registerResultNotify(notifyRequest);
            userFundAccountForLianlianpayService.clearBalanceCache(lianlianAccount.getUserId());
            try {
                activityInviteService.risingStar(lianlianAccount.getUserId(), null, InviteeQualificationsType.BINDING_THE_PURSE);
            }catch (Exception e){
                log.error("邀请error,orderNo：" +  orderNo, e);
            }
            return "Success";
        } catch (Exception e) {
            log.error("注册通知error,orderNo：" +  orderNo, e);
        }

        return "";
    }

    /**
     * 连连账户销户结果通知
     * @return
     */
    @PostMapping("/lianlianAccountCancel")
    @ResponseBody
    public String lianlianAccountCancel(@RequestBody String requestBody,
                                        HttpServletRequest request){
        log.info("收到连连付销户结果通知, 接收数据：{}" ,  requestBody);
        Map<String,String> requestHeaders = HttpServletUtil.getHeaders(request);

        UniformNotifyRequest notifyRequest = UniformNotifyRequest.builder()
                .requestBody(requestBody)
                .requestHeaders(requestHeaders)
                .build();
        try{
            UserFundAccount lianlianAccount = userFundAccountForLianlianpayService.cancelResultNotify(notifyRequest);
            userFundAccountForLianlianpayService.clearBalanceCache(lianlianAccount.getUserId());
            return "Success";
        } catch (Exception e) {
            log.error("销户通知error", e);
        }

        return "";
    }



}
