<template>
  <div class="page-view flex-row-sb">
    <app-sync-tree
      ref="appAsyncTree"
      :actions="treeActions"
      :default-checked-keys="defaultCheckedKeys"
      :default-data="{ customConfigField: 'custom config field' }"
      :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>

      <div class="pa-11 bg-white h-100 flex-col mt-11 border-radius-5">
        <div class="mb-11">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="addosd"> 添加表</el-button>
          <el-button icon="el-icon-upload2" size="mini" type="primary" @click="dataAdd"> 导入表</el-button>
          <el-button :disabled="selectedRows.length === 0" icon="el-icon-refresh" size="mini" type="primary"
                     @click="dataMove"> 移动
          </el-button>
        </div>
        <app-table
          :column="columns"
          :pagination="pagination"
          :table-data="tableData"
          :table-loading="tableLoading"
          :total="total"
          checkbox
          @selection-change="handleSelectionChange"
          @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>
    <fields-manage v-model="fieldsVisible" :data="rowData" title="字段管理" @confirm="refresh" />
    <source-selector v-model="dialogVisible" :catalog-id="curNode.id" :data="currentRow" :title="dialogTitle"
                     @confirm="onAddConfirm" />
    <detail-dialog v-model="dialogdetail" :data="dialogdData" :title="detailTitle" @confirm="onConfirm" />
    <move-dialog v-model="dialogMove" :selected-rows="selectedRows" :title="MoveTitle"
                 @move-success="handleMoveSuccess" />
    <put-out-dialog v-model="putOutVisible" :data="currentRow" @confirm="refresh" />
  </div>
</template>

<script>
import API from '@/api/business/dataODSCatalog'
import tableMixin from '@/mixins/table.js' // 列表mixins
import FieldsManage from './FieldsManage'
import SourceSelector from './SourceSelector'
import DetailDialog from './DetailDialog.vue'
import MoveDialog from './MoveDialog.vue'
import PutOutDialog from '@/views/dataResource/sourceLayer/dataODSCatalog/PutOutDialog.vue'

export default {
  name: '',
  components: {PutOutDialog, SourceSelector, FieldsManage, DetailDialog, MoveDialog},
  mixins: [tableMixin],
  data() {
    const TREE_CONFIG = {
      treeProps: {
        value: 'id',
        label: 'name'
      },
      expandAll: false,
      defaultExpandedKeys: ['1'],
      defaultCheckedKeys: ['1'],
      // 此处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'},
        {label: '表资源编码', prop: 'code', width: '300'},
        {
          label: '数据库表名',
          width: '250',
          prop: 'tableNameEn'
        },
        {
          label: '发布状态',
          prop: 'deployed',
          width: '150',
          align: 'center',
          dataType: 'slot', // 使用插槽
          slot: 'deployed' // 插槽名，搭配 dataType: 'slot' 使用
        },
        {
          dataType: 'option',
          label: '操作',
          width: '240px',
          fixed: 'right',
          operation: [
            {
              name: '字段管理',
              icon: 'el-icon-s-order',
              color: '#409eff',
              // showHide: (row) => {},
              clickFun: (row) => {
                this.rowData = row
                this.fieldsVisible = true
              }
            },
            {
              name: '发布建表',
              icon: 'el-icon-s-promotion',
              color: '#fa912a',
              showHide: (row) => {
                return row.deployed !== 1
              },
              clickFun: (row) => {
                this.publishTable(row)
              }
            },

            {
              name: '删除',
              icon: 'el-icon-delete',
              color: 'red',
              // showHide: row => {
              //   return row.deployed !== 1;
              // },
              clickFun: (row) => {
                this.$confirm(`此操作将永久删除资源项（${row.name}）, 是否继续?`, '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(async () => {
                  try {
                    this.tableLoading = true
                    await API.delSource(row.id)
                    this.$message.success('数据已删除')
                    this.refresh()
                  } catch (error) {
                    this.tableLoading = false
                  }
                })
              }
            }
          ]
        }
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'odsCatalogsId',
          relation: 'AND',
          value: ''
        }
      ],
      rowData: {}
    }
    const DIALOG_CONFIG = {
      dialogVisible: false,
      fieldsVisible: false,
      dialogTitle: '导入',
      dialogdetail: false,
      detailTitle: '新增',
      dialogdData: {},
      putOutVisible: false,
      dialogMove: false,
      MoveTitle: '移动'
    }

    return {
      selectedRows: [], // 新增：存储选中的行数据
      treeData: [],
      ...TREE_CONFIG,
      ...TABLE_CONFIG,
      ...DIALOG_CONFIG
      // importData: { catalogId: '' },
    }
  },
  computed: {
    dataMethod() {
      return API.getSourceList
    }
    // initRefresh: () => false,
  },
  methods: {
    async getTreeNodes() {
      const {value} = await API.queryTreeData()
      this.defaultExpandedKeys = [value?.[0].id || '']
      return {data: value || []}
    },
    reloadTree() {
      this.$refs.appAsyncTree.getTreeData()
    },
    /**
     * @description: treeActions支持函数也支持数组，由于实际场景当中 可能会动态设置按钮，故以函数示例来展示
     * @param {*} data 当前点击节点数据
     * @return {*} 当前节点展示的操作项数组
     */
    treeActions(data) {
      // 根节点判断方式以业务为准，此处仅为示例
      return [
        {label: '添加', type: 'add', method: this.addNode},
        {
          label: '编辑',
          type: 'edit',
          method: this.editNode,
          showHide: (row) => {
            return row.id !== '1'
          }
        },
        {
          label: '删除',
          type: 'delete',
          method: this.delNode,
          showHide: (row) => {
            return row.id !== '1'
          }
        }
      ]
    },
    onTreeNodeClick(node) {
      if (node.id === this.curNode?.id) return
      this.curNode = {...node}
      // this.filters['odsCatalogsId'] = node.id;
      // this.importData.catalogId = this.curNode.id;
      this.refresh()
      this.getData()
    },
    // 新增目录
    async addNode(params, node) {
      const {code, name} = params
      const {id} = node
      const newNode = {
        code,
        name,
        parentId: id
      }
      try {
        const {state, message} = await API.addTreeNode(newNode)
        if (state) {
          this.reloadTree()
          this.$message.success('添加资源目录成功！')
        } else {
          this.$message.warning(message || '添加贴源层目录失败！')
        }
      } catch (err) {
        this.$message.warning(err || '添加贴源层目录失败！')
      }
    },
    // 编辑
    async editNode(params) {
      const {code, name, parentId, id} = params
      const newNode = {
        code,
        name,
        id,
        parentId
      }
      try {
        const {state, message} = await API.editTreeNode(newNode)
        if (state) {
          this.reloadTree()
          this.$message.success('编辑贴源层目录成功！')
        } else {
          this.$message.warning(message || '编辑贴源层目录失败！')
        }
      } catch (err) {
        this.$message.warning(err || '编辑贴源层目录失败！')
      }
    },
    // 删除
    async delNode(params, node) {
      try {
        const {state, message} = await API.delTreeNode(node.id)
        if (state) {
          this.reloadTree()
          this.$message.success('删除贴源层目录成功！')
        } else {
          this.$message.warning(message || '删除贴源层目录失败！')
        }
      } catch (err) {
        this.$message.warning(err || '删除贴源层目录失败！')
      }
    },
    // 新增资源项    (odsCatalogsId 目录ID)
    addosd() {
      if (!this.curNode?.id) {
        this.$message.warning('请选择资源项所属目录')
        return
      }
      this.detailTitle = '新增数据资源'
      this.dialogdData = {
        odsCatalogsId: this.curNode.id
      }
      this.dialogdetail = true
    },
    // 新增：处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      console.log(this.selectedRows, '勾选的数据')
    },

    dataMove() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一条要移动的数据')
        return
      }
      this.dialogMove = true
      this.MoveTitle = '移动表-请选择移动的目标目录'
    },
    // 新增：移动确认后的处理
    handleMoveSuccess() {
      this.selectedRows = [] // 清空选择
      this.refresh() // 刷新数据
    },

    // 编辑资源项
    showDetail(row) {
      this.detailTitle = `编辑 - ${row.name}`
      this.dialogdData = row
      this.dialogdetail = true
    },
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'odsCatalogsId', this.curNode.id)
    },
    // 新增确定按钮
    onConfirm(data, pData) {
      this.getData()
      this.refresh()
    },
    // 导入
    dataAdd() {
      this.dialogTitle = '导入贴源层数据源'
      this.dialogVisible = true
    },
    // 发布按钮
    async publishTable(data) {
      this.currentRow = data
      this.putOutVisible = true
    },
    // 导入按钮
    onAddConfirm() {
      this.getData()
    }
  }
}
</script>

<style lang="scss"
