package com.ruoyi.bst.refund.service.impl;

import com.ruoyi.bst.app.domain.AppVO;
import com.ruoyi.bst.app.service.AppService;
import com.ruoyi.bst.channel.domain.ChannelVO;
import com.ruoyi.bst.channel.domain.enums.ChannelApiType;
import com.ruoyi.bst.channel.service.ChannelConverter;
import com.ruoyi.bst.channel.service.ChannelService;
import com.ruoyi.bst.pay.service.PayService;
import com.ruoyi.bst.refund.domain.Refund;
import com.ruoyi.bst.refund.domain.RefundQuery;
import com.ruoyi.bst.refund.domain.RefundVO;
import com.ruoyi.bst.refund.domain.enums.RefundStatus;
import com.ruoyi.bst.refund.mapper.RefundMapper;
import com.ruoyi.bst.refund.service.RefundService;
import com.ruoyi.common.domain.vo.LocalDateDecimalVO;
import com.ruoyi.common.domain.vo.LongDecimalVO;
import com.ruoyi.common.pay.PayApi;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.SnowFlakeUtil;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 退款Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-28
 */
@Service
public class RefundServiceImpl implements RefundService
{
    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private ChannelService channelService;

    @Autowired
    private AppService appService;

    @Autowired
    private ChannelConverter channelConverter;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private PayService payService;

    /**
     * 查询退款
     *
     * @param id 退款主键
     * @return 退款
     */
    @Override
    public RefundVO selectRefundById(Long id)
    {
        return refundMapper.selectRefundById(id);
    }

    /**
     * 查询退款列表
     *
     * @param refund 退款
     * @return 退款
     */
    @Override
    public List<RefundVO> selectRefundList(RefundQuery refund)
    {
        return refundMapper.selectRefundList(refund);
    }

    /**
     * 新增退款
     *
     * @param refund 退款
     * @return 结果
     */
    @Override
    public int insertRefund(Refund refund)
    {
        refund.setCreateTime(DateUtils.getNowDate());
        refund.setNo(String.valueOf(SnowFlakeUtil.newId()));
        return refundMapper.insertRefund(refund);
    }

    /**
     * 修改退款
     *
     * @param refund 退款
     * @return 结果
     */
    @Override
    public int updateRefund(Refund refund)
    {
        return refundMapper.updateRefund(refund);
    }

    /**
     * 批量删除退款
     *
     * @param ids 需要删除的退款主键
     * @return 结果
     */
    @Override
    public int deleteRefundByIds(Long[] ids)
    {
        return refundMapper.deleteRefundByIds(ids);
    }

    /**
     * 删除退款信息
     *
     * @param id 退款主键
     * @return 结果
     */
    @Override
    public int deleteRefundById(Long id)
    {
        return refundMapper.deleteRefundById(id);
    }


    @Override
    public int createRefund(Refund refund) {
        Integer result = transactionTemplate.execute(status -> {
            refund.setStatus(RefundStatus.REFUNDING.getStatus());
            int insertRefund = this.insertRefund(refund);
            ServiceUtil.assertion(insertRefund != 1, "创建退款订单失败");

            RefundVO vo = this.selectRefundByNo(refund.getNo());

            // 获取渠道信息
            ChannelVO channel = channelService.selectChannelByChannelId(vo.getChannelId());
            ServiceUtil.assertion(channel == null, "ID为%s的支付渠道不存在", vo.getChannelId());

            // 获取API
            ChannelApiType channelApiType = ChannelApiType.parse(channel.getApiType());
            ServiceUtil.assertion(channelApiType == null, "当前退款API开发中，请稍后重试");
            PayApi payApi = ChannelApiType.getPayApi(channelApiType);
            ServiceUtil.assertion(payApi == null, "当前退款API开发中，请稍后重试");

            // 获取APP信息
            AppVO app = appService.selectAppById(vo.getAppId());
            ServiceUtil.assertion(app == null, "ID为%s的APP不存在", vo.getAppId());

            // TODO 正式环境取消注释 调用API退款
            payApi.refund(vo, channelConverter.toConfig(channel, app));

            //TODO 5秒后支付成功，测试，正式环境需删除
//            scheduledExecutorService.schedule(() -> {
//                this.handleRefundSuccess(refund.getNo());
//            }, 5, TimeUnit.SECONDS);

            // TODO 正式环境取消注释 判断是否同步通知，若是则直接处理支付成功
            if (channelApiType.getIsRefundSync() != null && channelApiType.getIsRefundSync()) {
                scheduledExecutorService.schedule(() -> {
                    this.handleRefundSuccess(refund.getNo());
                }, 10, TimeUnit.SECONDS);
            }

            return insertRefund;
        });

        return result == null ? 0 : result;
    }

    private RefundVO selectRefundByNo(String no) {
        if (StringUtils.isBlank(no)) {
            return null;
        }

        RefundQuery query = new RefundQuery();
        query.setEqNo(no);
        return refundMapper.selectRefundList(query).get(0);
    }

    @Override
    public void handleRefundSuccess(String no) {
        ServiceUtil.assertion(StringUtils.isBlank(no), "退款订单编号不允许为空");

        RefundVO refund = this.selectRefundByNo(no);
        ServiceUtil.assertion(refund == null, "编号为%s的退款订单不存在", no);

        transactionTemplate.execute(status -> {
            // 退款订单修改状态
            Refund data = new Refund();
            data.setStatus(RefundStatus.SUCCESS.getStatus());
            RefundQuery query = new RefundQuery();
            query.setId(refund.getId());
            query.setStatus(RefundStatus.REFUNDING.getStatus());
            int rows = refundMapper.updateByQuery(data, query);
            ServiceUtil.assertion(rows != 1, "修改退款订单状态失败");


            // 处理支付单
            RefundVO newRefund = this.selectRefundByNo(no);
            int handleResult = payService.handleRefundSuccess(newRefund);
            ServiceUtil.assertion(handleResult != 1, "修改支付单状态失败");

            return rows;
        });

    }

    @Override
    public List<LocalDateDecimalVO> selectRefundAmount(RefundQuery refundQuery) {
        return refundMapper.selectRefundAmount(refundQuery);
    }

    @Override
    public List<LongDecimalVO> selectSumOfRefundAmountGroupByStoreId(RefundQuery refundQuery) {
        return refundMapper.selectSumOfRefundAmountGroupByStoreId(refundQuery);
    }
}
