import extraParas from '../../config'
import zhCN from 'ant-design-vue/es/locale/zh_CN'
import styles from './index.module.scss'
import DynamicForm from '../DynamicForm'
import StaticForm from '../StaticForm'

export default {
  extraParas,
  name: 'CustomForm',
  components: {
    DynamicForm,
    StaticForm
  },
  props: {
    value: Array
  },
  data() {
    return {
      form: {},
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    }
  },
  methods: {
    async submit() {
      return new Promise((reslove, reject) => {
        this.$refs.dynamic.$refs.form.validate(valid => {
          if (valid) {
            reslove({...this.form})
          } else {
            reject('表单校验失败')
          }
        })
      })
    }
  },
  mounted() {
    const configured = this.value || []
    const configuredForm = configured.reduce((form, cur) => {
      form[cur.name] = cur.defaultValue
      return form
    }, {})
    extraParas.forEach(({ name, defaultValue, config = {} }) => {
      let val = (name in configuredForm) ? configuredForm[name] : defaultValue
      if (config.type === 'MultiSelect' || config.type === 'CheckBox') {
        let selected = []
        try {
          selected = JSON.parse(val)
        } catch(e) {}
        this.$set(this.form, name, selected)
      } else {
        this.$set(this.form, name, val)
      }
    })
  },
  render() {
    return (
      <a-config-provider locale={zhCN}>
        <div class={styles.customForm}>
          {/* 动态表单 */}
          <DynamicForm paras={extraParas} form={this.form} ref="dynamic" />
          {/* 静态表单，可手动定义表单样式 */}
          {/* <StaticForm form={this.form} ref="form" /> */}
        </div>
      </a-config-provider>
    )
  }
}