<template>
  <cms-edit-form
    ref="extendTemplateFormRef"
    :form-model="extendTemplateForm"
    :label-width="this.CmsPageForm.labelWidth"
    :form-rules="extendTemplateRules"
  >
    <cms-form-item
      v-for="(row, index) in extendTemplateFieldList"
      :key="index"
      :label="row.fieldName"
      :prop="row.fieldKey" :column="3">
      <cms-extend-field-config
        v-model="extendTemplateForm[[row.fieldKey]]"
        :form-model="row"
        :field-name="'parameterValue'"
        :placeholder="row.placeholder ? row.placeholder : '请输入' + row.fieldName"
        :constants="constants"
        :dictionary-config="dictionaryConfig"
        :props-config="row"/>
    </cms-form-item>
  </cms-edit-form>
</template>

<script>
export default {
  name: "CmsExtendField",
  inject: {
    CmsPageForm: {
      default: ''
    }
  },
  data() {
    return {
      extendTemplateForm: {
        funCode: undefined,
      },
      extendTemplateRules: {},
      extendTemplateFieldList: []
    }
  },

  methods: {
    validate(callback) {
      this.$refs.extendTemplateFormRef.validate(valid => {
        callback(valid);
      })
    },
    getForm() {
      return this.$refs.extendTemplateFormRef;
    },
    getFormData() {
      return this.extendTemplateForm;
    },
    getRequestData: async function () {
      if (this.requestCall) {
        const { code, msg, data } = await this.requestCall({
          funCode: this.CmsPageForm.funCode,
          businessId: this.CmsPageForm.formModel.id
        });
        if (code === 200) {
          this.extendTemplateFieldList = data;
          this.extendTemplateFieldList.forEach(row => {
            const fieldKey = row.fieldKey;
            this.$set(this.extendTemplateForm, [ fieldKey ], row.defaultValue);
            this.extendTemplateRules[fieldKey] = [ {
              required: row.required,
              message: this.$t("common.message.validMsg"),
              trigger: [ "change", "blur" ],
            }, ]
          })
        }
      }
    },
  },
  watch: {
    'formModel.extendMap': {
      handler(extendMap) {
        if (extendMap) {
          Object.keys(extendMap).forEach(fieldKey => {
            const defaultValue = extendMap[fieldKey];
            if (defaultValue) {
              this.$set(this.extendTemplateForm, [ fieldKey ],  defaultValue);
            }
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  props: {
    requestCall: [ Function, String ],
    dictionaryConfig: [],
    constants: {},
    formModel: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  async created() {
    await this.getRequestData();
  }
}
</script>

<style scoped>

</style>
