<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 :span="6" label="资源名称">
          <el-input v-model="filters.name" clearable placeholder="请输入" @keyup.enter.native="onQuery(filters)" />
        </app-filter-item>
        <app-filter-item :span="6" label="发布状态">
          <el-select v-model="filters.deployedStatus" clearable placeholder="请选择"
                     @keyup.enter.native="onQuery(filters)"
          >
            <el-option v-for="item in createdList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </app-filter-item>
      </app-filter>

      <!-- table列表 -->
      <div class="flex-1 pa-15 bg-white h-100 flex-col mt-11 border-radius-5">
        <div class="mb-15">
          <el-button icon="el-icon-plus" size="mini" type="primary" @click="addData">新增</el-button>
          <el-button :disabled="!multipleSelection.length > 0" icon="el-icon-delete" size="mini" type="danger"
                     @click="deleteRowChange"
          >删除
          </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
          @select-change="selectChange"
          @pagination-change="onPaginationChange"
          @row-dblclick="editData"
        >
          <template #isApi="scope">
            <el-tag :type="scope.row['isApi'] === '1' ? '' : 'danger'">{{ scope.row['isApi'] === '1' ? '是' : '否' }}
            </el-tag>
          </template>
          <template #isDatabase="scope">
            <el-tag :type="scope.row['isDatabase'] === '1' ? '' : 'danger'">
              {{ scope.row['isDatabase'] === '1' ? '是' : '否' }}
            </el-tag>
          </template>
          <template #isFile="scope">
            <el-tag :type="scope.row['isFile'] === '1' ? '' : 'danger'">{{ scope.row['isFile'] === '1' ? '是' : '否'
              }}
            </el-tag>
          </template>
          <template #deployed="scope">
            <el-tag :type="scope.row.deployedStatus === '1' ? 'primary' : 'warning'">
              {{ scope.row.deployedStatus === '1' ? '发布' : '未发布' }}
            </el-tag>
          </template>
        </app-table>
      </div>
    </div>
    <!-- 新增修改弹层 -->
    <add-edit-dialog v-model="dialogVisible" :data="currentRow" :title="dialogTitle" @confirm="onCompanyConfirm" />
    <fields-manage v-model="fieldDialogVisible" :data="currentRow" title="字段管理" @confirm="onCompanyConfirm" />
    <put-out-dialog v-model="putOutVisible" :data="currentRow" @confirm="onCompanyConfirm" />
    <!-- 资源授权 -->
    <resource-authorize v-if="resourceDialog" v-model="resourceDialog" :data="currentRow" :table-id="currentRow.id"
                        xqf-type="1"
                        @confirm="onCompanyConfirm"
    />
    <move-dialog v-model="dialogMove" :selected-rows="selectedRows" :title="MoveTitle"
                 @move-success="handleMoveSuccess" />
  </div>
</template>
<script>
import tableMixin from '@/mixins/table.js'
import AddEditDialog from './AddEditDialog.vue'
import fieldsManage from './fieldsManage.vue'
import API from '@/api/business/shareDataCatalog'
import PutOutDialog from './PutOutDialog.vue'
import ResourceAuthorize from './ResourceAuthorize.vue'
import MoveDialog from './MoveDialog.vue'

export default {
  components: {MoveDialog, ResourceAuthorize, PutOutDialog, fieldsManage, AddEditDialog},
  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: '资源目录编码不能为空'}]
        }
      ],
      curNode: {} // 当前选择节点
    }
    return {
      ...TREE_CONFIG,
      createdList: [
        {label: '发布', value: 1},
        {label: '未发布', value: 0}
      ],
      columns: [
        {label: '资源名称', prop: 'name'},
        {label: '数据库表名', prop: 'tableCode', width: '150px'},
        {label: '资源更新周期', prop: 'updateRate', width: '110px'},
        {label: '资源级别', prop: 'level', width: '80px', align: 'center'},
        {
          label: '是否开启库表共享',
          prop: 'isDatabase',
          dataType: 'slot',
          slot: 'isDatabase',
          width: '100px',
          align: 'center'
        },
        {label: '是否开启接口共享', prop: 'isApi', dataType: 'slot', slot: 'isApi', width: '100px', align: 'center'},
        {label: '是否开启文件共享', prop: 'isFile', dataType: 'slot', slot: 'isFile', width: '100px', align: 'center'},
        {label: '发布状态', prop: 'deployed', dataType: 'slot', slot: 'deployed', width: '100px', align: 'center'},
        {
          dataType: 'option',
          label: '操作',
          width: '250px',
          fixed: 'right',
          operation: [
            {
              name: '字段管理',
              type: 'text',
              size: 'mini',
              color: '#409eff',
              icon: 'el-icon-s-order',
              plain: true,
              clickFun: (row) => {
                this.currentRow = row
                this.fieldDialogVisible = true
              }
            },
            {
              name: '发布建表',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-s-promotion',
              color: '#fa912a',
              plain: true,
              showHide: row => {
                return row.deployedStatus !== '1'
              },
              clickFun: row => {
                this.putOutChange(row)
              }
            },
            {
              name: '资源授权',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-setting',
              plain: true,
              showHide: row => {
                return row.isDatabase === '1'
              },
              clickFun: (row) => {
                this.currentRow = row
                this.resourceDialog = true
              }
            },
            {
              name: '接口共享',
              type: 'text',
              size: 'mini',
              icon: 'el-icon-setting',
              plain: true,
              showHide: row => {
                return row.isApi === '1'
              },
              clickFun: (row) => {
                this.goTodataService(row)
              }
            },
            {
              name: '文件共享',
              icon: 'el-icon-tickets',
              type: 'text',
              size: 'mini',
              plain: true,
              showHide: row => {
                return row.isFile === '1'
              },
              clickFun: (row) => {
                this.gotoFile(row)
              }
            },
            {
              name: '删除',
              icon: 'el-icon-delete',
              color: 'red',
              clickFun: (row) => {
                this.delTable(row)
              }
            }
          ]
        }
      ],
      defaultFilter: [
        {
          operation: 'EQUAL',
          property: 'catalogId',
          relation: 'AND',
          value: ''
        }
      ],
      dialogVisible: false,
      fieldDialogVisible: false,
      putOutVisible: false,
      resourceDialog: false,
      dialogTitle: '新增',
      multipleSelection: [],
      dialogMove: false,
      MoveTitle: '移动'
    }
  },
  computed: {
    dataMethod() {
      return API.shareCatalogsTable
    }
  },
  methods: {
    // 左边树
    onBeforeGetData(queryParams, formData) {
      this.setFilterValue(this.queryParams, this.defaultFilter, 'catalogId', this.curNode.id)
    },
    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 || '删除资源目录失败！')
      }
    },
    // 新增：处理表格选择变化
    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() // 刷新数据
    },
    // 列表
    addData() {
      if (!this.curNode?.id) {
        this.$message.warning('请选择资源项所属目录')
        return
      }
      this.dialogTitle = '新增共享资源'
      this.currentRow = {
        catalogId: this.curNode.id
      }
      this.dialogVisible = true
    },
    editData(row) {
      this.dialogTitle = `编辑 - ${row.name}`
      this.currentRow = row
      this.dialogVisible = true
    },

    // 弹层回调
    onCompanyConfirm(data) {
      this.refresh()
    },
    // 列表按钮事件
    putOutChange(row) {
      this.currentRow = row
      this.putOutVisible = true
    },
    goTodataService(row) {
      // this.$router.push('/bizPlat/apiInterface');
      this.$router.push({name: 'shareDataCatalogApiInterface', query: {id: row.id}})
    },
    gotoFile(row) {
      this.$router.push({name: 'offlineFile', query: {id: row.id}})
    },
    gotoLibraryTable() {
      this.$router.push('/bizPlat/dataResource/dataShare/shareTable')
    },
    selectChange(data) {
      this.selectedRows = data
      this.multipleSelection = []
      data.forEach((item) => {
        this.multipleSelection.push(item.id)
      })
    },
    // 删除事件
    async deleteRowChange() {
      const delId = JSON.parse(JSON.stringify(this.multipleSelection)).join(',')
      this.$confirm('是否删除选中数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const {state} = await API.deleteTableData(delId)
          if (state) {
            await this.getData()
            this.$message.success('删除成功！')
          }
        } catch (err) {
          this.$message.warning(err || '删除失败！')
        }
      })
    },
    // 个别删除
    delTable(row) {
      this.$confirm(`此操作将删除（${row.name}）, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const {state, message} = await API.removeShare(row.id)
            if (state) {
              await this.getData()
              this.$message.success('删除成功！')
            } else {
              this.$message.warning(message || '删除失败！')
            }
          } catch (err) {
            this.$message.warning(err || '删除失败！')
          }
        })
        .catch(() => {
        })
    }
  }
}
</script>
<style scoped>
::v-deep .el-table__cell:first-child .cell {
  text-align: center;
}
</style>
