<template>
  <div class="avue-component">
    <div v-if="type === 'DynamicForm'">
      <avue-form-design
        :widconfigProps="widconfigProps"
        class="app-form-design"
        style="height: 86vh;"
        :options="formOpt"
        @change="handleChange"
      ></avue-form-design>
    </div>
    <div v-else-if="type === 'DynamicSubForm'">
      <avue-form-design
        :widconfigProps="widconfigProps"
        class="app-form-design"
        style="height: 86vh;"
        :options="formOpt"
        @change="handleChange"
      ></avue-form-design>
    </div>
    <div v-else-if="type === 'DynamicGrid'">
      <app-avue-crud :colOptions="tableOpt" @change="handleChange"></app-avue-crud>
    </div>
  </div>
</template>
<script lang="ts">
import {
  Vue,
  Component,
  Prop,
  Model,
  Emit,
  Watch,
} from "vue-property-decorator";
import { Subject, Subscription } from "rxjs";
import { component } from "vue/types/umd";
import "./avue-component.less";

@Component({})
export default class AvueComponent extends Vue {
  @Prop() public type?: string;

  @Prop() public options?: any;

  @Prop() public formState!: Subject<any>;

  @Prop() public name: any;

  @Prop() public systemid: any;

  @Prop() public entityname: any;

  public widconfigProps: Array<any> = [];

  public formOpt: any = {};

  public tableOpt: any = [];

  public handleChange(val: any) {
    let value: any;
    if (typeof val === "string") {
      value = val;
    } else {
      value = JSON.stringify(val);
    }
    let params: any = { name: this.name, value: value };
    this.$emit("formitemvaluechange", params);
  }

  /**
   * 订阅对象
   *
   * @protected
   * @type {(Subscription | undefined)}
   * @memberof AvueComponent
   */
  protected formStateEvent: Subscription | undefined;

  public created() {
    let that: any = this;
    if (this.formState) {
      this.formStateEvent = this.formState.subscribe(({ type, data }) => {
        if (Object.is("load", type)) that.load();
      });
    }
  }

  public load() {
    let that: any = this;
    let url: string = "lite/Sample/entitys/CITY";
    if (this.systemid && this.entityname) {
      url = `lite/${this.systemid}/entitys/${this.entityname}`;
    }
    this.$http.get(url).then((response: any) => {
      if (response && response.data) {
        let arr: Array<any> = [];
        let data: any = response.data;
        data.fields.forEach((field: any) => {
          arr.push({ value: field.codeName.toLowerCase(), label: field.showName, comment: field.comment });
        });
        that.widconfigProps = arr;
        that.$forceUpdate();
      }
    });
    if (this.options) {
      let opt: any = this.options.replace(/[\n\r]/g, "");
      if (this.type)
        if (this.type.indexOf("Form") > 0) {
          this.formOpt = JSON.parse(opt);
        } else {
          this.tableOpt = JSON.parse(opt);
        }
    }
  }
}
</script>