package com.yhy.module.core.dal.dataobject.workbench;

import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.yhy.module.core.dal.typehandler.PostgreSQLJsonbTypeHandler;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 * 单位工程信息 DO
 *
 * @author yhy
 */
@TableName(value = "yhy_wb_unit_info", autoResultMap = true)
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WbUnitInfoDO extends BaseDO {

    /**
     * 主键ID
     */
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;

    /**
     * 租户ID
     */
    private Long tenantId;

    /**
     * 关联编制树节点ID（单位工程节点）
     */
    private Long compileTreeId;

    /**
     * 工程编号（项目范围内唯一）
     */
    private String unitCode;

    /**
     * 工程名称
     */
    private String unitName;

    /**
     * 专业类别（字典：wb_specialty_type）
     */
    private String specialtyType;

    /**
     * 库类别（字典：wb_library_type）
     */
    private String libraryType;

    /**
     * 清单数据库（清单目录树ID）
     */
    private Long boqCatalogItemId;

    /**
     * 定额数据库（定额专业树ID）
     */
    private Long quotaCatalogItemId;

    /**
     * 执行费率文件（费率模式节点ID）
     */
    private Long rateModeId;

    /**
     * 建设规模（字典：wb_construction_scale）
     */
    private String constructionScale;

    /**
     * 配置快照（预留）
     */
    @TableField(typeHandler = PostgreSQLJsonbTypeHandler.class)
    private Map<String, Object> configSnapshot;

    /**
     * 扩展属性（JSONB）
     */
    @TableField(typeHandler = PostgreSQLJsonbTypeHandler.class)
    private Map<String, Object> attributes;

    // attributes 中的 key 常量
    public static final String ATTR_RATE_MODE_BINDINGS = "rateModeBindings";
    public static final String ATTR_LAST_SELECTED_QUOTA_SPECIALTY = "lastSelectedQuotaSpecialty";

    /**
     * 获取费率模式绑定Map
     * 格式: { "定额专业ID": { "rateModeId": 123, "rateModeName": "xxx", "quotaSpecialtyName": "xxx" } }
     */
    @SuppressWarnings("unchecked")
    public Map<String, Map<String, Object>> getRateModeBindings() {
        if (attributes == null) {
            return new java.util.HashMap<>();
        }
        Object bindings = attributes.get(ATTR_RATE_MODE_BINDINGS);
        if (bindings instanceof Map) {
            return (Map<String, Map<String, Object>>) bindings;
        }
        return new java.util.HashMap<>();
    }

    /**
     * 设置费率模式绑定Map
     */
    public void setRateModeBindings(Map<String, Map<String, Object>> rateModeBindings) {
        if (attributes == null) {
            attributes = new java.util.HashMap<>();
        }
        attributes.put(ATTR_RATE_MODE_BINDINGS, rateModeBindings);
    }

    /**
     * 获取指定定额专业的费率模式ID
     * @param quotaCatalogItemId 定额专业ID
     * @return 费率模式ID，如果未绑定返回null
     */
    public Long getRateModeIdByQuotaSpecialty(Long quotaCatalogItemId) {
        Map<String, Map<String, Object>> bindings = getRateModeBindings();
        Map<String, Object> binding = bindings.get(String.valueOf(quotaCatalogItemId));
        if (binding != null && binding.get("rateModeId") != null) {
            Object rateModeIdObj = binding.get("rateModeId");
            if (rateModeIdObj instanceof Number) {
                return ((Number) rateModeIdObj).longValue();
            }
            if (rateModeIdObj instanceof String) {
                return Long.parseLong((String) rateModeIdObj);
            }
        }
        return null;
    }

    /**
     * 绑定定额专业的费率模式
     * @param quotaCatalogItemId 定额专业ID
     * @param rateModeId 费率模式ID
     * @param rateModeName 费率模式名称（快照用）
     * @param quotaSpecialtyName 定额专业名称（快照用）
     */
    public void bindRateMode(Long quotaCatalogItemId, Long rateModeId, String rateModeName, String quotaSpecialtyName) {
        Map<String, Map<String, Object>> bindings = getRateModeBindings();
        Map<String, Object> binding = bindings.getOrDefault(String.valueOf(quotaCatalogItemId), new java.util.HashMap<>());
        // 使用字符串存储大整数ID，避免JavaScript精度丢失
        binding.put("rateModeId", String.valueOf(rateModeId));
        binding.put("rateModeName", rateModeName);
        binding.put("quotaSpecialtyName", quotaSpecialtyName);
        binding.put("bindTime", java.time.LocalDateTime.now().toString());
        bindings.put(String.valueOf(quotaCatalogItemId), binding);
        setRateModeBindings(bindings);
    }

    /**
     * 获取指定定额专业的完整绑定信息
     * @param quotaCatalogItemId 定额专业ID
     * @return 绑定信息Map，如果未绑定返回null
     */
    public Map<String, Object> getRateModeBinding(Long quotaCatalogItemId) {
        Map<String, Map<String, Object>> bindings = getRateModeBindings();
        return bindings.get(String.valueOf(quotaCatalogItemId));
    }

    /**
     * 保存费率覆写值
     * @param quotaCatalogItemId 定额专业ID
     * @param rateSettings 费率覆写值 { "rateItemId": { "fieldIndex": "value" } }
     */
    public void saveRateSettings(Long quotaCatalogItemId, Map<String, Object> rateSettings) {
        Map<String, Map<String, Object>> bindings = getRateModeBindings();
        Map<String, Object> binding = bindings.getOrDefault(String.valueOf(quotaCatalogItemId), new java.util.HashMap<>());
        binding.put("rateSettings", rateSettings);
        bindings.put(String.valueOf(quotaCatalogItemId), binding);
        setRateModeBindings(bindings);
    }

    /**
     * 保存取费覆写值
     * @param quotaCatalogItemId 定额专业ID
     * @param feeSettings 取费覆写值 { "feeItemId": { "name": "xxx", ... } }
     */
    public void saveFeeSettings(Long quotaCatalogItemId, Map<String, Object> feeSettings) {
        Map<String, Map<String, Object>> bindings = getRateModeBindings();
        Map<String, Object> binding = bindings.getOrDefault(String.valueOf(quotaCatalogItemId), new java.util.HashMap<>());
        binding.put("feeSettings", feeSettings);
        bindings.put(String.valueOf(quotaCatalogItemId), binding);
        setRateModeBindings(bindings);
    }

    /**
     * 获取费率覆写值
     * @param quotaCatalogItemId 定额专业ID
     * @return 费率覆写值Map
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getRateSettings(Long quotaCatalogItemId) {
        Map<String, Object> binding = getRateModeBinding(quotaCatalogItemId);
        if (binding != null && binding.get("rateSettings") instanceof Map) {
            return (Map<String, Object>) binding.get("rateSettings");
        }
        return new java.util.HashMap<>();
    }

    /**
     * 获取取费覆写值
     * @param quotaCatalogItemId 定额专业ID
     * @return 取费覆写值Map
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getFeeSettings(Long quotaCatalogItemId) {
        Map<String, Object> binding = getRateModeBinding(quotaCatalogItemId);
        if (binding != null && binding.get("feeSettings") instanceof Map) {
            return (Map<String, Object>) binding.get("feeSettings");
        }
        return new java.util.HashMap<>();
    }

    /**
     * 获取用户上次选择的定额专业ID
     * @return 定额专业ID，如果未设置返回null
     */
    public Long getLastSelectedQuotaSpecialty() {
        if (attributes == null) {
            return null;
        }
        Object value = attributes.get(ATTR_LAST_SELECTED_QUOTA_SPECIALTY);
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof String) {
            try {
                return Long.parseLong((String) value);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 设置用户上次选择的定额专业ID
     * @param quotaCatalogItemId 定额专业ID
     */
    public void setLastSelectedQuotaSpecialty(Long quotaCatalogItemId) {
        if (attributes == null) {
            attributes = new java.util.HashMap<>();
        }
        // 使用字符串存储，避免大整数精度丢失
        attributes.put(ATTR_LAST_SELECTED_QUOTA_SPECIALTY, quotaCatalogItemId != null ? String.valueOf(quotaCatalogItemId) : null);
    }
}
