<template>
  <a-form-model :model="form" :rules="rules" class="yo-form" ref="form">
    <a-spin :spinning="loading">
      <a-icon slot="indicator" spin type="loading" />
      <div class="yo-form-group">
        <a-form-model-item has-feedback label="机构名称" prop="name">
          <a-input placeholder="请输入机构名称" v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="唯一编码" prop="code">
          <a-input placeholder="请输入唯一编码" v-model="form.code" />
        </a-form-model-item>
        <a-form-model-item has-feedback label="上级机构" prop="pid">
          <a-tree-select
            :tree-data="orgData"
            placeholder="请选择上级机构"
            tree-default-expand-all
            v-model="form.pid"
          />
        </a-form-model-item>
        <a-form-model-item label="排序" prop="sort">
          <a-input-number
            :max="1000"
            :min="0"
            class="w-100-p"
            placeholder="请输入排序"
            v-model="form.sort"
          />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea placeholder="请输入备注" v-model="form.remark" />
        </a-form-model-item>
      </div>
    </a-spin>
  </a-form-model>
</template>
<script>
export default {
  data() {
    return {
      form: {},
      rules: {
        name: [{ required: true, message: '请输入机构名称' }],
        code: [{ required: true, message: '请输入唯一编码' }],
        pid: [{ required: true, message: '请选择上级机构' }],
      },

      loading: false,

      orgData: [],
    };
  },
  methods: {
    /**
     * 必要的方法
     * 在打开编辑页时允许填充数据
     */
    onFillData(record) {
      this.form = this.$_.cloneDeep(record);
    },

    /**
     * 必要的方法
     * 在外部窗口进行保存时调用表单验证
     */
    onValidate(callback) {
      this.$refs.form.validate(callback);
    },

    /**
     * 必要的方法
     * 在外部窗口关闭或重置时对表单验证进行初始化
     */
    onResetFields() {
      setTimeout(() => {
        this.$refs.form.resetFields();
      }, 300);
    },

    async onInit() {
      this.loading = true;
      this.orgData = await this.onLoadOrgData();
      this.loading = false;
    },

    onLoadOrgData() {
      return this.$api.getOrgTree().then(({ data }) => {
        return data;
      });
    },

    onChangeExtData(value, record, type) {
      record[type] = value;
    },
  },
};
</script>