/*
 * @Author: donghao donghao@supervision.ltd
 * @Date: 2025-07-31 10:03:44
 * @LastEditors: donghao donghao@supervision.ltd
 * @LastEditTime: 2025-08-01 17:04:27
 * @FilePath: \Robot-Al-Platform-Web\src\renderer\src\components\Form\formList.tsx
 * @Description: 定义 formList 组件
 */
//
import { defineComponent, getCurrentInstance, ComputedRef, computed, toRaw } from 'vue'
import type { FormTypes } from '@wocwin/t-ui-plus'
import { TForm } from '@wocwin/t-ui-plus'
import { ElMessage } from 'element-plus'
import { generateId } from '@/utils/plugins/random'
import { DSAddItemButton } from '@/components/Button'
import { Delete } from '@element-plus/icons-vue'

// 定义组件属性类型（保留所有 ElInputNumber 属性）
type DSFormListProps = {
  formConfig: FormTypes
  prefixRender?: (...ags: any[]) => any // 前置内容 render渲染
  suffixRender?: (...ags: any[]) => any // 后置内容 render渲染
  min?: number
  max?: number
}

export default defineComponent({
  name: 'DSFormList',
  props: {
    formConfig: {
      type: Object as FormTypes,
      default: {}
    },
    modelValue: {
      type: Array,
      default: () => []
    },
    min: {
      type: Number,
      default: 0
    },
    max: {
      type: Number,
      default: Infinity
    }
  },
  emits: ['update:modelValue'],
  setup(props: DSFormListProps, { emit, slots, attrs }) {
    const tFormAttrs = (index) => {
      const { formConfig, ...propsRest } = props
      const refId = formConfig.ref + index
      const finalOpts = {
        ...formConfig,
        ref: refId,
        modelValue: refId,
        formData: props.modelValue[index]
      }
      return { ...finalOpts, formOpts: finalOpts }
    }

    const addItem = () => {
      const list = props.modelValue
      if (list.length >= props.max) {
        ElMessage.warning(`最多只能添加 ${props.max} 项`)
        return
      }
      list.push({ formItemsUuid: generateId() })
      emit(
        'update:modelValue',
        list.map(({ formItemsUuid, ...rest }) => rest)
      )
    }

    const removeItem = (formItem, index) => {
      const list = props.modelValue
      if (list.length <= props.min) {
        ElMessage.warning(`至少需要保留 ${props.min} 项`)
        return
      }
      console.log('removeItem', formItem, index)
      list.splice(index, 1)
      emit('update:modelValue', list)
    }

    const moveItem = (index, direction) => {
      const list = props.modelValue
      if (
        (direction === 'up' && index === 0) ||
        (direction === 'down' && index === list.length - 1)
      ) {
        return
      }

      const newIndex = direction === 'up' ? index - 1 : index + 1
      const item = list.splice(index, 1)[0]
      list.splice(newIndex, 0, item)
      emit('update:modelValue', list)
    }
    // const canAdd = list.length < props.max
    // const canRemove = list.length > props.min
    // 渲染自定义前缀内容
    const renderPrefix = (formItem, index) => {
      // props?.suffixRender &&
      if (props.prefixRender) {
        return props?.prefixRender?.()
      }
      return (
        <div className="flex items-center">
          <span>
            {props.formConfig?.title}
            {Number(index) + 1}
          </span>
          <div
            onClick={() => removeItem(formItem, index)}
            class="flex items-center justify-center ds-dialog-formList-delete"
          >
            <Delete />
          </div>
        </div>
      )
    }
    return () => (
      <div class="ds-form-list-comp">
        <ul class="form-list">
          {props.modelValue
            .map((item) => ({
              ...item,
              formItemsUuid: item?.id || generateId()
            }))
            .map((formItem, index) => (
              <li class="form-item-card" key={formItem.formItemsUuid}>
                {renderPrefix(formItem, index)}
                <TForm className="ds-form-list-comp-form" {...tFormAttrs(index)}></TForm>
              </li>
            ))}
        </ul>
        <DSAddItemButton {...tFormAttrs.value} onClick={() => addItem()}></DSAddItemButton>
      </div>
    )
  }
})
