package com.unibuy.smartdevice.structure;

import org.json.JSONObject;

public class SlotStructure {
    private int field;
    private int slot;
    private ProductStructure product;
    private int count;
    private boolean lock;
    private int secord;
    private JSONObject otherData;
    public int cartSelectedCount;// 本地欄位：購物車已選數量（General flavor 多品項購物車使用）

    // ── 雙向 LWW 同步序號（per-field）──
    // rev：店員在貨道管理「存檔且實際變更」時才遞增；synced_rev：已被後台確認(B009 成功/下行採用)的 rev。
    // rev > synced_rev = 有未上報的現場編輯 → 收到下行時該欄位拒絕被覆蓋。
    // 注意：出貨扣到 0 的 clearExpiry / 自動扣庫存 / 一鍵補貨「不可」遞增 rev。
    private int lockRev;
    private int lockSyncedRev;
    private int expiryRev;
    private int expirySyncedRev;

    /*
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("key", apiKey);
        jsonObject.put("machine", MachineName);
        jsonObject.put("tid", trackID + "");
        jsonObject.put(TPDNetworkConstants.ARG_SAMSUNG_PAY_PRIME_TYPE, type);
        String receive = DoPut(DomainName + "products/exp/B025", jsonObject.toString());
     */

    public SlotStructure(int field, int slot, ProductStructure product, int count, boolean lock, JSONObject otherData) {
        this.field = field;
        this.slot = slot;
        this.product = product;
        this.count = count;
        this.lock = lock;
        this.secord = 0;
        this.otherData = otherData;
    }

    @Override
    public String toString() {
        return "SlotStructure{" +
                "field=" + field +
                ", slot=" + slot +
                ", product=" + (product != null ? product.toString() : "null") +
                ", count=" + count +
                ", lock=" + lock +
                ", secord=" + secord +
                ", otherData=" + (otherData != null ? otherData.toString() : "{}") +
                '}';
    }

    public SlotStructure(int field, int slot, ProductStructure product, int count, boolean lock) {
        this(field, slot, product, count, lock, new JSONObject());
    }

    public SlotStructure(int field, int slot, ProductStructure product, int count) {
        this(field, slot, product, count, false, new JSONObject());
    }

    public int getField() {
        return field;
    }

    public void setField(int field) {
        this.field = field;
    }

    public int getSlot() {
        return this.slot;
    }
    public void setSlot(int slot) {
        this.slot = slot;
    }

    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }

    public boolean isLock() {
        return lock;
    }
    public void setLock(boolean lock) {
        this.lock = lock;
    }

    public int getSecord() {
        return secord;
    }

    public void setSecord(int secord) {
        this.secord = secord;
    }

    public ProductStructure getProduct() {
        return this.product;
    }
    public void setProduct(ProductStructure product) {
        this.product = product;
    }

    public JSONObject getOtherData() {
        return otherData;
    }

    /**
     * 效期是否已過期（後台庫存同步透過 otherData.expiry_date 下發，格式 "yyyy-MM-dd"）。
     * 規則：當天仍可販售，今天 > 效期日（即隔天起）才視為過期。
     * 採 ISO 日期字串字典序比對（等同時間序），避開時區／解析誤差。
     * 失敗時 fail-open 回傳 false（不擋售），避免時鐘或資料異常誤鎖全機。
     */
    public boolean isExpired() {
        if (otherData == null || !otherData.has("expiry_date"))
            return false;
        try {
            String expiry = otherData.getString("expiry_date");
            if (expiry == null || expiry.isEmpty() || "null".equalsIgnoreCase(expiry))
                return false;
            // 僅取日期部分 yyyy-MM-dd（即使後台帶了時間也安全）
            String expiryDate = expiry.length() >= 10 ? expiry.substring(0, 10) : expiry;
            String today = new java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
                    .format(new java.util.Date());
            return today.compareTo(expiryDate) > 0;
        } catch (Exception e) {
            return false;
        }
    }

    public void setOtherData(JSONObject otherData) {
        this.otherData = otherData;
    }

    /**
     * 取得效期字串（yyyy-MM-dd），無設定時回傳空字串。供貨道管理 UI 顯示用。
     */
    public String getExpiryDate() {
        if (otherData == null || !otherData.has("expiry_date"))
            return "";
        try {
            String expiry = otherData.getString("expiry_date");
            if (expiry == null || "null".equalsIgnoreCase(expiry))
                return "";
            return expiry.length() >= 10 ? expiry.substring(0, 10) : expiry;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 清除效期與批號。通常在貨道庫存歸 0（賣完）時呼叫，避免舊批貨效期殘留，
     * 導致下次本機補新貨時被舊效期誤鎖成「暫不販售」。
     * 注意：這是「自動」清除，呼叫端不可遞增 expiryRev（否則賣完會把後台預設的下批效期洗掉）。
     */
    public void clearExpiry() {
        if (otherData == null)
            return;
        otherData.remove("expiry_date");
        otherData.remove("batch_no");
    }

    /** 批號（otherData.batch_no），無則回空字串。 */
    public String getBatchNo() {
        if (otherData == null || !otherData.has("batch_no"))
            return "";
        try {
            String b = otherData.getString("batch_no");
            return (b == null || "null".equalsIgnoreCase(b)) ? "" : b;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 設定效期字串（yyyy-MM-dd）。供貨道管理 UI 編輯用；空字串/null 代表清除（無效期管控）。
     * 不在此遞增 rev —— rev 由 saveData 與 baseline 比對後統一遞增。
     */
    public void setExpiryDate(String expiry) {
        if (otherData == null)
            otherData = new JSONObject();
        try {
            if (expiry == null || expiry.trim().isEmpty()) {
                otherData.remove("expiry_date");
            } else {
                otherData.put("expiry_date", expiry.trim());
            }
        } catch (Exception ignored) {
        }
    }

    public int getLockRev() { return lockRev; }
    public void setLockRev(int lockRev) { this.lockRev = lockRev; }
    public int getLockSyncedRev() { return lockSyncedRev; }
    public void setLockSyncedRev(int lockSyncedRev) { this.lockSyncedRev = lockSyncedRev; }
    public int getExpiryRev() { return expiryRev; }
    public void setExpiryRev(int expiryRev) { this.expiryRev = expiryRev; }
    public int getExpirySyncedRev() { return expirySyncedRev; }
    public void setExpirySyncedRev(int expirySyncedRev) { this.expirySyncedRev = expirySyncedRev; }
}
