// 阀门、泵、传感器的状态判断逻辑
import { unref } from 'vue'

export function useValveHelper(valveArrRef) {
  // 兼容 ref/reactive/普通数组
  const getArr = () => Array.isArray(unref(valveArrRef)) ? unref(valveArrRef) : [];

  // 获取某个设备的数据数组(泵、阀门、传感器)
  const getDataArrByCode = (code) => {
    if (!code || typeof code !== 'string') return [];

    const valveList = getArr();
    if (!Array.isArray(valveList)) return [];

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

    return valve?.value || [];
  };

  // 检查某个 设备 是否存在
  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]);
      return isDeviceOpen(matched)
    } 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(isDeviceOpen);
    }
  };

  //阀门或逻辑判断
  const getValveOrStatus = (...codes) => {
    const arr = getArr();
    if (codes.length === 1) {
      return arr.some(item => item.code === codes[0] && isDeviceOpen(item));
    } else {
      const codeSet = new Set(codes);
      return arr.some(item => codeSet.has(item.code) && isDeviceOpen(item));
    }
  };

  // 单个阀门或泵状态判断
  const isDeviceOpen = (device) => {
    if (!device || !device.code || !device.value) return false;

    const firstVal = device.value[0];

    if (typeof firstVal === 'boolean') return firstVal; // 阀门
    if (typeof firstVal === 'number') return firstVal === 1; // 泵

    return false;
  };


  // json 条件判断  未设条件的话返回result默认值
  const evaluateCondition = (condition, result = false) => {
    // 尝试解析 JSON 字符串为对象
    if (typeof condition === 'string') {
      try {
        condition = JSON.parse(condition);
      } catch (e) {
        console.error('条件 JSON 解析失败:', e);
        return false;
      }
    }
    if (!condition || typeof condition !== 'object') return false;

    const operator = condition.operator;
    const conditions = condition.conditions;

    if (!Array.isArray(conditions) || !operator || conditions.length === 0) return result;

    const results = conditions.map(cond => {
      if (cond.type === 'group') {
        // 第二层 group（实际判断层）
        const itemCodes = cond.conditions
          .filter(c => c.type === 'item')
          .map(c => c.code);

        if (cond.operator === 'AND') {
          return getValveAndStatus(...itemCodes);
        } else if (cond.operator === 'OR') {
          return getValveOrStatus(...itemCodes);
        } else {
          return false;
        }
      } else {
        // 顶层不允许出现 item
        return false;
      }
    });

    // 最外层计算结果
    if (operator === 'AND') {
      return results.every(Boolean);
    } else if (operator === 'OR') {
      return results.some(Boolean);
    }

    return false;
  }

  // 获取管道种类
  const getPipeType = (dynamicPipelineCondition) => {
    // 如果是字符串，先解析 JSON
    if (typeof dynamicPipelineCondition === 'string') {
      try {
        dynamicPipelineCondition = JSON.parse(dynamicPipelineCondition);
      } catch (e) {
        console.error('dynamicPipelineCondition JSON 解析失败:', e);
        return null;
      }
    }

    if (!Array.isArray(dynamicPipelineCondition)) return null;

    for (const item of dynamicPipelineCondition) {
      const { class: pipeClass, operator, conditions } = item;

      if (!pipeClass || !operator || !Array.isArray(conditions)) continue;

      // 封装为一个完整的 condition 对象
      const conditionGroup = {
        operator,
        conditions
      };

      // 如果当前条件成立，返回该类名
      if (evaluateCondition(conditionGroup)) {
        return pipeClass;
      }
    }

    return null; // 无匹配
  }



  return {
    hasValve,
    getValveStatusArr,
    getValveAndStatus,//阀门与逻辑判断
    getValveOrStatus,//阀门或逻辑判断
    getDataArrByCode,//获取某个设备的数据数组
    evaluateCondition,//json条件判断
    getPipeType,//获取管道种类
  }
}
