// src/hooks/useValveHelper.js
import { unref } from 'vue'

export function useValveHelper(valveArrRef) {
  // 兼容 ref/reactive/普通数组
  const getArr = () => unref(valveArrRef)

  const hasValve = (code) => {
    // 检查 code 是否有效
    if (!code || typeof code !== 'string') return false;

    return getArr().some(v => {
      const vCode = v?.code;
      return typeof vCode === 'string' && vCode.toUpperCase() === code.toUpperCase();
    });
  }

  const getValveStatusArr = (code) => {
    // 检查 code 是否有效
    if (!code || typeof code !== 'string') return [];

    const valve = getArr().find(v => {
      const vCode = v?.code;
      return typeof vCode === 'string' && vCode.toUpperCase() === code.toUpperCase();
    });

    return valve?.value || [];
  }


  const getValveAndStatus = (...codes) => {
    const arr = getArr();

    if (codes.length === 1) {
      const matched = arr.find(item => item.code === codes[0]);
      if (!matched) return false; // 没匹配到
      return matched.value?.[0] === true;
    } else {
      const codeSet = new Set(codes);
      const matched = arr.filter(item => codeSet.has(item.code));

      if (matched.length !== codes.length) {
        return false; // 有 code 没匹配到
      }
      return matched.every(item => item.value?.[0] === true);
    }
  };


  const getValveOrStatus = (...codes) => {
    const arr = getArr();
    if (codes.length === 1) {
      return arr.some(item => item.code === codes[0] && item.value?.[0] === true);
    } else {
      const codeSet = new Set(codes);
      return arr.some(item => codeSet.has(item.code) && item.value?.[0] === true);
    }
  };

  // 获取某个 设备 的数据数组
  const getDataArrByCode = (code) => {
    // 检查 code 是否有效
    if (!code || typeof code !== 'string') return [];

    const valve = getArr().find(v => {
      const vCode = v?.code;
      return typeof vCode === 'string' && vCode.toUpperCase() === code.toUpperCase();
    });

    return valve?.value || [];
  }


  return {
    hasValve,
    getValveStatusArr,
    getValveAndStatus,
    getValveOrStatus,
    getDataArrByCode
  }
}
