<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :visible="visible"
    :width="600"
    @cancel="onCancel"
    @ok="onOk"
    title="授权数据"
  >
    <a-spin :spinning="loading">
      <a-icon slot="indicator" spin type="loading" />
      <a-form-model :model="form" :rules="rules" class="yo-form" ref="form">
        <div class="yo-form-group">
          <a-form-model-item has-feedback label="授权范围" prop="dataScopeType">
            <a-select placeholder="请选择授权范围" v-model="form.dataScopeType">
              <a-select-option
                :key="item.code"
                :value="item.code"
                @click="onChange(item.code)"
                v-for="item in dataScopeTypeData"
              >{{ item.value }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="选择机构" v-show="orgTreeShow">
            <a-tree-select
              :show-checked-strategy="SHOW_PARENT"
              :tree-data="orgTreeData"
              placeholder="请选择机构"
              tree-checkable
              v-model="checkedKeys"
            />
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

export default {
  data() {
    return {
      visible: false,
      confirmLoading: false,
      loading: true,

      record: {},

      form: {
        dataScopeType: '',
      },
      rules: {
        dataScopeType: [{ required: true, message: '请选择授权范围' }],
      },

      SHOW_PARENT,
      orgTreeData: [],

      checkedKeys: [],
      dataScopeTypeData: [],
      orgTreeShow: false,
      replaceFields: {
        key: 'id',
      },
    };
  },

  methods: {
    async onOpen(record) {
      this.visible = true;
      this.record = record;

      this.loading = true;

      await this.onLoadCodes();
      this.form.dataScopeType = record.dataScopeType.toString();

      await this.onChange(record.dataScopeType);

      this.loading = false;
    },

    /**
     * 加载字典数据时的必要方法
     */
    onLoadCodes() {
      return this.$api
        .$queue([this.$api.sysDictTypeDropDownWait({ code: 'data_scope_type' })])
        .then(([dataScopeType]) => {
          this.dataScopeTypeData = dataScopeType.data;
        });
    },

    async onChange(value) {
      if (value == '5') {
        this.loading = true;
        this.orgTreeShow = true;
        // 获取机构树
        this.orgTreeData = await this.onLoadTreeData();
        // 已关联数据
        this.checkedKeys = await this.onLoadRoleOwn();

        this.loading = false;
      } else {
        this.orgTreeShow = false;
        // 清理已选中机构
        this.checkedKeys = [];
      }
    },

    /**
     * 获取机构树
     */
    onLoadTreeData() {
      return this.$api.getOrgTree().then(({ data }) => {
        return data;
      });
    },

    /**
     * 此角色已有数据列表
     */
    onLoadRoleOwn() {
      return this.$api.sysRoleOwnData({ id: this.record.id }).then(({ data }) => {
        return data;
      });
    },

    onOk() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          this.$api
            .sysRoleGrantData({
              id: this.record.id,
              grantOrgIdList: this.checkedKeys,
              dataScopeType: this.form.dataScopeType,
            })
            .then(({ success }) => {
              if (success) {
                this.$message.success('授权成功');
                this.$emit('ok');
                this.onCancel();
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    onCancel() {
      this.visible = false;

      setTimeout(() => {
        this.record = {};
        this.checkedKeys = [];
        this.dataScopeTypeData = [];
        this.orgTreeShow = false;
        this.form = {};

        this.$refs.form.resetFields();
      }, 300);
    },
  },
};
</script>
