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

import com.ruoyi.common.domain.vo.LocalDateDecimalVO;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.pay.PayApi;
import com.ruoyi.common.pay.syb.enums.SybTrxStatus;
import com.ruoyi.common.pay.syb.service.SybPayService;
import com.ruoyi.common.pay.tm.TmPayService;
import com.ruoyi.common.pay.tm.enums.TmRefundStatus;
import com.ruoyi.common.pay.tm.vo.RefundInfo;
import com.ruoyi.common.pay.wx.service.WxPayService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.SnowFlakeUtil;
import com.ruoyi.ss.payBill.service.PayBillService;
import com.ruoyi.ss.refund.domain.Refund;
import com.ruoyi.ss.refund.domain.RefundQuery;
import com.ruoyi.ss.refund.domain.RefundVO;
import com.ruoyi.ss.refund.domain.enums.RefundStatus;
import com.ruoyi.ss.refund.mapper.RefundMapper;
import com.ruoyi.ss.refund.service.RefundService;
import com.ruoyi.ss.channel.domain.enums.ChannelEnum;
import com.ruoyi.ss.transactionBill.service.TransactionBillService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

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

/**
 * 退款订单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-09
 */
@Service
public class RefundServiceImpl implements RefundService
{
    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private TransactionBillService transactionBillService;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private PayBillService payBillService;

    @Autowired
    private SybPayService sybPayService;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @Autowired
    private TmPayService tmPayService;


    /**
     * 查询退款订单
     *
     * @param refundId 退款订单主键
     * @return 退款订单
     */
    @Override
    public RefundVO selectRefundByRefundId(Long refundId)
    {
        return refundMapper.selectRefundByRefundId(refundId);
    }

    /**
     * 查询退款订单列表
     *
     * @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.setRefundNo(String.valueOf(SnowFlakeUtil.newId()));
        return refundMapper.insertRefund(refund);
    }

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

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

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

    @Override
    public RefundVO selectRefundByRefundNo(String refundNo) {
        RefundQuery query = new RefundQuery();
        query.setRefundNo(refundNo);
        return this.selectOne(query);
    }

    @Override
    public RefundVO selectOne(RefundQuery query) {
        return refundMapper.selectOne(query);
    }

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

        RefundVO refund = this.selectRefundByRefundNo(refundNo);
        ServiceUtil.assertion(refund == null, "退款订单不存在");

        transactionTemplate.execute(status -> {
            // 退款订单修改状态
            Refund refundData = new Refund();
            refundData.setStatus(RefundStatus.REFUND_SUCCESS.getStatus());
            RefundQuery refundQuery = new RefundQuery();
            refundQuery.setRefundId(refund.getRefundId());
            refundQuery.setStatus(RefundStatus.REFUNDING.getStatus());
            int updateRefund = this.updateByQuery(refundData, refundQuery);
            ServiceUtil.assertion(updateRefund != 1, "修改退款订单状态失败");

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

            return updateRefund;
        });

    }

    @Override
    public int updateByQuery(Refund data, RefundQuery query) {
        if (query == null) {
            return 0;
        }
        return refundMapper.updateByQuery(data, query);
    }

    @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.selectRefundByRefundNo(refund.getRefundNo());

            // 发起退款
            PayApi payApi = ChannelEnum.getPayApi(refund.getChannelId());
            if (payApi == null) {
                throw new ServiceException("当前支付方式不支持退款");
            }
            payApi.refund(vo);

            // 判断是否同步通知，若是则直接处理支付成功
            ChannelEnum channelEnum = ChannelEnum.parse(refund.getChannelId());
            if (channelEnum != null && channelEnum.getIsRefundSync() != null && channelEnum.getIsRefundSync()) {
                scheduledExecutorService.schedule(() -> {
                    this.handleRefundSuccess(refund.getRefundNo());
                }, 10, TimeUnit.SECONDS);
            }

            return insertRefund;
        });

        return result == null ? 0 : result;
    }

    @Override
    public int refreshResult(Long refundId) {
        RefundVO refund = selectRefundByRefundId(refundId);
        return this.refreshResult(refund);
    }

    @Override
    public int refreshResult(RefundVO refund) {
        if (refund == null) {
            return 0;
        }
        if (!RefundStatus.REFUNDING.getStatus().equals(refund.getStatus())) {
            return 0;
        }

        // 通联微信
//        if (ChannelEnum.TL_WX.getType().equals(refund.getChannelId())) {
//            Map<String, String> params = sybPayService.queryByOutTradeNo(refund.getRefundNo());
//            String trxStatus = params.get("trxstatus");
//            if (SybTrxStatus.isSuccess(trxStatus)) {
//                // 退款成功
//                scheduledExecutorService.schedule(() -> {
//                    this.handleRefundSuccess(refund.getRefundNo());
//                }, 0, TimeUnit.SECONDS);
//            }
//        }

        return 1;
    }

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