package com.wzj.soopin.transaction.controller;

import com.wzj.soopin.transaction.domain.entity.*;
import com.wzj.soopin.transaction.service.impl.WxAuthService;
import com.wzj.soopin.transaction.service.impl.WxPayService;
import com.wzj.soopin.transaction.wechat.WechatPayConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.mapstruct.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "商家转账")
@RestController
@Slf4j
@RequestMapping("/api/transfer")
@RequiredArgsConstructor
public class WxPayController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private WxAuthService wxAuthService;

    /**
     *商家转账 - 发起转账
     * @return
     */
    @Operation(summary = "发起转账")
    @PostMapping("/wechat")
    public InitiateBatchTransferResponseNew payRequest() {
        InitiateBatchTransferResponseNew response = null;
        InitiateBatchTransferRequestNew request = new InitiateBatchTransferRequestNew();
        WechatPayConfig wechatPayConfig = new WechatPayConfig();
        //商户AppID
        request.setAppid("wxebcdaea31881caab");
        //商户单号
        request.setOutBillNo("test123456789");
        //转账金额(分为单位，测试：0.1元)，单笔转账额度最低为0.1元
        request.setTransferAmount(10);
        //转账场景ID
        //    /** 转账场景ID 说明：该批次转账使用的转账场景，如不填写则使用商家的默认场景，如无默认场景可为空，可前往“商家转账到零钱-前往功能”中申请。 如：1001-现金营销 */
        request.setTransferSceneId("1005");
        //用户的openId
        request.setOpenid("ox3uhvt23jLpQT37CriWHotQlxpw");
        //收款用户姓名
        request.setUserName("");
        //转账备注
        //【转账备注】 单条转账备注（微信用户会收到该备注），UTF8编码，最多允许32个字符
        request.setTransferRemark("奖金");
        //转账场景报备信息 佣金的固定类型
        List<TransferSceneReportInfoNew> transferDetailList = new ArrayList<>();
        TransferSceneReportInfoNew transferSceneReportInfoNew = new TransferSceneReportInfoNew();
        transferSceneReportInfoNew.setInfoType("岗位类型");
        transferSceneReportInfoNew.setInfoContent("代理人");
        transferDetailList.add(transferSceneReportInfoNew);
        TransferSceneReportInfoNew transferSceneReportInfoNew1 = new TransferSceneReportInfoNew();
        transferSceneReportInfoNew1.setInfoType("报酬说明");
        transferSceneReportInfoNew1.setInfoContent("手续费");
        transferDetailList.add(transferSceneReportInfoNew1);
        request.setTransferSceneReportInfos(transferDetailList);
        //异步接收微信支付结果通知的回调地址，通知url必须为公网可访问的URL，必须为HTTPS，不能携带参数
        // 注意：此处需要填写公网可访问的服务器地址，不能携带任何参数
        request.setNotifyUrl("https://2e879e23cc0e.ngrok-free.app/api/transfer/callback");
        try{
            response = wxPayService.initiateBatchTransferNew(request);
        }catch (ServiceException e){
            e.printStackTrace();
        }
        return response;
    }
    /**
     * 微信商户零线转账 - 回调通知
     * @Context注解  把HTTP请求上下文对象注入进来，HttpServletRequest、HttpServletResponse、UriInfo 等
     * @return
     */
    @Operation(summary = "微信商户零线转账 - 回调通知")
    @PostMapping("/callback")
    @Log(title = "微信商户零线转账 - 回调通知", businessType = BusinessType.INSERT)
    public ResponseEntity<Map<String, String>> wxPayCallback(@Context HttpServletRequest request) {
        Map<String,String> errMap = new HashMap<>();
        try {
            log.info("微信商户零线转账 - 回调通知 /wxpay/callback");
            Map<String, String> resMap = (Map<String, String>) wxPayService.wxPaySuccessCallback(request);
            return new ResponseEntity<>(resMap, HttpStatus.OK);
        } catch (ServiceException e){
            errMap.put("code", "FAIL");
            errMap.put("message", e.getMessage());
            return new ResponseEntity<>(errMap, HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            log.error("微信商户零线转账 - 回调通知 /wxpay/callback：异常！", e);
            errMap.put("code", "FAIL");
            errMap.put("message", "服务器内部错误");
            return new ResponseEntity<>(errMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 商家转账 - 商户单号查询转账单
     * @param outBillNo 商户系统内部的商家单号
     * @return 转账单详细信息
     */
    @Operation(summary = "查询转账单")
    @GetMapping("/detail")
    public ResponseEntity<TransferDetailEntityNew> getTransferDetailByOutNoNew(@RequestParam String outBillNo) {
        TransferDetailEntityNew response = null;
        try {
            response = wxPayService.getTransferDetailByOutNoNew(outBillNo);
        } catch (Exception e) {
            log.error("查询转账单时发生异常: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * 商家转账 - 撤销转账
     *
     * @param outBillNo 商户系统内部的商家单号
     * @return
     */
    @Operation(summary = "撤销转账")
    @PostMapping("/cancel")
    @Parameters({
        @Parameter(name = "outBillNo", description = "商户系统内部的商家单号", required = true, in = ParameterIn.QUERY)
    })
    public ResponseEntity<TransferBillEntity> cancelBatchTransfer(@RequestParam String outBillNo) {
        TransferBillEntity response = null;
        try {
            response = wxPayService.cancelBatchTransfer(outBillNo);
        } catch (SecurityException e) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        } catch (ServiceException e) {
            log.error("撤销转账时发生ServiceException: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            log.error("撤销转账时发生未知异常: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        // 确保返回的数据是正确的 JSON 解析结果
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    /**
     * 获取用户的openid
     *
     * @param code 授权码
     * @return 包含openid的响应对象
     */
    @Operation(summary = "获取用户openid")
    @GetMapping("/openid")
    @Parameters({
        @Parameter(name = "code", description = "授权码", required = true, in = ParameterIn.QUERY)
    })
    public ResponseEntity<WxAuthResponse> getOpenId(@RequestParam String code) {
        try {
            WxAuthResponse response = wxAuthService.getOpenIdByCode(code);
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            log.error("获取openid时发生异常: {}", e.getMessage());
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }





}
