package com.ecep.contract.vm;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

import com.ecep.contract.model.Contract;
import com.ecep.contract.model.ContractPayPlan;

import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class ContractPayPlanViewModel extends IdentityViewModel<ContractPayPlan> {
    /**
     * 关联的合同对象
     */
    SimpleObjectProperty<Contract> contract = new SimpleObjectProperty<>();
    /**
     * 关联的用友系统中的数据ID
     */
    SimpleIntegerProperty refId = new SimpleIntegerProperty();

    SimpleObjectProperty<LocalDate> payDate = new SimpleObjectProperty<>();
    SimpleFloatProperty payRatio = new SimpleFloatProperty();
    SimpleDoubleProperty payCurrency = new SimpleDoubleProperty();
    SimpleObjectProperty<String> payTerm = new SimpleObjectProperty<>();

    SimpleObjectProperty<LocalDateTime> updateDate = new SimpleObjectProperty<>();

    @Override
    protected void updateFrom(ContractPayPlan v) {
        super.updateFrom(v);
        getContract().set(v.getContract());
        getRefId().set(v.getRefId());
        getPayDate().set(v.getPayDate());
        getPayRatio().set(v.getPayRatio());
        getPayCurrency().set(v.getPayCurrency());
        getPayTerm().set(v.getPayTerm());
        getUpdateDate().set(v.getUpdateDate());
    }

    @Override
    public boolean copyTo(ContractPayPlan v) {
        boolean modified = super.copyTo(v);
        if (!Objects.equals(contract.get(), v.getContract())) {
            v.setContract(contract.get());
            modified = true;
        }
        if (!Objects.equals(refId.get(), v.getRefId())) {
            v.setRefId(refId.get());
            modified = true;
        }
        if (!Objects.equals(payDate.get(), v.getPayDate())) {
            v.setPayDate(payDate.get());
            modified = true;
        }
        if (!doubleEquals(payRatio.get(), v.getPayRatio())) {
            v.setPayRatio(payRatio.get());
            modified = true;
        }
        if (!doubleEquals(payCurrency.get(), v.getPayCurrency())) {
            v.setPayCurrency(payCurrency.get());
            modified = true;
        }
        if (!Objects.equals(payTerm.get(), v.getPayTerm())) {
            v.setPayTerm(payTerm.get());
            modified = true;
        }
        return modified;
    }

    /**
     * 判断两个 double 值是否相等
     *
     * @param a a
     * @param b b
     * @return 在误差范围内是否相同
     */
    private boolean doubleEquals(double a, double b) {
        return Math.abs(a - b) < 0.0001;
    }
}
