<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="left"
    >
      <el-form-item label="分配按钮" prop="buttonIds">
        <el-select
          v-model="form.buttonIds"
          size="small"
          filterable
          multiple
          placeholder="选择按钮"
        >
          <el-option
            v-for="item in buttonData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" size="small" @click="save">确 定</el-button>
      <el-button size="small" @click="close">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getButtonIds, assignButton, getList } from '@/api/platform';
export default {
  data() {
    return {
      form: {
        roleId: '',
        buttonIds: '',
      },
      buttonData: [],
      rules: {
        buttonIds: [
          { required: true, trigger: 'blur', message: '请选择按钮' },
        ],
      },
      title: '',
      dialogFormVisible: false,
    };
  },
  created() {},
  methods: {
    handleCountryChange(value) {
      if (value) {
        const len = value.length - 1;
        this.form.parentId = value[len];
      } else {
        this.form.parentId = 0;
      }
    },
    async getButtonData() {
      const { data } = await getList({ page: 1, size: 1000 });
      this.buttonData = data.items;
      await this.queryRoleButton();
    },
    // 查询角色现有按钮
    async queryRoleButton() {
      const { data } = await getButtonIds({ roleId: this.form.roleId });
      this.form.buttonIds = data;
    },
    roleButton(roleId) {
      this.title = '绑定按钮';
      this.form.roleId = roleId;
      this.dialogFormVisible = true;
      this.getButtonData();
    },
    close() {
      this.$refs['form'].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      this.$emit('fetch-data');
    },
    save() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.form.name = this.form.title;
          const { msg } = await assignButton(this.form);
          this.$notify({
            title: msg,
            type: 'success',
          });
          this.$refs['form'].resetFields();
          this.dialogFormVisible = false;
          this.$parent.fetchData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>
