package cn.lihongjie.coal.meterDayLog.entity;

import cn.lihongjie.coal.base.entity.OrgCommonEntity;

import jakarta.persistence.Entity;
import jakarta.persistence.ManyToOne;

import lombok.Data;

import org.hibernate.annotations.Comment;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Subselect;

@Data
@Entity
@Subselect("""


select distinct on (DATE_TRUNC('day', time), meter_id, organization_id) id,
                                                                          create_time,
                                                                          create_user_id,
                                                                          file_ids,
                                                                          update_time,
                                                                          update_user_id,
                                                                          code,
                                                                          name,
                                                                          remarks,
                                                                          sort_key,
                                                                          status,
                                                                          organization_id,
                                                                          DATE_TRUNC('day', time) as time,
                                                                          value,
                                                                          meter_id
from t_meter_log

order by DATE_TRUNC('day', time), meter_id, organization_id, t_meter_log.time desc

""")

//@jakarta.persistence.Table(indexes = @jakarta.persistence.Index(name ="idx_meter_day_log_org_id", columnList = "organization_id"))

public class MeterDayLogEntity extends OrgCommonEntity {

    @ManyToOne
    private cn.lihongjie.coal.meter.entity.MeterEntity meter;

    @Comment("抄表月份")
    private java.time.LocalDate time;

    @Comment("抄表值")
    private java.lang.Double value;

    @Formula("( lag(value, 1, (select tm.init_value from t_meter tm where tm.id = meter_id)) over (partition by meter_id order by time asc ) )")
    private java.lang.Double previousValue;
    @Formula(" (round( ( value - ( lag(value, 1, (select tm.init_value from t_meter tm where tm.id = meter_id)) over (partition by meter_id order by time asc ) ) )::numeric, 2))")
    private java.lang.Double usage;
}