import { ElMessage } from 'element-plus'
import type { Ref } from 'vue'

interface EditTableRow {
  key: string
  isEdit?: boolean
}

export function useEditTable<T extends EditTableRow>(arr: Ref<Array<T>>) {
  function edit(index: number) {
    arr.value[index].isEdit = true
  }

  function cancel(index: number) {
    const row = arr.value[index]
    if (row.key) {
      row.isEdit = false
      return
    }
    arr.value.splice(index, 1)
  }

  function create() {
    arr.value.unshift({ key: '', isEdit: true } as T)
  }

  function del(index: number) {
    arr.value.splice(index, 1)
  }

  function save(index: number) {
    const row = arr.value[index]
    if (!row.key) {
      ElMessage.error('请输入key再保存')
      return
    }
    row.isEdit = false
  }
  return {
    edit,
    cancel,
    del,
    save,
    create
  }
}
