import { getCurrentInstance, computed } from 'vue'
export const getPropArr = (val: any) => {
  if (typeof val !== 'string') {
    return ['']
  }
  return val.split('.')
}

// 取得当前item所属表单实例
export const getFormInstance = () => {
  let formItem = getCurrentInstance()
  while (formItem?.parent) {
    if (formItem.parent.type.name === 'ElForm') {
      return formItem.parent
    }
    formItem = formItem.parent
  }
  throw new Error('form不存在')
}

export function usePropBind() {
  const { control, prop, defaultPropValue } = <any>getCurrentInstance()?.attrs
  
  const { model } = <any>getFormInstance().props
  if (!model) {
    throw new Error('请为form绑定model属性')
  }
  const arr = getPropArr(prop)
  
  // 取得当前item绑定的表单值
  const propValue: any = computed(() => {
    let target = model
    for (let index = 0; index < arr.length; index++) {
      target = target[arr[index]]
      if (typeof target === 'undefined') break
    }
    return target
  })

  // 修改当前item绑定的表单值
  const handleChange = (value: any) => {
    let target = model;
    
    for (let index = 0; index < arr.length; index++) {
      const propValue = arr[index]
      if (index === arr.length - 1) {
        target[propValue] = value
        break
      }
      if (typeof model[propValue] === 'undefined') {
        target[propValue] = {}
      }
      target = model[propValue]
    }
  }
    
  return { propValue, handleChange }
}

export const LABEL_KEY = '[label]'
export const MIN_KEY = '[min]'
export const MAX_KEY = '[max]'
export const NUMBER_MIN = -999999999999999
export const NUMBER_MAX = 999999999999999

export const checkBoolean = (value: any) => typeof value === 'string' ? value.trim().toLowerCase() === 'true' : Boolean(value)

export const getDatePattern = (type: any) => {
  let pattern = 'YYYY-MM-DD HH:mm:ss'
  switch (type) {
    case 'date':
    case 'daterange':
      pattern = 'YYYY-MM-DD'
      break
    case 'month':
    case 'monthrange':
      pattern = 'YYYY-MM'
      break
    case 'year':
      pattern = 'YYYY'
      break
    default:
      break;
  }
  return pattern
}