import {LOGIC_TYPE} from "../app/pages/IndexDefine/constants";

/**
 * 将数组转换为树形结构
 */
export function listTools({
  array,
  parentKey = "pId",      // 注入额外的父ID
  titleKey = "label",     // 注入额外的title
  valueKey = "value",     // 注入额外的value
  typeEnum,
  getLeaf = true          // 过滤所有的子节点
}) {
  /**
   * 将数组转换为树形结构
   */
  function loop(array,item,parentKey,titleKey,valueKey,getLeaf) {
    const {id}=item
    let map = {
      ...item,
      key:item.id,
      title:item.name,
      [parentKey]:item.parentId,
      [titleKey]:item.name,
      [valueKey]:item.id,
      description:item.description,
      typeEnum:typeEnum,
      children: []
    }

    let children =[]
    for (const row of array){
      const isChildren = array.findIndex(e=>e.parentId===row.id)
      if (!getLeaf&&isChildren===-1){
        // 过滤掉所有叶子节点
        continue
      }
      if (row.parentId===id){
        children.push(loop(array,row,parentKey,titleKey,valueKey,getLeaf))
      }
    }

    // 当再也没有子节点时，注入isLeaf节点
    if (getLeaf && item.parentId!==0 && children.length===0){
      map.isLeaf=getLeaf
    }

    map.children=children
    return map
  }

  let tree = []
  for (const item of array) {
    const {parentId}=item
    if (parentId===0){
      tree.push(loop(array,item,parentKey,titleKey,valueKey,getLeaf))
    }
  }
  return tree
}

/**
 * 将数组分为两两一组
 */
export function splitArray(options,col=2) {
  let arr = [];
  let item = []
  for(let i=1;i<options.length+1;i++){
    if (i%col===1){
      item.push(options[i-1])
    }else if(i%col===0){
      item.push(options[i-1])
      arr.push(item)
      item=[]
    }
    if (i===options.length){
      arr.push(item)
    }
  }
  return arr
}

/** 业务限定配置转SQL*/
export function bizConditionToSQL(attributes) {
  let defaultConfig = "";
  if (attributes){
    for (let i = attributes.length - 1; i >= 0; i--) {
      const {value,operator,bizName,relation} = attributes[i];
      if (bizName && operator && value){
        const cdt = attributes.length>1&&relation?relation:""
        if (LOGIC_TYPE[operator]==="包含" || LOGIC_TYPE[operator]==="不包含"){
          defaultConfig +=` ${cdt} ${bizName} ${operator} '%${value}%'`
          continue
        }
        if (LOGIC_TYPE[operator]==="为空"||LOGIC_TYPE[operator]==="不为空"){
          defaultConfig +=` ${cdt} ${bizName} ${operator}`
          continue
        }
        if (LOGIC_TYPE[operator]==="之内"||LOGIC_TYPE[operator]==="之外"){
          defaultConfig +=` ${cdt} ${bizName} ${operator} (${value})`
          continue
        }
        defaultConfig +=` ${cdt} ${bizName} ${operator} ${value} `
      }
    }
  }
  return defaultConfig
}