<template>
  <app-dialog v-model="visible" :loading="dialogLoading" append-to-body class="detail-dialog" title="选择资源"
              width="60%" @confirm="onConfirm"
  >
    <div class="page-view flex-row-sb">
      <app-sync-tree
        ref="appAsyncTree"
        :actions="treeActions"
        :default-data="{ customConfigField: 'custom config field' }"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-all="false"
        :fields="treeFields"
        :props="treeProps"
        :request-method="getTreeNodes"
        highlight-first
        title="共享资源目录"
        @select="onTreeNodeClick"
      />

      <div class="page-view flex-1 ml-15 h-100">
        <app-filter ref="app-filter" :model="filters" class="bg-white px-15 border-radius-5" label-width="100px"
                    @query="onQuery" @reset="onReset"
        >
          <div v-if="type==='sql'">
            <app-filter-item :filter-config="{ operation: 'EQUAL' }" :span="12" el-type="input"
                             label="共享资源名称"
            >
              <el-input v-model="filters.name" clearable placeholder="请输入"
                        @keyup.enter.native="$refs['app-filter'].query"
              />
            </app-filter-item>
          </div>
          <div v-if="type==='file'">
            <app-filter-item :filter-config="{ operation: 'EQUAL' }" :span="12" el-type="input"
                             label="文件名称"
            >
              <el-input v-model="filters.fileName" clearable placeholder="请输入"
                        @keyup.enter.native="$refs['app-filter'].query"
              />
            </app-filter-item>
          </div>
          <div v-if="type==='api'">
            <app-filter-item :filter-config="{ operation: 'EQUAL' }" :span="12" el-type="input"
                             label="接口名称"
            >
              <el-input v-model="filters.apiName" clearable placeholder="请输入"
                        @keyup.enter.native="$refs['app-filter'].query"
              />
            </app-filter-item>
          </div>
        </app-filter>

        <!-- 列表组件 -->
        <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
          <app-table
            :column="columnChange"
            :index="false"
            :pagination="pagination"
            :table-data="tableData"
            :table-loading="tableLoading"
            :total="total"
            checkbox
            @select-change="selectChange"
            @pagination-change="onPaginationChange"
          />
        </div>
      </div>
    </div>
  </app-dialog>
</template>

<script>
import dialogMixin from '@/mixins/dialog.js';
import tableMixin from '@/mixins/table.js';
import CATLOG from '@/api/business/shareDataCatalog';
import API from '@/api/business/shareDataCall';

export default {
  name: 'ResourceList',
  mixins: [dialogMixin, tableMixin],
  props: {
    type: {
      type: String,
      default: '',
    },
    id: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      dialogLoading: false,
      sqlColumns: [
        { label: '资源名称', prop: 'name', align: 'center' },
        { label: '数据库表名', prop: 'tableCode', width: '200px', align: 'center' },
        { label: '资源更新周期', prop: 'updateRate', width: '150px', align: 'center' },
        { label: '资源级别', prop: 'level', width: '100px', align: 'center' },
      ],
      fileColumns: [
        { label: '文件名称', prop: 'fileName', align: 'center', width: '250px' },
        { label: '文件描述', prop: 'fileContent', align: 'center' },
        { label: '文件类型', prop: 'fileType', width: '150px', align: 'center' },
      ],
      apiColumns: [
        { label: '接口名称', prop: 'apiName', align: 'center' },
        { label: '接口地址', prop: 'apiUrl', width: '250px', align: 'center' },
        { label: '请求方式', prop: 'apiMode', width: '200px', align: 'center' },
      ],
      treeProps: {
        value: 'id',
        label: 'name',
      },
      defaultExpandedKeys: ['0'],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 't1.CATALOG_ID_',
          relation: 'AND',
          value: '',
        },
      ],
      treeFields: [],
      curNode: {},
      muilteList: [],
    };
  },
  computed: {
    columnChange() {
      if (this.type === 'sql') {
        return this.sqlColumns;
      } else if (this.type === 'file') {
        return this.fileColumns;
      } else {
        return this.apiColumns;
      }
    },
    dataMethod() {
      if (this.type === 'sql') {
        return API.detaBaseResourceAuthorization;
      } else if (this.type === 'file') {
        return API.fileResourceAuthorization;
      } else {
        return API.apiResourceAuthorization;
      }
    },
  },
  methods: {
    onBeforeGetData(queryParams, formData) {
      if (this.type === 'sql') {
        this.setFilterValue(this.queryParams, this.defaultFilter, 't1.CATALOG_ID_', this.curNode.id);
      }
    },
    async getTreeNodes() {
      const { value = [] } = await CATLOG.getShareTree();
      this.defaultExpandedKeys = [value?.[0].id || ''];
      return { data: value || [] };
    },
    treeActions(data) {
      return [];
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return;
      this.curNode = { ...node };
      this.getData();
    },

    initData(data) {
      console.log(data, 'typetypetype');
    },
    async onConfirm() {
      if (this.muilteList.length > 0) {
        try {
          let param = [];
          if (this.type === 'sql') {
            param = this.muilteList.map((item) => {
              return {
                memberId: this.id,
                resourceType: '1',
                tableId: item.id,
              };
            });
          } else {
            param = this.muilteList.map((item) => {
              return {
                memberId: this.id,
                resourceType: this.type === 'file' ? '2' : '3',
                resourceId: item.id,
                tableId: item.tableId,
              };
            });
          }
          const { state } = await API.authorizationConfirm(param);
          if (state) {
            this.visible = false;
            this.$emit('confirm');
            this.$message.success('授权成功！');
          }
        } catch (err) {
          this.$message.warning(err || '授权失败！');
        }
      } else {
        this.$message.warning('请选择资源');
      }
    },
    selectChange(data) {
      this.muilteList = data;
    },
  },
};
</script>

<style lang="scss" scoped>
.gz-dialog .app-dialog-content {
  padding: 0 !important;
}
</style>
