package com.kexue.skills.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kexue.skills.entity.PaymentOrder;
import com.kexue.skills.entity.dto.PaymentOrderDto;
import com.kexue.skills.mapper.PaymentOrderMapper;
import com.kexue.skills.service.AccountService;
import com.kexue.skills.service.PaymentOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (PaymentOrder)表服务实现类
 *
 * @author 王志维
 * @since 2025-02-21 23:01:48
 */
@Service("paymentOrderService")
@Transactional(rollbackFor = Exception.class)
public class PaymentOrderServiceImpl implements PaymentOrderService {
    @Resource
    private PaymentOrderMapper paymentOrderMapper;

    @Resource
    private AccountService accountService;

    /**
     * 分页查询
     *
     * @param queryDto 筛选条件
     * @return 查询结果
     */
    @Override
    public PageInfo<PaymentOrder> getPageList(PaymentOrderDto queryDto) {
        PageHelper.startPage(queryDto.getPageNum(), queryDto.getPageSize());
        List<PaymentOrder> list = this.paymentOrderMapper.getPageList(queryDto);
        return new PageInfo<>(list);
    }

    /**
     * 查询列表
     *
     * @param queryDto 筛选条件
     * @return 查询结果
     */
    @Override
    public List<PaymentOrder> getList(PaymentOrderDto queryDto) {
        return this.paymentOrderMapper.getList(queryDto);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param orderId 主键
     * @return 实例对象
     */
    @Override
    public PaymentOrder queryById(Long orderId) {
        return this.paymentOrderMapper.queryById(orderId);
    }

    /**
     * 通过订单号查询单条数据
     *
     * @param orderNo 订单号
     * @return 实例对象
     */
    @Override
    public PaymentOrder queryByOrderNo(String orderNo) {
        return this.paymentOrderMapper.queryByOrderNo(orderNo);
    }

    /**
     * 新增数据
     *
     * @param paymentOrder 实例对象
     * @return 实例对象
     */
    @Override
    public PaymentOrder insert(PaymentOrder paymentOrder) {
        // 设置创建时间和更新时间
        Date now = new Date();
        paymentOrder.setCreateTime(now);
        paymentOrder.setUpdateTime(now);
        // 设置默认值
        paymentOrder.setDeleteFlag(0);
        // 保存数据
        this.paymentOrderMapper.insert(paymentOrder);
        return paymentOrder;
    }

    /**
     * 更新数据
     *
     * @param paymentOrder 实例对象
     * @return 实例对象
     */
    @Override
    public PaymentOrder update(PaymentOrder paymentOrder) {
        // 设置更新时间
        paymentOrder.setUpdateTime(new Date());
        // 更新数据
        this.paymentOrderMapper.update(paymentOrder);
        return this.queryById(paymentOrder.getOrderId());
    }

    /**
     * 更新订单状态
     *
     * @param orderId 订单ID
     * @param status 状态
     * @param channelOrderNo 渠道订单号
     * @return 影响行数
     */
    @Override
    public int updateStatus(Long orderId, Integer status, String channelOrderNo) {
        return this.paymentOrderMapper.updateStatus(orderId, status, channelOrderNo);
    }

    /**
     * 通过主键逻辑删除
     *
     * @param orderId 主键
     * @param updateBy 更新人
     * @return 影响行数
     */
    @Override
    public int logicDeleteById(Long orderId, String updateBy) {
        return this.paymentOrderMapper.logicDeleteById(orderId, updateBy);
    }

    /**
     * 通过主键物理删除
     *
     * @param orderId 主键
     * @return 影响行数
     */
    @Override
    public int deleteById(Long orderId) {
        return this.paymentOrderMapper.deleteById(orderId);
    }

    /**
     * 创建支付订单
     *
     * @param paymentOrder 订单信息
     * @return 支付订单
     */
    @Override
    public PaymentOrder createPaymentOrder(PaymentOrder paymentOrder) {
        // 生成订单号
        String orderNo = generateOrderNo();
        paymentOrder.setOrderNo(orderNo);
        // 设置初始状态
        paymentOrder.setStatus(1); // 1.待支付
        // 设置创建时间和更新时间
        Date now = new Date();
        paymentOrder.setCreateTime(now);
        paymentOrder.setUpdateTime(now);
        // 设置默认值
        paymentOrder.setDeleteFlag(0);
        // 保存订单
        this.paymentOrderMapper.insert(paymentOrder);
        return paymentOrder;
    }

    /**
     * 处理支付回调
     *
     * @param orderNo 订单号
     * @param status 支付状态
     * @param channelOrderNo 渠道订单号
     * @return 处理结果
     */
    @Override
    public boolean handlePaymentCallback(String orderNo, Integer status, String channelOrderNo) {
        // 查询订单
        PaymentOrder order = this.queryByOrderNo(orderNo);
        if (order == null) {
            return false;
        }
        
        // 更新订单状态
        this.updateStatus(order.getOrderId(), status, channelOrderNo);
        
        // 如果支付成功，更新账户余额
        if (status == 2) { // 2.已支付
            // 根据业务类型处理不同的业务逻辑
            if ("recharge".equals(order.getBusinessType())) {
                // 充值业务，增加用户余额
                this.accountService.addBalance(order.getUserId(), order.getAmount(), orderNo, 
                        order.getBusinessId(), order.getBusinessType(), "充值成功");
            } else if ("purchase_content".equals(order.getBusinessType())) {
                // 购买内容业务，这里不需要操作余额，因为余额已经在购买时扣除
                // 只需要更新订单状态即可
            }
        }
        
        return true;
    }

    /**
     * 生成订单号
     *
     * @return 订单号
     */
    private String generateOrderNo() {
        // 订单号生成规则：时间戳 + 6位随机数
        String timestamp = String.valueOf(System.currentTimeMillis());
        String random = UUID.randomUUID().toString().substring(0, 6).replaceAll("-", "");
        return timestamp + random;
    }
}