import * as API from 'api/base/roles';

export default{
  props: {
    show: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default() {
        return null;
      }
    }
  },
  watch: {
    show(bool) {
      this.my_show = bool;
      if (bool) {
        if (this.data) {
          for (let k in this.data) {
            if (k in this.params) {
              this.params[k] = this.data[k];
            }
          }
        }
      }
    }
  },
  data() {
    return {
      my_show: false,
      loading: false,
      params: {
        name: '',
        type: '',
        remark: '',
        parent_id: ''
      }
    };
  },
  methods: {
    ok() {
      if (!this.params.name) {
        this.$Message.info('请填写角色名');
        return;
      }

      if (this.data) {
        // 编辑
        API.update(this.params, this.data.id).then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$emit('update-success');
            this.$Message.success('更新成功');
            this.my_show = false;
          }
        }).catch(err => {
          this.loading = false;
        });
      } else {
        // 添加
        API.create(this.params).then(res => {
          this.loading = false;
          if (res.code == 0) {
            this.$emit('add-success');
            this.$Message.success('添加成功');
            this.my_show = false;
          }
        }).catch(err => {
          this.loading = false;
        });
      }
    },

    visibleChange(bool) {
      if (!bool) {
        this.$emit('update:show', false);
        for (let k in this.params) {
          this.params[k] = '';
        }
      }
    }
  }
};
