<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :visible="visible"
    :width="600"
    @cancel="onCancel"
    @ok="onOk"
    class="yo-modal-form"
    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 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="isDefine">
            <a-tree-select
              :show-checked-strategy="SHOW_PARENT"
              :tree-data="orgTreeData"
              placeholder="请选择机构"
              tree-checkable
              v-model="orgCheckedKeys"
            />
          </a-form-model-item>
          <a-form-model-item label="选择区域" v-show="isDefine">
            <a-tree-select
              :replace-fields="{ title: 'name', value: 'code', children: 'children' }"
              :show-checked-strategy="SHOW_PARENT"
              :tree-data="areaTreeData"
              placeholder="请选择所属区域"
              tree-checkable
              v-model="areaCheckedKeys"
            />
          </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: [],
      orgCheckedKeys: [],

      areaTreeData: [],
      areaCheckedKeys: [],

      dataScopeTypeData: [],
      isDefine: 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.sysDictTypeDropDownAwait({ code: 'data_scope_type' })])
        .then(([dataScopeType]) => {
          this.dataScopeTypeData = dataScopeType.data;
        });
    },

    async onChange(value) {
      if (value == '5') {
        this.loading = true;
        this.isDefine = true;
        // 获取机构树
        this.orgTreeData = await this.onLoadOrgTreeData();
        // 获取区域
        this.areaTreeData = await this.onLoadAreaTreeData();
        // 已关联数据
        this.orgCheckedKeys = await this.onLoadRoleOwn();

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

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

    onLoadAreaTreeData() {
      return this.$api.getAreaTree().then(({ data }) => {
        // 为了防止出现空的层级选择,删除所有空children节点
        const clearChiildren = (data) => {
          data.forEach((item) => {
            if (item.children && item.children.length) {
              clearChiildren(item.children);
            } else {
              delete item.children;
            }
          });
        };
        clearChiildren(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.orgCheckedKeys,
              grantAreaCodeList: this.areaCheckedKeys,
              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.orgCheckedKeys = [];
        this.areaCheckedKeys = [];
        this.dataScopeTypeData = [];
        this.isDefine = false;
        this.form = {};

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