import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import { isBoolean } from 'lodash';

// 约束电平状态类型
export type ConstraintLevel = 'high' | 'low' | 'undefined';

export const useConstraintsStore = defineStore('constraints', () => {

  // 约束状态存储
  const constraintStates = reactive<Record<string, ConstraintLevel>>({});

  // 约束颜色映射
  const constraintColors = {
    high: '#ff3333', // 高电平为红色
    low: '#3333ff',  // 低电平为蓝色
    undefined: '#999999' // 未定义为灰色
  };

  // 获取约束状态
  function getConstraintState(constraint: string): ConstraintLevel {
    if (!constraint) return 'undefined';
    return constraintStates[constraint] || 'undefined';
  }

  // 设置约束状态
  function setConstraintState(constraint: string, level: ConstraintLevel) {
    if (!constraint) return;
    constraintStates[constraint] = level;
  }

  // 批量设置约束状态
  function batchSetConstraintStates(states: Record<string, ConstraintLevel> | Record<string, boolean>) {
    // 收集发生变化的约束
    const changedConstraints: [string, ConstraintLevel][] = [];

    // 更新状态并收集变化
    Object.entries(states).forEach(([constraint, level]) => {
      if (isBoolean(level)) {
        level = level ? "high" : "low";
      }

      if (constraintStates[constraint] !== level) {
        constraintStates[constraint] = level;
        changedConstraints.push([constraint, level]);
      }
    });

    // 通知所有变化
    changedConstraints.forEach(([constraint, level]) => {
      stateChangeCallbacks.forEach(callback => callback(constraint, level));
    });
  }

  // 获取约束对应的颜色
  function getConstraintColor(constraint: string): string {
    const state = getConstraintState(constraint);
    return constraintColors[state];
  }

  // 清除所有约束状态
  function clearAllConstraintStates() {
    Object.keys(constraintStates).forEach(key => {
      delete constraintStates[key];
    });
  }

  // 获取所有约束状态
  function getAllConstraintStates(): Record<string, ConstraintLevel> {
    return { ...constraintStates };
  }

  // 注册约束状态变化回调
  const stateChangeCallbacks: ((constraint: string, level: ConstraintLevel) => void)[] = [];

  function onConstraintStateChange(callback: (constraint: string, level: ConstraintLevel) => void) {
    stateChangeCallbacks.push(callback);
    return () => {
      const index = stateChangeCallbacks.indexOf(callback);
      if (index > -1) {
        stateChangeCallbacks.splice(index, 1);
      }
    };
  }

  // 触发约束变化
  function notifyConstraintChange(constraint: string, level: ConstraintLevel) {
    setConstraintState(constraint, level);
    stateChangeCallbacks.forEach(callback => callback(constraint, level));
  }

  return {
    getConstraintState,
    setConstraintState,
    batchSetConstraintStates,
    getConstraintColor,
    clearAllConstraintStates,
    getAllConstraintStates,
    onConstraintStateChange,
    notifyConstraintChange,
  }
})

