package com.example.cattletends.entity;

import javax.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 牛只数据实体类
 */
@Entity
@Table(name = "cattleData", indexes = {
    @Index(name = "idx_price", columnList = "price"),
    @Index(name = "idx_type", columnList = "type"),
    @Index(name = "idx_province", columnList = "province"),
    @Index(name = "idx_type_price", columnList = "type,price"),
    @Index(name = "idx_province_price", columnList = "province,price"),
    @Index(name = "idx_type_province_location_price", columnList = "type,province,location,price")
})
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CattleData {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    private Integer id;

    /**
     * 创建时间
     */
    @Column(name = "create_time")
    private LocalDateTime createTime;

    /**
     * 品种
     */
    @Column(name = "type", length = 255)
    private String type;

    /**
     * 省份
     */
    @Column(name = "province", length = 255, nullable = false)
    private String province;

    /**
     * 所在产地
     */
    @Column(name = "location", length = 255)
    private String location;

    /**
     * 价格(元/斤)
     */
    @Column(name = "price", precision = 10, scale = 2)
    private BigDecimal price;

    /**
     * 更新时间
     */
    @Column(name = "up_time", nullable = false)
    private LocalDateTime upTime;

    /**
     * 保存前自动设置创建时间和更新时间
     */
    @PrePersist
    protected void onCreate() {
        LocalDateTime now = LocalDateTime.now();
        if (createTime == null) {
            createTime = now;
        }
        if (upTime == null) {
            upTime = now;
        }
    }

    /**
     * 更新前自动设置更新时间
     */
    @PreUpdate
    protected void onUpdate() {
        upTime = LocalDateTime.now();
    }
}

