package com.gxwebsoft.common.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.TenantPackage;
import com.gxwebsoft.common.system.entity.TenantSubscriptionOrder;
import com.gxwebsoft.common.system.mapper.TenantSubscriptionOrderMapper;
import com.gxwebsoft.common.system.service.TenantPackageService;
import com.gxwebsoft.common.system.service.TenantSubscriptionOrderService;
import com.gxwebsoft.common.system.service.TenantSubscriptionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 租户订阅订单ServiceImpl
 *
 * @author WebSoft
 * @since 2025-12-12
 */
@Service
public class TenantSubscriptionOrderServiceImpl extends ServiceImpl<TenantSubscriptionOrderMapper, TenantSubscriptionOrder> implements TenantSubscriptionOrderService {

    @Resource
    private TenantPackageService tenantPackageService;

    @Resource
    private TenantSubscriptionService tenantSubscriptionService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantSubscriptionOrder createOrder(Integer packageId, Integer payType, Integer tenantId, Integer userId) {
        // 查询套餐信息
        TenantPackage tenantPackage = tenantPackageService.getById(packageId);
        if (tenantPackage == null) {
            throw new BusinessException("套餐不存在");
        }
        if (tenantPackage.getStatus() != 1) {
            throw new BusinessException("套餐已下架");
        }

        // 计算价格
        BigDecimal price;
        if (payType == 1) {
            price = tenantPackage.getPriceMonthly();
        } else if (payType == 3) {
            price = tenantPackage.getPriceQuarterly();
        } else if (payType == 12) {
            price = tenantPackage.getPriceYearly();
        } else {
            throw new BusinessException("支付周期不正确");
        }

        // 创建订单
        TenantSubscriptionOrder order = new TenantSubscriptionOrder();
        order.setOrderNo(generateOrderNo());
        order.setTenantId(tenantId);
        order.setPackageId(packageId);
        order.setPackageName(tenantPackage.getPackageName());
        order.setVersion(tenantPackage.getVersion());
        order.setPayType(payType);
        order.setOriginalPrice(price);
        order.setDiscountPrice(BigDecimal.ZERO);
        order.setActualPrice(price);
        order.setIsTrial(0);
        order.setIsRenewal(0);
        order.setIsUpgrade(0);
        order.setOrderStatus(0); // 待支付
        order.setUserId(userId);
        order.setCreateTime(new Date());

        save(order);
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TenantSubscriptionOrder createTrialOrder(Integer tenantId, Integer userId) {
        // 查询试用套餐（version=0）
        TenantPackage trialPackage = tenantPackageService.getByVersion(0);
        if (trialPackage == null) {
            throw new BusinessException("试用套餐不存在");
        }

        // 检查是否已经试用过
        long count = count(new LambdaQueryWrapper<TenantSubscriptionOrder>()
                .eq(TenantSubscriptionOrder::getTenantId, tenantId)
                .eq(TenantSubscriptionOrder::getIsTrial, 1));
        if (count > 0) {
            throw new BusinessException("已经使用过试用版");
        }

        // 创建试用订单
        TenantSubscriptionOrder order = new TenantSubscriptionOrder();
        order.setOrderNo(generateOrderNo());
        order.setTenantId(tenantId);
        order.setPackageId(trialPackage.getPackageId());
        order.setPackageName(trialPackage.getPackageName());
        order.setVersion(trialPackage.getVersion());
        order.setPayType(0);
        order.setOriginalPrice(BigDecimal.ZERO);
        order.setDiscountPrice(BigDecimal.ZERO);
        order.setActualPrice(BigDecimal.ZERO);
        order.setStartTime(new Date());
        order.setEndTime(DateUtil.offsetDay(new Date(), trialPackage.getTrialDays()));
        order.setIsTrial(1);
        order.setIsRenewal(0);
        order.setIsUpgrade(0);
        order.setOrderStatus(2); // 直接激活
        order.setUserId(userId);
        order.setCreateTime(new Date());

        save(order);

        // 创建订阅记录
        tenantSubscriptionService.createOrUpdateSubscription(
                tenantId,
                trialPackage.getPackageId(),
                trialPackage.getVersion(),
                order.getStartTime(),
                order.getEndTime(),
                1
        );

        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(String orderNo, String paymentMethod, String paymentId) {
        TenantSubscriptionOrder order = getByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (order.getOrderStatus() != 0) {
            throw new BusinessException("订单状态不正确");
        }

        order.setPaymentMethod(paymentMethod);
        order.setPaymentId(paymentId);
        order.setPaymentTime(new Date());
        order.setOrderStatus(1); // 已支付
        order.setUpdateTime(new Date());

        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activateOrder(String orderNo) {
        TenantSubscriptionOrder order = getByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (order.getOrderStatus() != 1) {
            throw new BusinessException("订单未支付");
        }

        // 计算开始和结束时间
        Date startTime = new Date();
        Date endTime = DateUtil.offsetMonth(startTime, order.getPayType());

        order.setStartTime(startTime);
        order.setEndTime(endTime);
        order.setOrderStatus(2); // 已激活
        order.setUpdateTime(new Date());

        boolean updated = updateById(order);

        if (updated) {
            // 创建或更新订阅记录
            tenantSubscriptionService.createOrUpdateSubscription(
                    order.getTenantId(),
                    order.getPackageId(),
                    order.getVersion(),
                    startTime,
                    endTime,
                    0
            );
        }

        return updated;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(String orderNo, String cancelReason) {
        TenantSubscriptionOrder order = getByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (order.getOrderStatus() != 0) {
            throw new BusinessException("只能取消待支付订单");
        }

        order.setOrderStatus(3); // 已取消
        order.setCancelReason(cancelReason);
        order.setUpdateTime(new Date());

        return updateById(order);
    }

    @Override
    public PageResult<TenantSubscriptionOrder> pageByTenant(Integer tenantId, Integer page, Integer limit) {
        IPage<TenantSubscriptionOrder> iPage = new Page<>(page, limit);
        baseMapper.selectPageByTenant(iPage, tenantId);
        return new PageResult<TenantSubscriptionOrder>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public TenantSubscriptionOrder getByOrderNo(String orderNo) {
        return baseMapper.selectByOrderNo(orderNo);
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        return "SUB" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + IdUtil.randomUUID().substring(0, 6).toUpperCase();
    }
}
