import { defineAsyncComponent } from 'vue'
import { formInputProps, fromInputEmits } from '@cip/components/cip-form-input/form-input-props'
import { useFormInput, useElementFormEvent } from '@cip/components/hooks/form-input'
import CipButtonText from '@cip/components/cip-button-text'
import './mobile.less'
const CipFormItem = defineAsyncComponent(() => import('../../../cip-form-item'))
export default {
  props: formInputProps,
  emits: [...fromInputEmits],
  setup (props, context) {
    const { handleChange } = useElementFormEvent()
    const formInput = useFormInput(props, context)
    const { securityConfig, emitModelValue } = formInput
    const updateModelValue = (val, index) => {
      const data = props.modelValue
      data[index] = val
      emitModelValue(data)
    }
    const addItem = () => {
      const val = Array.isArray(props.modelValue) ? props.modelValue : []
      val.push({})
      handleChange(val)
      emitModelValue(val)
    }

    return () => <div class={'basic-table__mobile'}>
      {
        (props.modelValue || []).map((row, rowIndex) =>
          <div>
            <div>{rowIndex + 1}</div>
            {securityConfig.value.options.map((option, optionIndex) => {
              const inputConfig = { ...option.config }
              inputConfig.width = '100%'
              inputConfig.ruleKey = `${props.fieldKey}.${rowIndex}.${option.key}`
              return <CipFormItem
                key={`${rowIndex}-${optionIndex}`}
                model={row}
                fieldKey={option.key}
                config={inputConfig}
                inTable={true}
                tableData={props.modelValue}
                tableDependOnValues={props.dependOnValues}
                onUpdate:model={(val) => {
                  row = val
                  updateModelValue(val, rowIndex)
                }}
              />
            })}
          </div>
        )
      }
      <CipButtonText size="large" onClick={() => addItem()}>
        <i class="el-icon-circle-plus create-handle"/>
      </CipButtonText>
    </div>
  }
}
