<template>
  <div class="ws-state-version">
    <v-row v-if="C_value">
      <v-col
        v-for="(field, fieldKey) in _updateFields"
        cols="12"
        :sm="field.sm ? field.sm : 12"
        :key="fieldKey"
      >
        <WsState
          :type="field.type"
          :label="field.label"
          :fields="field.fields"
          :rules="field.rules"
          :autofocus="field.autofocus"
          :displayLabel="field.displayLabel"
          :uploadUrl="field.uploadUrl"
          :modelName="field.modelName"
          :value="C_value[fieldKey]"
          :originValue="$_getOriginValue(value,fieldKey)"
          @input="$_onInput($event,fieldKey)"
        />
      </v-col>
    </v-row>
  </div>
</template>

<script>
export default {
  data: () => ({
    C_value: null,
  }),
  methods: {
    $_getOriginValue(modelData, fieldKey) {
      if (!modelData) {
        return null;
      } else {
        return modelData[fieldKey];
      }
    },
    $_onInput($event, fieldKey) {
      this.C_value[fieldKey] = $event;
    },
    $_valueInit() {
      const initValue = {};
      for (let fieldKey in this._updateFields) {
        const field = this.fields[fieldKey];
        if (field.readonly) {
          continue;
        }

        if (this.value && this.value[fieldKey] != undefined) {
          if (field.type == "belongsTo" && this.value) {
            initValue[fieldKey] = this.value[fieldKey].id;
          } else if (field.type == "hasMany" && this.value) {
            const _value = [];
            this.value[fieldKey].forEach((itemValueItem) => {
              _value.push(itemValueItem.id);
            });
            initValue[fieldKey] = _value;
          } else {
            initValue[fieldKey] = this.value[fieldKey];
          }
        } else if (field.defaultValue !== undefined) {
          initValue[fieldKey] = field.defaultValue;
        } else {
          initValue[fieldKey] = null;
        }
      }
      this.C_value = initValue;
    },
  },
  mounted() {
    this.$_valueInit();
  },
  computed: {
    _updateFields() {
      return this.$_CMS_geUpdateFields(this.fields);
    },
  },
  props: {
    originValue: {},
    fields: {
      type: Object,
      default: null,
    },
    value: {},
  },
  watch: {
    C_value: {
      handler() {
        this.$emit("input", this.C_value);
      },
    },
  },
};
</script>

<style>
</style>