import type { VxeFormEventProps, VxeFormProps, VxeModalProps } from 'vxe-pc-ui'
import type { VxeGridEventProps, VxeGridProps } from 'vxe-table'

import { BasicService } from '#/api/service/basic'

export const mj_form_input = 'mj-form-input'
export const mj_form_target = 'mj-form-target'
export const mj_form_textarea = 'VxeTextarea'
export const mj_form_switch = 'VxeSwitch'
export const mj_form_select = 'VxeSelect'
export const mj_form_tree_select = 'VxeTreeSelect'
export const mj_form_date = 'VxeDatePicker'
export const mj_form_date_range = 'VxeDateRangePicker'
export const mj_form_button_group = 'VxeButtonGroup'
export const mj_form_radio_group = 'VxeRadioGroup'
export const mj_form_checkbox_group = 'VxeCheckboxGroup'
export const mj_table_select = 'mj-table-select'
export const mj_form_text = 'mj-form-text'
export const mj_form_money = 'mj-form-money'
export const mj_form_phone = 'mj-form-phone'
export const mj_form_image = 'mj-form-image'
export const mj_form_upload = 'mj-form-upload'

export const mj_action_add = 1
export const mj_action_update = 2
export const mj_action_remove = 3

export const mj_empty_data = -100

export type MjFormProps = VxeFormProps
export type MjFormEventProps = VxeFormEventProps
export type MjGridProps = VxeGridProps & {
  afterLoadData?: (data: any) => any
  afterReset?: () => void
  beforeLoadData?: (params: any) => any
  beforeRemove?: (rows: any) => any
  disableEdit?: (row: any) => boolean
}
export type MjGridEventProps = VxeGridEventProps
export type MjModalProps = VxeModalProps
export type MjEditFormProps = {
  // 添加时的过滤字段
  addFields?: string[]
  addForm?: MjFormProps
  beforeEditFormShow?: (data: any, edit: boolean) => any
  beforeReset?: (data: any) => any
  beforeSaveOrUpdate?: (data: any) => any
  defaultFormData?: any
  form: MjFormProps
  modal?: MjModalProps
  onEditFormHide?: (edit: boolean) => void
  updateFields?: string[]
  updateForm?: MjFormProps
}

export type SelectedItems = {
  // 最新的一条item
  item: any
  items: any[]
}

export type MjTableProps = {
  addButtonText?: string
  deleteButtonText?: string
  editForm?: MjEditFormProps
  grid: MjGridProps
  gridEvents?: MjGridEventProps
  hideAdd?: boolean
  hideEdit?: boolean
  hideRemove?: boolean
  hideSearch?: boolean
  hideToolbar?: boolean
  multiSelectable?: boolean
  searchForm?: MjFormProps
  searchParams?: any
  selectable?: boolean
  selectedItems?: SelectedItems
  service: BasicService
}

// 调用自定义表单控件的reset方法
export function resetSelfItems(items: any[], oldData: any, newData: any) {
  for (const item of items) {
    if (item.children?.length) {
      // 如果有子item
      resetSelfItems(item.children, oldData, newData)
      continue
    }
    const props = item.itemRender?.props
    // 不存在属性，或者被禁用，直接跳过
    if (!props) continue
    if (props.disabled) {
      // 禁用的，保持之前的值
      const f = item.field as any
      newData[f] = oldData[f]
      continue
    }
    props._methods?.reset?.()
  }
}
