package com.ruoyi.bst.vipOrder.service.impl;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.pay.service.PayValidator;
import com.ruoyi.bst.vip.domain.VipVO;
import com.ruoyi.bst.vipOrder.domain.bo.VipOrderCreateBO;
import com.ruoyi.bst.vipOrder.domain.dto.VipOrderCreateDTO;
import com.ruoyi.bst.vipOrder.service.VipOrderValidator;
import com.ruoyi.common.core.domain.vo.UserVO;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;

@Service
public class VipOrderValidatorImpl implements VipOrderValidator {

    @Autowired
    private PayValidator payValidator;
    
    @Override
    public void validate(VipOrderCreateBO bo) {
        ServiceUtil.assertion(bo == null, "卡券订单创建参数不能为空");

        VipOrderCreateDTO dto = bo.getDto();

        // 卡券信息
        VipVO vip = bo.getVip();
        ServiceUtil.assertion(vip == null, "ID为%s的卡券信息不存在", dto.getVipId());

        // 校验卡券数据是否一致
        this.checkVip(vip, dto.getVip());
        
        // 用户信息
        UserVO user = bo.getUser();
        ServiceUtil.assertion(user == null, "ID为%s的用户信息不存在", dto.getUserId());

        // 支付校验
        payValidator.checkPay(bo.getApp(), bo.getChannel(), bo.getUserApp(), bo.getChannelPayList(), null);
    }

    /**
     * 校验卡券数据是否一致
     * @param db
     * @param param
     */
    private void checkVip(VipVO db, VipVO param) {
        // 参数校验
        ServiceUtil.assertion(param == null || db == null, "卡券数据不一致");
        
        // 使用MathUtils进行数值比较
        ServiceUtil.assertion(!MathUtils.equals(db.getPrice(), param.getPrice()), "卡券价格已发生变化，请刷新后重试");
        ServiceUtil.assertion(!MathUtils.equals(db.getDiscountValue(), param.getDiscountValue()), "卡券优惠值已发生变化，请刷新后重试");
        ServiceUtil.assertion(!MathUtils.equals(db.getValidDays(), param.getValidDays()), "卡券有效期已发生变化，请刷新后重试");
        ServiceUtil.assertion(!Objects.equals(db.getEnableLimit(), param.getEnableLimit()), "卡券使用限制已发生变化，请刷新后重试");
        ServiceUtil.assertion(!MathUtils.equals(db.getLimitTotal(), param.getLimitTotal()), "卡券可用次数已发生变化，请刷新后重试");
        ServiceUtil.assertion(!MathUtils.equals(db.getMinAmount(), param.getMinAmount()), "卡券最低使用门槛已发生变化，请刷新后重试");

        // 如果开启使用限制,校验限制相关参数
        if(Boolean.TRUE.equals(db.getEnableLimit())) {
            ServiceUtil.assertion(!MathUtils.equals(db.getLimitCount(), param.getLimitCount()), "卡券限制频率次数已发生变化，请刷新后重试");
            ServiceUtil.assertion(!MathUtils.equals(db.getLimitRound(), param.getLimitRound()), "卡券限制频率周期已发生变化，请刷新后重试");
            ServiceUtil.assertion(!Objects.equals(db.getLimitUnit(), param.getLimitUnit()), "卡券限制频率单位已发生变化，请刷新后重试");
        }
    }
}
