package com.ruoyi.school.member.domain;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 会员卡实体类
 * 对应数据库表: sc_member_cards
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("sc_member_cards")
public class  ScMemberCard implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     */
    @TableId(value = "id")
    private Long id;

    @TableField(value = "tenant_id")
    private String tenantId;

    /**
     * 卡号
     */
    @TableField(value = "card_no")
    private String cardNo;

    /**
     * 会员ID
     */
    @TableField(value = "member_id")
    private Long memberId;



    /**
     * 卡类型ID
     */
    @TableField(value = "card_type_id")
    private Long cardTypeId;

    /**
     * 状态
     * ACTIVE-激活, INACTIVE-未激活, EXPIRED-已过期,
     * SUSPENDED-已暂停, DEPLETED-已用完
     */
    @TableField("status")
    private String status;

    /**
     * 剩余次数
     */
    @TableField("remaining_count")
    private BigDecimal remainingCount;
    @TableField("count_fee")
    private BigDecimal countFee;
    @TableField("day_fee")
    private BigDecimal dayFee;

    /**
     * 剩余天数
     */
    @TableField(exist = false)
    private Integer remainingDays ;

    /**
     * 总次数
     */
    @TableField("total_count")
    private BigDecimal totalCount;

    /**
     * 总天数
     */
    @TableField("total_days")
    private Integer totalDays ;

    @TableField("total_fee")
    private BigDecimal totalFee;

    @TableField("remaining_total_fee")
    private BigDecimal remainingTotalFee;

    //时间卡 是否激活 1:立刻激活 2：首次预约激活
    @TableField("have_activation_date")
    private String haveActivationDate;

    //储值or次数卡 是否设置有效期 1:不限期，用完失效 2：设置有效期
    @TableField("have_expiry_date")
    private String haveExpiryDate;

    /**
     * 激活日期
     */
    @TableField("activation_date")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate activationDate;

    /**
     * 到期日期
     */
    @TableField("expiry_date")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate expiryDate;

    /**
     * 购买日期
     */
    @TableField(value = "purchase_date", fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime purchaseDate;

    /**
     * 购买价格
     */
    @TableField("price")
    private BigDecimal price;


    /**
     * 备注
     */
    @TableField("notes")
    private String notes;

    /**
     * 收费模式 count:课时 days:时间 total_fee:储值
     */
    @TableField("charge_type")
    private String chargeType;

    /**
     * 创建时间
     */
    @TableField(value = "created_at", fill = FieldFill.INSERT)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @TableField(value = "updated_at", fill = FieldFill.INSERT_UPDATE)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;

    /**
     * 逻辑删除标志 (0-未删除，1-已删除)
     */
    @TableLogic
    @TableField(value = "is_deleted")
    private Integer isDeleted = 0;



    /**
     * 会员实体（关联查询用）
     * 注意：MyBatis Plus 不支持直接实体关联，这里仅作为查询结果接收字段
     */
    @TableField(exist = false)
    @JsonIgnore
    private ScStudent member;

    /**
     * 卡类型实体（关联查询用）
     * 注意：MyBatis Plus 不支持直接实体关联，这里仅作为查询结果接收字段
     */
    @TableField(exist = false)
    @JsonIgnore
    private ScMemberCardTypes cardType;
    @TableField(exist = false)
    private String cardName;

    /**
     * 是否有效（可用的卡）
     */
    @TableField(exist = false)
    private Boolean valid;

    /**
     * 是否已过期
     */
    @TableField(exist = false)
    private Boolean expired;

    /**
     * 是否可用（激活且未过期）
     */
    @TableField(exist = false)
    private Boolean available;

    /**
     * 是否可以续费
     */
    @TableField(exist = false)
    private Boolean canRenew;

    // 枚举类
    public enum CardStatus {
        ACTIVE("激活"),
        INACTIVE("未激活"),
        EXPIRED("已过期"),
        SUSPENDED("已暂停"),
        DEPLETED("已用完");

        private final String description;

        CardStatus(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public static CardStatus fromString(String status) {
            if (status == null) return null;
            for (CardStatus s : CardStatus.values()) {
                if (s.name().equalsIgnoreCase(status)) {
                    return s;
                }
            }
            return null;
        }
    }

    /**
     * 获取卡状态枚举
     */
    public CardStatus getCardStatus() {
        return CardStatus.fromString(this.status);
    }



    public Integer getRemainingDays() {
        if (activationDate== null || expiryDate == null ) {
            return totalDays;
        }

        if (expiryDate.isBefore(LocalDate.now())) {
            return 0;
        }
       Long days= java.time.temporal.ChronoUnit.DAYS.between(
                LocalDate.now(), expiryDate
        );
        return days.intValue();
    }

    /**
     * 设置卡状态
     */
    public void setCardStatus(CardStatus cardStatus) {
        this.status = cardStatus != null ? cardStatus.name() : null;
    }

    /**
     * 是否有效（可用的卡）
     */
    public Boolean isValid() {
        CardStatus currentStatus = getCardStatus();
        return CardStatus.ACTIVE.equals(currentStatus) ||
               CardStatus.INACTIVE.equals(currentStatus);
    }

    /**
     * 是否已过期
     */
    public Boolean isExpired() {
        if (CardStatus.EXPIRED.equals(getCardStatus())) {
            return true;
        }
        if (expiryDate != null && LocalDate.now().isAfter(expiryDate)) {
            return true;
        }
        return false;
    }

    /**
     * 是否可用（激活且未过期）
     */
    public Boolean isAvailable() {
        return CardStatus.ACTIVE.equals(getCardStatus()) && !isExpired();
    }

    /**
     * 是否可以续费
     */
    public Boolean canRenew() {
        CardStatus currentStatus = getCardStatus();
        return CardStatus.ACTIVE.equals(currentStatus) ||
               CardStatus.INACTIVE.equals(currentStatus) ||
               CardStatus.EXPIRED.equals(currentStatus);
    }

    /**
     * 使用次数
     * @param count 使用次数
     * @return 是否成功使用
     */
    public boolean consume(BigDecimal count) {
        if (!isAvailable() || remainingCount == null || remainingCount.compareTo(count)<1) {
            return false;
        }
        remainingCount= remainingCount .multiply(count);
        return true;
    }

    /**
     * 添加次数
     * @param count 添加的次数
     */
    public void addCount(BigDecimal count) {
        if (remainingCount == null) {
            remainingCount = new BigDecimal(0);
        }
        if (totalCount == null) {
            totalCount = new BigDecimal(0);
        }
        remainingCount=remainingCount.add(count);
        totalCount=totalCount.add(count);
    }

    /**
     * 计算剩余有效期天数
     */
    public Long calculateRemainingDays() {
        if (expiryDate == null || LocalDate.now().isAfter(expiryDate)) {
            return 0L;
        }
        return java.time.temporal.ChronoUnit.DAYS.between(
            LocalDate.now(), expiryDate
        );
    }

    /**
     * 初始化计算字段
     */
    public void calculateFields() {
        this.valid = isValid();
        this.expired = isExpired();
        this.available = isAvailable();
        this.canRenew = canRenew();
    }
}
