<template>
  <div>
    <div class="i-layout-page-header">
      <PageHeader :title="$route.meta.title" :content="$route.meta.description" hidden-breadcrumb />
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <view-table
        ref="table"
        view-code="Permission"
        :select-enable="allow('export')"
        :tree-enable="true"
        :tree-load="row => onTreeLoad(row)"
        :has-children="
          row => {
            return row.hasChildren;
          }
        "
        :before-load-data="beforeLoadData"
        :create-enable="allow('create')"
        :remove-enable="allow('remove')"
        @on-load-data="onLoadData"
        @create="create()"
        @edit="({ row, index }) => edit(row)"
      >
        <template #filterCommand>
          <Button v-if="allow('export')" size="small" type="info" custom-icon="fa fa-cloud-download-alt" @click="exportFile()">{{ $t('Front_Btn_Export') }}</Button>
          <file-upload v-if="allow('import')" url="api/Permission/importFile" accept=".pms" @on-success="importFileSuccess">
            <template #>
              <Button type="primary" custom-icon="fa fa-cloud-upload-alt" size="small">{{ $t('Front_Btn_Import') }}</Button>
            </template>
          </file-upload>
        </template>
        <template #command="{ row }">
          <Button v-if="allow('create')" size="small" :title="$t('Front_Btn_Create_Child')" type="primary" custom-icon="fa fa-plus" @click="create(row)"></Button>
        </template>
        <template #column="{ row, column, code }">
          <template v-if="code == 'name'">
            <div :style="{ 'font-weight': row.hasChildren ? 'bold' : '' }">{{ showData(row, column) }}</div>
          </template>
        </template>
      </view-table>
    </Card>
    <modal-form ref="form" view-code="PermissionEdit" :create-enable="allow('create')" :edit-enable="allow('edit')" @on-change="formChange" @on-after-save="formAfterSave" />
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';
  import permissionApi from '../../api/permission';
  import modelApi from '../../api/model';

  export default {
    name: 'system-permission',
    mixins: [mixinPage],
    components: {},
    data() {
      return {
        data: null
      };
    },
    computed: {},
    created() {},
    methods: {
      formChange(sender, oldValue, newValue, selected) {
        const data = this.$refs.form.data;
        const columns = this.$refs.form.columns;

        const columnCustomPageID = columns.find(item => {
          return item.code === 'customPageID';
        });
        const columnTemplateUrl = columns.find(item => {
          return item.code === 'templateUrl';
        });

        if (data.isCustomPage) {
          // 自定义页面
          columnCustomPageID.isShow = true;
          columnTemplateUrl.isShow = false;
        } else {
          columnCustomPageID.isShow = false;
          columnTemplateUrl.isShow = true;
        }

        // 必须父路由打头
        if (sender && sender.code == 'parentID') {
          if (selected) {
            data.url = selected.url + '/';
          }
        }

        if (sender && sender.code == 'hasPermissionPoint') {
          if (data.hasPermissionPoint && data.permissionPoint == null) {
            this.$refs.form.setTableData('permissionPoint', [
              { code: 'view', name: '查看' },
              { code: 'create', name: '新增' },
              { code: 'edit', name: '编辑' },
              { code: 'remove', name: '删除' }
            ]);
          }
          // else if (!data.hasPermissionPoint) {
          //     this.$refs.form.setTableData('permissionPoint', null);
          // }
        }

        //this.$refs.form.forceUpdate();
      },
      // 导出文件
      exportFile() {
        let ids = this.$refs.table.getSelected().map(x => {
          return x.id;
        });
        if (ids.length > 0) {
          permissionApi.exportFile(ids);
        } else {
          this.error('Front_Msg_Please_Select_Export_Item');
        }
      },
      // 导入成功
      importFileSuccess(res) {
        if (res.code == 0) {
          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
          });
        } else {
          this.error(res.message);
        }
      },
      // 树展开
      async onTreeLoad(row) {
        let res = await modelApi.query('Permission', {
          parentID: row.id,
          page: 1,
          per: 1000,
          orderBy: '+orderNo'
        });

        for (let data of res.data) {
          data._depth = row._depth == null ? 1 : row._depth + 1;
        }

        return res.data;
      },
      // 创建
      create(parent) {
        this.data = null;
        if (parent) {
          this.$refs.form.openDefault({
            clientTypeID: parent.clientTypeID,
            parentID: parent.id,
            icon: parent.icon,
            url: parent.url + '/',
            orderNo: parent.orderNo
          });
        } else {
          this.$refs.form.openDefault({});
        }
      },
      // 编辑
      edit(row) {
        this.data = row;
        this.$refs.form.open(row);
      },
      // 保存后事件
      formAfterSave(row) {
        if (this.data) {
          for (let key in row) {
            this.data[key] = row[key];
          }
        } else {
          this.$refs.table.loadData();
        }
      },
      beforeLoadData() {
        let filterData = this.$refs.table.filterData;

        if (!(filterData['keyword'] || '').trim()) {
          // 普通查询，只查询顶层包装
          filterData['parentID'] = 'null';
        } else {
          // 根据关键词查询，查询所有层级
          filterData['parentID'] = null;
        }
      },
      async onLoadData() {
        let filterData = this.$refs.table.filterData;
        if (!!(filterData['keyword'] || '').trim()) {
          // 根据关键词查询的结果，递归查找所有上层
          let data = this.$refs.table.data;
          if (data.length > 0) {
            let dataWithParent = [];
            for (let i = 0; i < data.length; i++) {
              await this.loadParentData(data[i], dataWithParent);
            }

            dataWithParent.forEach(item => {
              if (item.parentID) {
                let parent = dataWithParent.find(p => p.id == item.parentID);
                if (!parent.children) {
                  parent.children = [];
                }

                parent.children.push(item);
                parent._showChildren = true;
              }
            });

            data.length = 0;
            dataWithParent
              .filter(item => item.parentID == null)
              .forEach(item => {
                data.push(item);
              });
          }
        }
      },
      async loadParentData(data, dataWithParent) {
        dataWithParent.push(data);

        if (data.parentID && !dataWithParent.some(item => item.id == data.parentID)) {
          let res = await modelApi.query('Permission', {
            id: data.parentID,
            page: 1,
            per: 1
          });

          await this.loadParentData(res.data[0], dataWithParent);
        } else {
          return;
        }
      }
    }
  };
</script>
[]
