<template>
  <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" @query="onQuery"
                  @reset="onReset"
      >
        <app-filter-item :filter-config="{ operation: 'EQUAL' }" el-type="input" label="资源名称" prop="name">
          <el-input v-model="filters.name" clearable placeholder="请输入"
                    @keyup.enter.native="$refs['app-filter'].query"
          />
        </app-filter-item>
      </app-filter>

      <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
        <app-table
          :column="columns"
          :pagination="pagination"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          @pagination-change="onPaginationChange"
          @row-dblclick="showDetail"
        >
          <!-- 状态 -->
          <template #deployed="scope">
            <el-tag :type="scope.row.deployedStatus === '1' ? 'primary' : 'warning'">
              {{ scope.row.deployedStatus === '1' ? '发布' : '未发布' }}
            </el-tag>
          </template>
        </app-table>
      </div>
    </div>

    <!--  详情  -->
    <detail-dialog v-model="dialogVisible" :data="currentRow" title="资源详情" />
  </div>
</template>

<script>
import tableMixin from '@/mixins/table.js'
import ResourceAuthorize from '@/views/dataResource/dataShare/shareDataCatalog/ResourceAuthorize.vue'
import DetailDialog from '@/views/dataResource/dataShare/shareTable/DetailDialog.vue'
import API from '@/api/business/shareDataCatalog'

export default {
  components: {DetailDialog, ResourceAuthorize},
  mixins: [tableMixin],
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name'
      },
      defaultExpandedKeys: ['0'],
      treeFields: [
        {
          label: '资源目录名称',
          prop: 'name',
          labelWidth: '120',
          rules: [{required: true, message: '资源目录名称不能为空'}]
        },
        {
          label: '资源目录编码',
          prop: 'code',
          labelWidth: '120',
          rules: [{required: true, message: '资源目录编码不能为空'}]
        }
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'catalogId',
          relation: 'AND',
          value: ''
        },
        {
          operation: 'EQUAL',
          property: 'isApi',
          relation: 'AND',
          value: ''
        }
      ],
      curNode: {} // 当前选择节点
    }
    const TABLE_CONFIG = {
      columns: [
        {label: '资源名称', prop: 'name', align: 'center'},
        {label: '数据库表名', prop: 'tableCode', width: '150px'},
        {label: '资源更新周期', prop: 'updateRate', width: '110px'},
        {label: '资源级别', prop: 'level', width: '80px', align: 'center'},
        {label: '发布状态', prop: 'deployed', dataType: 'slot', slot: 'deployed', width: '100px', align: 'center'},
        {
          dataType: 'option',
          label: '操作',
          width: '250px',
          fixed: 'right',
          align: 'center',
          operation: [
            {
              name: '查看接口',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-view',
              plain: true,
              clickFun: (row) => {
                this.checkApiChange(row)
              }
            }
          ]
        }
      ]
    }
    return {
      ...TREE_CONFIG, // 树相关
      ...TABLE_CONFIG, // table相关
      dialogVisible: false,
      resourceDialog: false
    }
  },
  computed: {
    dataMethod() {
      return API.shareCatalogsTable
    }
  },
  methods: {
    // 左边树
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'catalogId', this.curNode.id)
      this.setFilterValue(this.queryParams, this.defaultFilter, 'isApi', 1)
    },
    async getTreeNodes() {
      const {value = []} = await API.getShareTree()
      this.defaultExpandedKeys = [value?.[0].id || '']
      return {data: value || []}
    },
    reloadTree() {
      this.$refs.appAsyncTree.getTreeData()
    },
    treeActions(data) {
      return [
        {label: '添加', type: 'add', method: this.addNode},
        {label: '编辑', type: 'edit', method: this.editNode},
        {label: '删除', type: 'delete', method: this.delNode}
      ]
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return
      this.curNode = {...node}
      this.getData()
    },
    async addNode(params, node) {
      const {code, name} = params
      const {id} = node
      const newNode = {
        code,
        name,
        parentId: id
      }
      try {
        const {state} = await API.addShareTree(newNode)
        if (state) {
          this.reloadTree()
          this.$message.success('添加资源目录成功！')
        }
      } catch (err) {
        this.$message.warning(err || '添加资源目录失败！')
      }
    },
    async editNode(params) {
      const {code, name, parentId, id} = params
      const newNode = {
        code,
        name,
        id,
        parentId
      }
      try {
        const {state} = await API.editShareTree(newNode)
        if (state) {
          this.reloadTree()
          this.$message.success('编辑资源目录成功！')
        }
      } catch (err) {
        this.$message.warning(err || '编辑资源目录失败！')
      }
    },
    async delNode(params, node) {
      try {
        const {state} = await API.removeShareTree(node.id)
        if (state) {
          this.reloadTree()
          this.$message.success('删除资源目录成功！')
        }
      } catch (err) {
        this.$message.warning(err || '删除资源目录失败！')
      }
    },

    // 双击详情
    showDetail(row) {
      this.currentRow = row
      this.dialogVisible = true
    },
    // 查看文件
    checkApiChange(row) {
      console.log(this.curNode.id, '树目录id')
      console.log(row.id, '列表数据id')
      if (row && row.id && this.curNode && this.curNode.id) {
        this.$router.push({
          name: 'apiInterfaceShareApi',
          query: {
            tableId: row.id,
            catalogId: this.curNode.id
          }
        })
      } else {
        console.error('No valid id found in the row object')
      }
    }

  }
}
</script>

<style lang="scss" scoped></style>
