package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.OrderCreateRequest;
import com.ruoyi.common.core.domain.dto.PaymentRequest;
import com.ruoyi.common.core.domain.dto.RefundRequest;
import com.ruoyi.common.core.domain.entity.OrderInfo;
import com.ruoyi.common.core.domain.entity.PayStatusEnum;
import com.ruoyi.common.core.domain.vo.OrderInfoVO;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.OrderInfoMapper;
import com.ruoyi.system.service.IOrderInfoService;
import com.ruoyi.system.util.PaymentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-03
 */
@Service
public class OrderInfoServiceImpl implements IOrderInfoService 
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    
    @Autowired
    private PaymentUtil paymentUtil;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public OrderInfo selectOrderInfoById(String id)
    {
        return orderInfoMapper.selectOrderInfoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param orderInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param orderInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertOrderInfo(OrderInfo orderInfo)
    {
        orderInfo.setCreateTime(DateUtils.getNowDate());
        return orderInfoMapper.insertOrderInfo(orderInfo);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param orderInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateOrderInfo(OrderInfo orderInfo)
    {
        orderInfo.setUpdateTime(DateUtils.getNowDate());
        return orderInfoMapper.updateOrderInfo(orderInfo);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoByIds(String[] ids)
    {
        return orderInfoMapper.deleteOrderInfoByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderInfoById(String id)
    {
        return orderInfoMapper.deleteOrderInfoById(id);
    }

    @Override
    @Transactional
    public AjaxResult createOrder(OrderCreateRequest request) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(request.getOrderName()) || request.getAmount() == null || request.getAmount() <= 0) {
                return AjaxResult.error("订单信息不完整");
            }
            
            // 获取当前用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null) {
                return AjaxResult.error("用户未登录");
            }
            
            // 创建订单
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setId(UUID.randomUUID().toString().replace("-", ""));
            orderInfo.setOrderId(System.currentTimeMillis()); // 使用时间戳作为订单号
            orderInfo.setOrderName(request.getOrderName());
            orderInfo.setUserId(loginUser.getUserId());
            orderInfo.setAmount(request.getAmount());
            orderInfo.setPayType(request.getPayType());
            orderInfo.setPackageType(request.getPackageType());
            orderInfo.setDeviceType(request.getDeviceType());
            orderInfo.setClientIp(request.getClientIp());
            orderInfo.setPayStatus(PayStatusEnum.CREATE.status); // 1-创建订单
            orderInfo.setIdDel(0L);
            orderInfo.setVersion(1L);
            orderInfo.setCreateTime(DateUtils.getNowDate());
            
            // 保存订单
            int result = insertOrderInfo(orderInfo);
            if (result > 0) {
                return AjaxResult.success("订单创建成功", orderInfo);
            } else {
                return AjaxResult.error("订单创建失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("订单创建异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult payOrder(PaymentRequest request) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(request.getOrderId())) {
                return AjaxResult.error("订单ID不能为空");
            }
            
            // 查询订单
            OrderInfo orderInfo = selectOrderByOrderId(request.getOrderId());
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 检查订单状态
            if (orderInfo.getPayStatus() != PayStatusEnum.CREATE.getStatus()) {
                return AjaxResult.error("订单状态不正确");
            }
            
            // 检查用户权限
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null || !loginUser.getUserId().equals(orderInfo.getUserId())) {
                return AjaxResult.error("无权限操作此订单");
            }
            
            // 调用第三方支付接口
            Map<String, Object> paymentResult = processPayment(orderInfo, request);
            
            return AjaxResult.success("支付请求成功", paymentResult);
            
        } catch (Exception e) {
            return AjaxResult.error("支付异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult completePayment(String orderId, String tradeNo, String payType) {
        try {
            // 查询订单
            OrderInfo orderInfo = selectOrderByOrderId(orderId);
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 检查订单状态
            if (orderInfo.getPayStatus() != PayStatusEnum.CREATE.getStatus()) {
                return AjaxResult.error("订单状态不正确");
            }
            
            // 更新订单状态
            orderInfo.setPayStatus(PayStatusEnum.PENDING.getStatus()); // 2-待出货
            orderInfo.setPayTime(DateUtils.getNowDate());
            orderInfo.setTradeNo(tradeNo);
            orderInfo.setCallTime(DateUtils.getNowDate());
            orderInfo.setCallbackContent("支付成功回调");
            orderInfo.setUpdateTime(DateUtils.getNowDate());
            
            // 计算服务时间
            calculateServiceTime(orderInfo);
            
            // 保存订单
            int result = updateOrderInfo(orderInfo);
            if (result > 0) {
                return AjaxResult.success("支付完成");
            } else {
                return AjaxResult.error("支付完成处理失败");
            }
            
        } catch (Exception e) {
            return AjaxResult.error("支付完成处理异常: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public AjaxResult refundOrder(RefundRequest request) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(request.getOrderId()) || request.getRefundAmount() == null || request.getRefundAmount() <= 0) {
                return AjaxResult.error("退款信息不完整");
            }
            
            // 查询订单
            OrderInfo orderInfo = selectOrderByOrderId(request.getOrderId());
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 检查订单状态
            if (orderInfo.getPayStatus() != PayStatusEnum.PENDING.getStatus() && orderInfo.getPayStatus() != PayStatusEnum.WAIT_REFUND.getStatus()) {
                return AjaxResult.error("订单状态不允许退款");
            }
            
            // 检查退款金额
            if (request.getRefundAmount() > orderInfo.getAmount()) {
                return AjaxResult.error("退款金额不能大于订单金额");
            }
            
            // 检查是否已退款
            if (orderInfo.getRefundAmount() != null && orderInfo.getRefundAmount() > 0) {
                return AjaxResult.error("订单已退款");
            }
            
            // 调用第三方退款接口
            boolean refundResult = paymentUtil.processRefund(orderInfo.getOrderId().toString(), request.getRefundAmount(), orderInfo.getPayType());
            if (!refundResult) {
                return AjaxResult.error("第三方退款失败");
            }
            
            // 更新订单退款信息
            orderInfo.setRefundAmount(request.getRefundAmount());
            orderInfo.setRefundTime(DateUtils.getNowDate());
            orderInfo.setUpdateTime(DateUtils.getNowDate());
            
            // 如果是全额退款，更新订单状态
            if (request.getRefundAmount().equals(orderInfo.getAmount())) {
                orderInfo.setPayStatus(PayStatusEnum.REFUND.getStatus()); // 4-已退款
            }
            
            // 保存订单
            int result = updateOrderInfo(orderInfo);
            if (result > 0) {
                return AjaxResult.success("退款申请成功");
            } else {
                return AjaxResult.error("退款申请失败");
            }
            
        } catch (Exception e) {
            return AjaxResult.error("退款异常: " + e.getMessage());
        }
    }

    @Override
    public List<OrderInfo> selectUserOrders(Long userId) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setIdDel(0L);
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    @Override
    public OrderInfo selectOrderByOrderId(String orderId) {
        return orderInfoMapper.selectOrderByOrderId(orderId);
    }

    @Override
    public List<OrderInfoVO> selectOrderInfoVOList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoVOList(orderInfo);
    }

    @Override
    @Transactional
    public AjaxResult confirmShipment(String orderId) {
        try {
            // 查询订单
            OrderInfo orderInfo = selectOrderByOrderId(orderId);
            if (orderInfo == null) {
                return AjaxResult.error("订单不存在");
            }
            
            // 检查订单状态
            if (orderInfo.getPayStatus() != PayStatusEnum.PENDING.getStatus()) {
                return AjaxResult.error("订单状态不正确，只有已支付的订单才能确认出货");
            }
            
            // 更新订单状态为已完成
            orderInfo.setPayStatus(PayStatusEnum.COMPLETE.getStatus()); // 3-已完成
            orderInfo.setUpdateTime(DateUtils.getNowDate());
            
            // 保存订单
            int result = updateOrderInfo(orderInfo);
            if (result > 0) {
                return AjaxResult.success("确认出货成功");
            } else {
                return AjaxResult.error("确认出货失败");
            }
            
        } catch (Exception e) {
            return AjaxResult.error("确认出货异常: " + e.getMessage());
        }
    }

    /**
     * 处理支付过程
     */
    private Map<String, Object> processPayment(OrderInfo orderInfo, PaymentRequest request) {
        // 根据支付方式调用相应的支付接口
        switch (request.getPayType()) {
            case "aliPay":
                return paymentUtil.processAliPay(orderInfo, request);
            case "wechatPay":
                return paymentUtil.processWechatPay(orderInfo, request);
            case "applePay":
                return paymentUtil.processApplePay(orderInfo, request);
            default:
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("error", "不支持的支付方式");
                return errorResult;
        }
    }

    /**
     * 计算服务时间
     */
    private void calculateServiceTime(OrderInfo orderInfo) {
        Date now = DateUtils.getNowDate();
        orderInfo.setStartTime(now);
        
        // 根据套餐类型计算结束时间
        String packageType = orderInfo.getPackageType();
        if ("1".equals(packageType)) {
            // 包月
            orderInfo.setEndTime(DateUtils.addMonths(now, 1));
        } else if ("3".equals(packageType)) {
            // 包季度
            orderInfo.setEndTime(DateUtils.addMonths(now, 3));
        } else if ("6".equals(packageType)) {
            // 半年
            orderInfo.setEndTime(DateUtils.addMonths(now, 6));
        } else if ("12".equals(packageType)) {
            // 一年
            orderInfo.setEndTime(DateUtils.addMonths(now, 12));
        }
    }
}
