package org.dromara.pay.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
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.PayApp;
import org.dromara.pay.domain.PayChannel;
import org.dromara.pay.domain.PayOrder;
import org.dromara.pay.domain.bo.PayOrderBo;
import org.dromara.pay.domain.vo.PayOrderSubmitRespVO;
import org.dromara.pay.domain.vo.PayOrderVo;
import org.dromara.pay.enums.PayOrderStatusEnum;
import org.dromara.pay.event.PaySuccessEvent;
import org.dromara.pay.mapper.PayAppMapper;
import org.dromara.pay.mapper.PayChannelMapper;
import org.dromara.pay.mapper.PayOrderMapper;
import org.dromara.pay.service.PayOrderService;
import org.springframework.context.ApplicationEventPublisher;
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 PayOrderServiceImpl implements PayOrderService {

    private final PayOrderMapper baseMapper;
    private final PayAppMapper payAppMapper;
    private final PayChannelMapper payChannelMapper;
    private final PayStrategyFactory payStrategyFactory;
    private final ApplicationEventPublisher eventPublisher;

    /**
     * 查询支付订单
     */
    @Override
    public PayOrderVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询支付订单列表
     */
    @Override
    public TableDataInfo<PayOrderVo> queryPageList(PayOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayOrder> lqw = buildQueryWrapper(bo);
        Page<PayOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询支付订单列表
     */
    @Override
    public List<PayOrderVo> queryList(PayOrderBo bo) {
        LambdaQueryWrapper<PayOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

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

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

    /**
     * 修改支付订单
     */
    @Override
    public Boolean updateByBo(PayOrderBo bo) {
        PayOrder update = MapstructUtils.convert(bo, PayOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayOrder entity){
        // 校验商户订单号唯一性（如果已存在）
        if (StringUtils.isNotBlank(entity.getMerchantOrderId())) {
            LambdaQueryWrapper<PayOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PayOrder::getMerchantOrderId, entity.getMerchantOrderId());
            if (entity.getId() != null) {
                wrapper.ne(PayOrder::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(wrapper);
            if (count > 0) {
                throw new ServiceException("商户订单号已存在");
            }
        }
        // 校验支付单号唯一性
        if (StringUtils.isNotBlank(entity.getNo())) {
            LambdaQueryWrapper<PayOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PayOrder::getNo, entity.getNo());
            if (entity.getId() != null) {
                wrapper.ne(PayOrder::getId, entity.getId());
            }
            Long count = baseMapper.selectCount(wrapper);
            if (count > 0) {
                throw new ServiceException("支付单号已存在");
            }
        }
    }

    /**
     * 批量删除支付订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            // 校验订单是否可以删除（已支付的订单不能删除）
            for (Long id : ids) {
                PayOrder order = baseMapper.selectById(id);
                if (order != null && PayOrderStatusEnum.SUCCESS.getStatus().equals(order.getStatus())) {
                    throw new ServiceException("已支付的订单不能删除");
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayOrderSubmitRespVO submitOrder(PayOrderBo bo) {
        // 1. 校验 App
        PayApp app = payAppMapper.selectById(bo.getAppId());
        if (app == null || app.getStatus() == 1) { // 假设 1 为关闭
            throw new ServiceException("应用不存在或已禁用");
        }

        // 2. 校验 Channel
        PayChannel channel = payChannelMapper.selectOne(new LambdaQueryWrapper<PayChannel>()
                .eq(PayChannel::getAppId, bo.getAppId())
                .eq(PayChannel::getCode, bo.getChannelCode()));
        if (channel == null || channel.getStatus() == 1) {
             throw new ServiceException("支付渠道不存在或已禁用");
        }

        // 3. 创建订单
        PayOrder order = MapstructUtils.convert(bo, PayOrder.class);
        order.setChannelId(channel.getId());
        order.setNo(IdUtil.getSnowflakeNextIdStr()); // 生成内部单号
        order.setStatus(PayOrderStatusEnum.WAITING.getStatus());
        order.setExpireTime(new Date(System.currentTimeMillis() + 30 * 60 * 1000)); // 30分钟过期
        // 补全 NotifyUrl
        if (StringUtils.isBlank(order.getNotifyUrl())) {
            String baseUrl = app.getPayNotifyUrl();
            if (baseUrl.endsWith("/")) {
                baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
            }
            order.setNotifyUrl(baseUrl + "/" + channel.getCode() + "/" + channel.getId());
        }
        
        baseMapper.insert(order);

        // 4. 调用策略
        PayStrategy strategy = payStrategyFactory.getStrategy(channel.getCode());
        PayOrderSubmitRespVO resp = strategy.unifiedOrder(order, channel);
        
        return resp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notifyOrderSuccess(String orderNo, String channelOrderNo) {
        PayOrder order = baseMapper.selectOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getNo, orderNo));
        if (order == null) {
            log.error("支付回调订单不存在: {}", orderNo);
            return;
        }
        if (PayOrderStatusEnum.SUCCESS.getStatus().equals(order.getStatus())) {
            log.info("订单已支付，忽略回调: {}", orderNo);
            return;
        }
        
        order.setStatus(PayOrderStatusEnum.SUCCESS.getStatus());
        order.setSuccessTime(new Date());
        order.setChannelOrderNo(channelOrderNo);
        baseMapper.updateById(order);
        
        log.info("订单支付成功: {}", orderNo);
        // 发布支付成功事件
        eventPublisher.publishEvent(new PaySuccessEvent(this, order));
    }
}
