package org.dromara.pay.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.pay.core.PayStrategy;
import org.dromara.pay.core.PayStrategyFactory;
import org.dromara.pay.domain.PayChannel;
import org.dromara.pay.domain.PayOrder;
import org.dromara.pay.domain.PayRefund;
import org.dromara.pay.domain.bo.PayRefundBo;
import org.dromara.pay.domain.vo.PayRefundVo;
import org.dromara.pay.enums.PayOrderStatusEnum;
import org.dromara.pay.mapper.PayChannelMapper;
import org.dromara.pay.mapper.PayOrderMapper;
import org.dromara.pay.mapper.PayRefundMapper;
import org.dromara.pay.service.PayRefundService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 退款订单Service业务层处理
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PayRefundServiceImpl implements PayRefundService {

    private final PayRefundMapper baseMapper;
    private final PayOrderMapper payOrderMapper;
    private final PayChannelMapper payChannelMapper;
    private final PayStrategyFactory payStrategyFactory;

    /**
     * 查询退款订单
     */
    @Override
    public PayRefundVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询退款订单列表
     */
    @Override
    public TableDataInfo<PayRefundVo> queryPageList(PayRefundBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayRefund> lqw = buildQueryWrapper(bo);
        Page<PayRefundVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询退款订单列表
     */
    @Override
    public List<PayRefundVo> queryList(PayRefundBo bo) {
        LambdaQueryWrapper<PayRefund> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayRefund> buildQueryWrapper(PayRefundBo bo) {
        LambdaQueryWrapper<PayRefund> lqw = new LambdaQueryWrapper<>();
        lqw.eq(bo.getAppId() != null, PayRefund::getAppId, bo.getAppId());
        lqw.eq(bo.getChannelId() != null, PayRefund::getChannelId, bo.getChannelId());
        lqw.eq(StringUtils.isNotBlank(bo.getChannelCode()), PayRefund::getChannelCode, bo.getChannelCode());
        lqw.eq(StringUtils.isNotBlank(bo.getMerchantOrderId()), PayRefund::getMerchantOrderId, bo.getMerchantOrderId());
        lqw.eq(StringUtils.isNotBlank(bo.getMerchantRefundId()), PayRefund::getMerchantRefundId, bo.getMerchantRefundId());
        lqw.eq(bo.getStatus() != null, PayRefund::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增退款订单
     */
    @Override
    public Boolean insertByBo(PayRefundBo bo) {
        PayRefund add = MapstructUtils.convert(bo, PayRefund.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改退款订单
     */
    @Override
    public Boolean updateByBo(PayRefundBo bo) {
        PayRefund update = MapstructUtils.convert(bo, PayRefund.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayRefund entity){
        // 校验退款单号唯一性
        if (StringUtils.isNotBlank(entity.getNo())) {
            LambdaQueryWrapper<PayRefund> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PayRefund::getNo, entity.getNo());
            if (entity.getId() != null) {
                wrapper.ne(PayRefund::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(wrapper);
            if (count > 0) {
                throw new ServiceException("退款单号已存在");
            }
        }
        // 校验商户退款编号唯一性
        if (StringUtils.isNotBlank(entity.getMerchantRefundId())) {
            LambdaQueryWrapper<PayRefund> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PayRefund::getMerchantRefundId, entity.getMerchantRefundId());
            if (entity.getId() != null) {
                wrapper.ne(PayRefund::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(wrapper);
            if (count > 0) {
                throw new ServiceException("商户退款编号已存在");
            }
        }
        // 校验退款金额不能超过支付金额
        if (entity.getRefundPrice() != null && entity.getPayPrice() != null) {
            if (entity.getRefundPrice() > entity.getPayPrice()) {
                throw new ServiceException("退款金额不能超过支付金额");
            }
        }
    }

    /**
     * 批量删除退款订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            // 校验退款订单是否可以删除（处理中的退款不能删除）
            for (Long id : ids) {
                PayRefund refund = baseMapper.selectById(id);
                if (refund != null && refund.getStatus() == 0) {
                    throw new ServiceException("处理中的退款订单不能删除");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createRefund(PayRefundBo bo) {
        // 1. 校验订单
        PayOrder order = payOrderMapper.selectOne(new LambdaQueryWrapper<PayOrder>()
                .eq(PayOrder::getNo, bo.getOrderNo()));
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!PayOrderStatusEnum.SUCCESS.getStatus().equals(order.getStatus())) {
            throw new ServiceException("订单未支付或已退款");
        }
        
        // 2. 创建退款单
        PayRefund refund = MapstructUtils.convert(bo, PayRefund.class);
        refund.setAppId(order.getAppId());
        refund.setChannelId(order.getChannelId());
        refund.setChannelCode(order.getChannelCode());
        refund.setMerchantOrderId(order.getMerchantOrderId());
        refund.setPayPrice(order.getPrice());
        refund.setNo(IdUtil.getSnowflakeNextIdStr()); // 生成退款单号
        refund.setStatus(0); // WAITING
        // NotifyUrl 可以从 App 配置获取，或者 BO 传入
        
        baseMapper.insert(refund);
        
        // 3. 执行退款策略
        PayChannel channel = payChannelMapper.selectById(order.getChannelId());
        PayStrategy strategy = payStrategyFactory.getStrategy(channel.getCode());
        Boolean success = strategy.refund(refund, channel);
        
        // 4. 更新状态
        if (success) {
            refund.setStatus(10); // SUCCESS (假设 10 为成功)
            refund.setSuccessTime(new Date());
            baseMapper.updateById(refund);
            
            // 更新订单状态 (如果是全额退款，可以标记为已退款)
            // 简单处理：只要退款成功，订单状态改为已退款 (20)
            order.setStatus(PayOrderStatusEnum.REFUND.getStatus());
            payOrderMapper.updateById(order);
        } else {
            refund.setStatus(20); // FAIL (假设 20 为失败)
            baseMapper.updateById(refund);
        }
        
        return success;
    }

    /**
     * 处理退款回调成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyRefundSuccess(String refundNo, String channelRefundNo) {
        PayRefund refund = baseMapper.selectOne(new LambdaQueryWrapper<PayRefund>().eq(PayRefund::getNo, refundNo));
        if (refund == null) {
            log.error("退款回调订单不存在: {}", refundNo);
            return;
        }
        if (refund.getStatus() == 10) { // 已成功
            log.info("退款已成功，忽略回调: {}", refundNo);
            return;
        }
        
        refund.setStatus(10); // SUCCESS
        refund.setSuccessTime(new Date());
        refund.setChannelRefundNo(channelRefundNo);
        baseMapper.updateById(refund);
        
        log.info("退款成功: {}", refundNo);
    }
}
