package com.ruoyi.cai.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.cai.domain.MemberPrice;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.domain.UserMember;
import com.ruoyi.cai.domain.VipOrder;
import com.ruoyi.cai.dto.admin.vo.VipOrderAdminVo;
import com.ruoyi.cai.dto.dto.AddVipOrderDto;
import com.ruoyi.cai.mapper.VipOrderMapper;
import com.ruoyi.cai.pay.*;
import com.ruoyi.cai.service.*;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * VIP订单Service业务层处理
 *
 * @author 77
 * @date 2024-01-03
 */
@Service
@Slf4j
public class VipOrderServiceImpl extends ServiceImpl<VipOrderMapper,VipOrder> implements VipOrderService {

    @Autowired
    private MemberPriceService memberPriceService;
    @Autowired
    private UserMemberService userMemberService;
    @Autowired
    private UserService userService;

    /**
     * 强制修改VIP
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VipOrder updateVipOrderAdmin(Long memberPriceId, Long userId){
        MemberPrice memberPrice = memberPriceService.getById(memberPriceId);
        if(memberPrice == null){
            throw new ServiceException("VIP价格错误");
        }
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(userId);
        vipOrder.setVipId(memberPrice.getId());
        vipOrder.setVipType(memberPrice.getMemberType());
        vipOrder.setVipName(memberPrice.getName());
        vipOrder.setVipExpire(memberPrice.getExpires());
        vipOrder.setVipLongs(memberPrice.getLongs());
        vipOrder.setPrice(memberPrice.getPrice());
        vipOrder.setOrderNo(OrderNoUtil.createOrderNo(OrderTypeEnum.VIP_ORDER_SUB));
        vipOrder.setPayStatus(PayStatusEnum.NO_PAY.getCode());
        vipOrder.setPlatformType(PlatformTypeEnum.ADMIN.name());
        vipOrder.setOperateIp(ServletUtils.getClientIP());
        vipOrder.setAdmin(true);
        vipOrder.setAdminId(LoginHelper.getUserId());
        this.save(vipOrder);
        LocalDateTime now = LocalDateTime.now();
        UserMember userMember = userMemberService.getByUserId(userId);
        if(userMember == null){
            userMember = new UserMember();
        }
        userMember.setUserId(userId);
        userMember.setMemberType(memberPrice.getMemberType());
        userMember.setExpire(memberPrice.getExpires());
        userMember.setLongs(memberPrice.getLongs());
        userMember.setExpireDate(now.plusDays(memberPrice.getExpires()));
        userMember.setCreateTime(now);
        userMember.setMemberStatus(MemberStatusEnum.NORMAL.getCode());
        userMemberService.saveOrUpdate(userMember);
        return vipOrder;
    }

    @Override
    public VipOrder addVipOrder(AddVipOrderDto addVipOrder){
        Long memberPriceId = addVipOrder.getMemberPriceId();
        User user = userService.getById(addVipOrder.getUserId());
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        MemberPrice memberPrice = memberPriceService.getById(memberPriceId);
        if(memberPrice == null){
            throw new ServiceException("VIP价格错误");
        }
        VipOrder vipOrder = new VipOrder();
        vipOrder.setUserId(addVipOrder.getUserId());
        vipOrder.setVipId(memberPrice.getId());
        vipOrder.setVipType(memberPrice.getMemberType());
        vipOrder.setVipName(memberPrice.getName());
        vipOrder.setVipExpire(memberPrice.getExpires());
        vipOrder.setVipLongs(memberPrice.getLongs());
        vipOrder.setPrice(memberPrice.getPrice());
        vipOrder.setOrderNo(OrderNoUtil.createOrderNo(OrderTypeEnum.VIP_ORDER_SUB));
        vipOrder.setPayStatus(PayStatusEnum.READY_PAY.getCode());
        this.save(vipOrder);
        return vipOrder;
    }

    @Override
    public VipOrder getByOrderNo(String orderNo){
        return this.getOne(Wrappers.lambdaQuery(VipOrder.class).eq(VipOrder::getOrderNo,orderNo)
                .last("limit 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderSuccess(String orderNo){
        VipOrder vipOrder = this.getByOrderNo(orderNo);
        if(vipOrder == null){
            throw new ServiceException("订单不存在");
        }
        if(!PayStatusEnum.READY_PAY.getCode().equals(vipOrder.getPayStatus())){
            log.error("订单支付状态错误!vipOrder={}", JSON.toJSONString(vipOrder));
            throw new ServiceException("订单支付状态错误!");
        }
        boolean update = this.update(Wrappers.lambdaUpdate(VipOrder.class)
                .eq(VipOrder::getOrderNo, vipOrder.getOrderNo())
                .eq(VipOrder::getPayStatus, PayStatusEnum.READY_PAY.getCode())
                .set(VipOrder::getPayStatus, PayStatusEnum.PAY.getCode()));
        if(!update){
            log.error("订单支付状态错误!vipOrder={}", JSON.toJSONString(vipOrder));
            throw new ServiceException("订单支付状态错误!");
        }
        // 新增会员
        incVip(vipOrder.getUserId(),vipOrder.getVipType(),vipOrder.getVipExpire(),vipOrder.getVipLongs());
    }

    public boolean incVip(Long userId,Integer memberType,Integer expire,Integer longs){
        UserMember userMember = userMemberService.getByUserIdAndType(userId,memberType);
        LocalDateTime createTime = LocalDateTime.now();
        // 以前会员失效
        if(userMember == null ||
                !MemberStatusEnum.NORMAL.getCode().equals(userMember.getMemberStatus()) || // 会员不可用
                userMember.getExpireDate().isBefore(createTime)
        ){
            if(userMember == null){
                userMember = new UserMember();
            }
            userMember.setUserId(userId);
            userMember.setMemberType(memberType);
            userMember.setExpire(expire);
            userMember.setLongs(longs);
            LocalDate expireDate = createTime.plusDays(expire).plusDays(1).toLocalDate();
            userMember.setExpireDate(LocalDateTime.of(expireDate, LocalTime.MIN));
            userMember.setCreateTime(createTime);
            userMember.setMemberStatus(MemberStatusEnum.NORMAL.getCode());
            userMemberService.saveOrUpdate(userMember);
            return true;
        }
        if(userMember.getLongs() == 1){ // 已经是永久会员还买？ 傻逼
            return true;
        }
        userMember.setCreateTime(createTime);
        userMember.setExpireDate(userMember.getExpireDate().plusDays(expire));
        userMember.setLongs(longs);
        userMemberService.saveOrUpdate(userMember);
        return true;
    }

    @Override
    public Page<VipOrderAdminVo> pageAdmin(PageQuery pageQuery, VipOrderAdminVo bo) {
        return baseMapper.pageAdmin(pageQuery.build(),bo);
    }

}
