<template>
  <div class="page-view flex-row-sb">
    <app-sync-tree
      ref="appAsyncTree"
      :actions="treeActions"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-all="expandAll"
      :fields="treeFields"
      :props="treeProps"
      :request-method="getTreeNodes"
      highlight-first
      title="贴源层目录"
      @select="onTreeNodeClick"
    />

    <div class="page-view flex-1 ml-11">
      <app-filter ref="app-filter" :model="filters" class="bg-white px-15 border-radius-5" label-width="90px" @query="onQuery" @reset="onReset">
        <app-filter-item :filter-config="{ operation: 'EQUAL' }" :span="6" el-type="input" label="资源项名称">
          <el-input v-model="filters.name" clearable placeholder="请输入" @keyup.enter.native="$refs['app-filter'].query" />
        </app-filter-item>
        <app-filter-item :span="6" label="资源项编码">
          <el-input v-model="filters.code" 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">
        <!--        <div class="mb-11">-->
        <!--          <el-button :disabled="!curNode" icon="el-icon-plus" size="mini" type="primary" @click="dataAdd"> 新增 </el-button>-->
        <!--        </div>-->
        <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['deployed'] === 1 ? '' : 'danger'">{{ scope.row['deployed'] === 1 ? '已发布' : '未发布' }}</el-tag>
          </template>
        </app-table>
      </div>
    </div>

    <detail-dialog v-model="dialogVisible" :data="currentRow" :ods-catalogs-id="curNode.id" :title="dialogTitle" />

    <!--    <source-selector v-model="dialogVisible" :data="currentRow" :ods-catalogs-id="curNode.id" :title="dialogTitle" @confirm="onAddConfirm" />-->
  </div>
</template>

<script>
import API from '@/api/business/dataODSCatalog';
import tableMixin from '@/mixins/table.js'; // 列表mixins
import DetailDialog from './DetailDialog';

export default {
  name: '',
  components: { DetailDialog },
  mixins: [tableMixin],
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name',
      },
      expandAll: false,
      defaultExpandedKeys: ['0'],
      // 此处fields内配置对象属性包括: label/prop/rules/type(枚举:switch/number/input(默认))/span/
      treeFields: [
        { label: '目录名称', prop: 'name', rules: [{ required: true, message: '资源目录名称不能为空' }] },
        { label: '目录编码', prop: 'code', rules: [{ required: true, message: '资源目录编码不能为空' }] },
      ],
      curNode: {}, // 当前选择节点
    };
    const TABLE_CONFIG = {
      // 列表表头
      columns: [
        { label: '资源名称', prop: 'name', width: '240' },
        { label: '资源编码', prop: 'name', width: '150' },
        {
          label: '资源密级',
          prop: 'level',
          width: '100',
          align: 'center',
          formatData: (val) => {
            return this.filterDict('SECRET_LEVEL', val).label;
          },
        },
        {
          label: '资源格式',
          prop: 'sourceType',
          width: '100',
          align: 'center',
          formatData: (val) => {
            return this.filterDict('SOURCE_FILE_TYPE', val).label;
          },
        },
        {
          label: '提供方式',
          prop: 'source',
          width: '100',
          align: 'center',
          formatData: (val) => {
            return this.filterDict('SOURCE_PROVIDED_TYPE', val).label;
          },
        },
        {
          label: '是否发布',
          prop: 'deployed',
          width: '100',
          align: 'center',
          dataType: 'slot', // 使用插槽
          slot: 'deployed', // 插槽名，搭配 dataType: 'slot' 使用
        },
        {
          label: '提供方表前缀命名',
          width: '150',
          prop: 'tablePrefixCode',
        },
        {
          label: '数据库表名',
          width: '150',
          prop: 'tableNameCh',
        },
        {
          label: '物理实体表中文名',
          width: '150',
          prop: 'tableNameCh',
        },
        {
          label: '物理实体表英文名',
          width: '150',
          prop: 'tableNameEn',
        },
        {
          dataType: 'option',
          label: '操作',
          width: '130px',
          fixed: 'right',
          operation: [
            {
              name: '查看数据',
              // showHide: (row) => {},
              clickFun: (row) => {
                this.currentRow = row;
                this.dialogTitle = `${row.name} - 数据信息`;
                this.dialogVisible = true;
              },
            },
          ],
        },
      ],
    };
    const DIALOG_CONFIG = {
      dialogVisible: false,
      dialogTitle: '',
    };

    return {
      ...TREE_CONFIG,
      ...TABLE_CONFIG,
      ...DIALOG_CONFIG,
    };
  },
  computed: {
    dataMethod() {
      return API.getSourceList;
    },
    initRefresh: () => false,
  },
  methods: {
    async getTreeNodes() {
      const { value } = await API.queryTreeData();
      return { data: value || [] };
    },
    /**
     * @description: treeActions支持函数也支持数组，由于实际场景当中 可能会动态设置按钮，故以函数示例来展示
     * @param {*} data 当前点击节点数据
     * @return {*} 当前节点展示的操作项数组
     */
    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.filters['odsCatalogsId'] = node.id;
      this.refresh();
    },
    async addNode(params, node) {
      try {
        await API.addTreeNode(params);
        const tree = this.$refs.appAsyncTree.getElTree();
        tree.append(params, node);
      } catch (error) {
        console.log(error);
      }
      // addTreeNode
      // 此处仅为示例 实际为回调
    },
    async editNode(params, node) {
      try {
        const { code, name, parentId, id } = params;
        await API.editTreeNode({ code, name, parentId, id });
        this.$refs.appAsyncTree.getTreeData();
      } catch (error) {
        console.log(error);
      }
    },
    async delNode(params, node) {
      try {
        await API.delTreeNode(node.id);
        this.$refs.appAsyncTree.getTreeData();
      } catch (err) {
        this.$message.warning(err || '删除资源目录失败！');
      }
    },
    dataAdd() {
      this.dialogTitle = '新增贴源层数据源';
      this.dialogVisible = true;
    },
    async onAddConfirm(source) {
      /** 先注释*/
      // const params = {
      //   ...source,
      //   odsCatalogsId: this.curNode.id,
      //   dbSourceId: source.id,
      //   clusterMouldId: source.clusterId,
      // };
      // delete params.id;
      // delete params.clusterId;
      // delete params.deployed;
      //
      // try {
      //   await API.addSource(params);
      //   // this.$me
      //   this.refresh();
      // } catch (error) {
      //   console.log(error);
      // }

      const params = {
        catalogId: this.curNode.id,
        tableId: source.id,
      };

      try {
        await API.addByCompanySource(params);
        this.$message.success('操作成功');
        // this.$me
        this.refresh();
      } catch (error) {
        console.log(error);
      }

      console.log(params);
    },
    showDetail() {},
  },
};
</script>

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