package com.tashow.cloud.pay.controller.admin.notify;

import cn.hutool.core.collection.CollUtil;
import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.pojo.PageResult;
import com.tashow.cloud.pay.controller.admin.notify.vo.PayNotifyTaskDetailRespVO;
import com.tashow.cloud.pay.controller.admin.notify.vo.PayNotifyTaskPageReqVO;
import com.tashow.cloud.pay.controller.admin.notify.vo.PayNotifyTaskRespVO;
import com.tashow.cloud.pay.convert.notify.PayNotifyTaskConvert;
import com.tashow.cloud.pay.dal.dataobject.app.PayAppDO;
import com.tashow.cloud.pay.dal.dataobject.notify.PayNotifyLogDO;
import com.tashow.cloud.pay.dal.dataobject.notify.PayNotifyTaskDO;
import com.tashow.cloud.pay.service.app.PayAppService;
import com.tashow.cloud.pay.service.channel.PayChannelService;
import com.tashow.cloud.pay.service.notify.PayNotifyService;
import com.tashow.cloud.pay.service.order.PayOrderService;
import com.tashow.cloud.pay.service.refund.PayRefundService;
import com.tashow.cloud.pay.service.transfer.PayTransferService;
import com.tashow.cloud.sdk.payment.client.PayClient;
import com.tashow.cloud.sdk.payment.dto.order.PayOrderRespDTO;
import com.tashow.cloud.sdk.payment.dto.refund.PayRefundRespDTO;
import com.tashow.cloud.sdk.payment.dto.transfer.PayTransferRespDTO;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static com.tashow.cloud.common.exception.util.ServiceExceptionUtil.exception;
import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.common.util.collection.CollectionUtils.convertList;
import static com.tashow.cloud.payapi.enums.ErrorCodeConstants.CHANNEL_NOT_FOUND;


// 管理后台 - 回调通知
@RestController
@RequestMapping("/pay/notify")
@Validated
@Slf4j
public class PayNotifyController {

    @Resource
    private PayOrderService orderService;
    @Resource
    private PayRefundService refundService;
    @Resource
    private PayTransferService payTransferService;
    @Resource
    private PayNotifyService notifyService;
    @Resource
    private PayAppService appService;
    @Resource
    private PayChannelService channelService;

    @PostMapping(value = "/order/{channelId}")
    // 支付渠道的统一【支付】回调
    @PermitAll
    public String notifyOrder(@PathVariable("channelId") Long channelId,
                              @RequestParam(required = false) Map<String, String> params,
                              @RequestBody(required = false) String body) {
        log.info("[notifyOrder][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyOrder][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }

        // 2. 解析通知数据
        PayOrderRespDTO notify = payClient.parseOrderNotify(params, body);
        orderService.notifyOrder(channelId, notify);
        return "success";
    }

    @PostMapping(value = "/refund/{channelId}")
    // 支付渠道的统一【退款】回调
    @PermitAll
    public String notifyRefund(@PathVariable("channelId") Long channelId,
                               @RequestParam(required = false) Map<String, String> params,
                               @RequestBody(required = false) String body) {
        log.info("[notifyRefund][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyRefund][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }

        // 2. 解析通知数据
        PayRefundRespDTO notify = payClient.parseRefundNotify(params, body);
        refundService.notifyRefund(channelId, notify);
        return "success";
    }

    /**
     * 支付渠道的统一【转账】回调
     * @param channelId
     * @param params
     * @param body
     * @return
     */
    @PostMapping(value = "/transfer/{channelId}")
    @PermitAll
    public String notifyTransfer(@PathVariable("channelId") Long channelId,
                                 @RequestParam(required = false) Map<String, String> params,
                                 @RequestBody(required = false) String body) {
        log.info("[notifyTransfer][channelId({}) 回调数据({}/{})]", channelId, params, body);
        // 1. 校验支付渠道是否存在
        PayClient payClient = channelService.getPayClient(channelId);
        if (payClient == null) {
            log.error("[notifyTransfer][渠道编号({}) 找不到对应的支付客户端]", channelId);
            throw exception(CHANNEL_NOT_FOUND);
        }

        // 2. 解析通知数据
        PayTransferRespDTO notify = payClient.parseTransferNotify(params, body);
        payTransferService.notifyTransfer(channelId, notify);
        return "success";
    }

    /**
     * 获得回调通知的明细
     * @param id 编号
     * @return
     */
    @GetMapping("/get-detail")
    @PreAuthorize("@ss.hasPermission('pay:notify:query')")
    public CommonResult<PayNotifyTaskDetailRespVO> getNotifyTaskDetail(@RequestParam("id") Long id) {
        PayNotifyTaskDO task = notifyService.getNotifyTask(id);
        if (task == null) {
            return success(null);
        }
        // 拼接返回
        PayAppDO app = appService.getApp(task.getAppId());
        List<PayNotifyLogDO> logs = notifyService.getNotifyLogList(id);
        return success(PayNotifyTaskConvert.INSTANCE.convert(task, app, logs));
    }

    /**
     * 获得回调通知分页
     * @param pageVO
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('pay:notify:query')")
    public CommonResult<PageResult<PayNotifyTaskRespVO>> getNotifyTaskPage(@Valid PayNotifyTaskPageReqVO pageVO) {
        PageResult<PayNotifyTaskDO> pageResult = notifyService.getNotifyTaskPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        // 拼接返回
        Map<Long, PayAppDO> appMap = appService.getAppMap(convertList(pageResult.getList(), PayNotifyTaskDO::getAppId));
        return success(PayNotifyTaskConvert.INSTANCE.convertPage(pageResult, appMap));
    }

}
