<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--部门数据-->
        <pane size="23">
          <el-col>
            <div class="head-container">
              <span class="mb10 disInlineBlock">资源分组</span>
<!--              <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />-->
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :current-node-key="currentNodeKey" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--用户数据-->
        <pane size="77">
          <el-form :model="queryParams" ref="queryRef" v-show="showSearch" size="small" label-width="80px">
            <el-col :span="9">
              <el-form-item label="资源名称" prop="queryName">
                <el-input
                  v-model="queryParams.queryName"
                  placeholder="请输入资源名称/硬件SN"
                  clearable
                  @keyup.enter.native="handleQuery(1)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-form-item label="资源类型" prop="resourceType">
                <el-select
                  v-model="queryParams.resourceType"
                  placeholder="请选择资源类型"
                  clearable>
                  <el-option
                    v-for="dict in dict.type.rm_register_resource_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item class="lastBtnSty">
                <el-button type="primary" size="mini" icon="Search" @click="handleQuery(1)">搜索</el-button>
                <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-form>
          <input type="file" ref="fileInput" @change="handleFileChange" style="display: none;">
          <TableList :columns="columns" :config="config" :modelIdent="this.$options.name" :queryParams="queryParams" :tableList="roleList" @fnClick="callback" @fnRenderList="getList" @value-change="handleValueChange">
<!--            <template v-slot:tableExpand="slotProps">-->
<!--              <div v-for="(val, key) of expandList" style="padding: 5px 0 5px 70px;">-->
<!--                <div style="width: 150px;" class="ml10 disInlineBlock">{{val}}</div>-->
<!--                <div class="ml10 disInlineBlock">{{slotProps.row[key]}}</div>-->
<!--              </div>-->
<!--            </template>-->
            <!--    资源类型    -->
            <template #tempResType="{ row, column }">
              <dict-tag :options="dict.type.rm_register_resource_type" :value="row.resourceType"/>
            </template>
            <!--    在线状态    -->
            <template #tempOnlineStatus="{ row, column }">
              <dict-tag :options="dict.type.rm_register_online_state" :value="row.onlineStatus"/>
            </template>
          </TableList>
          <!--     新建文件夹     -->
          <el-dialog title="命令执行结果" :visible.sync="open" width="800px" append-to-body>
            <div class="block">
              <el-timeline :reverse="true">
                <el-timeline-item v-for="item of timelineList" :timestamp="item.createTime" placement="top">
                  <pre>{{item.content}}</pre>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-dialog>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script setup>
  import TableList from "@/components/table/index.vue"
  import EchartsPie from "@/components/echartsList/pie.vue"
  import {listRegisterList, delTopology, getResGroupList, getScriptResultBySn} from "@/api/disRevenue/resource"
  import { Splitpanes, Pane } from "splitpanes"
  import Treeselect from "@riophae/vue-treeselect"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css"
  import "splitpanes/dist/splitpanes.css"
  export default {
    name: 'RemoteManage',
    components: {TableList,EchartsPie, Splitpanes, Pane, Treeselect},
    dicts: ['rm_register_online_state', 'rm_register_resource_type'],
    data() {
      return {
        loading: true,
        // 部门名称
        deptName: undefined,
        // 所有部门树选项
        deptOptions: undefined,
        defaultProps: {
          children: "children",
          label: "label",
          disabled: true
        },
        currentNodeKey: 0, // 默认选中
        showSearch: true,
        roleList: [],
        queryParams: {
          total: 0,
          pageNum: 1,
          pageSize: 10,
          queryName: '',
          resourceType: ''
        },
        // 列显隐信息
        columns: {
          id: { label: `ID`, width: '50', visible: false },
          resourceName: { label: `资源名称`, minWidth: '250', visible: true },
          hardwareSn: { label: `硬件SN`, minWidth: '200'},
          description: { label: `描述`, minWidth: '200'},
          resourceType: { label: `资源类型`, minWidth: '100', slotName: 'tempResType'},
          inIp: { label: `内网IP`, minWidth: '160', visible: true},
          ipAddress: { label: `公网IP`, minWidth: '200', visible: true },
          resourcePort: { label: `管理端口`, minWidth: '160', visible: true},
          onlineStatus: { label: `在线状态`, minWidth: '160', slotName: 'tempOnlineStatus'},
        },
        config: {
          // expand: true, // 表格下拉
          tableButton: {
            line: [
              {content: '详情', fnCode: 'details', type: 'text', icon: 'el-icon-view', hasPermi: 'resource:fileManage:details'},
              // {content: '修改', fnCode: 'edit', type: 'text', icon: 'el-icon-edit', hasPermi: 'disRevenue:resource:fileManage:edit'},
              {content: '查看脚本执行结果', fnCode: 'result', type: 'text', icon: 'el-icon-s-check', hasPermi: 'resource:fileManage:result'},
              {}
            ]
          }
        },
        expandList: {
          switchName: '接口名称',
          switchSn: 'MAC地址',
          interfaceName: '接口类型',
          serverName: 'IPv4地址',

        },
        timelineList: [
          {content: '【服务器节点名称1】执行脚本命令', time: '2025-12-12 12:12:12'},
          {content: '【服务器节点名称1】执行脚本命令', time: '2025-12-11 12:12:12'},
          {content: '【服务器节点名称1】执行脚本命令', time: '2025-12-10 12:12:12'}
        ],
        open: false,
        title: '',
        moveList: [],
        catalogList: null,
        formList:{
          switchName: '',
          remarks: ''
        }
      }
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getDeptTree();
    },
    methods: {
      // 处理文件选择
      handleFileChange(e) {
        // console.log('e====',e);
        // const file = e.target.files[0]  // 获取第一个选中的文件
        // if (file) {
        //   selectedFile = file
        //   selectedFileName = file.name  // 显示文件名
        //   // 可选：自动上传
        //   // uploadFile()
        // } else {
        //   clearFile()  // 未选择文件时清空
        // }
      },
      /** 查询部门下拉树结构 */
      getDeptTree() {
        getResGroupList().then(res => {
          if (res && res.data) {
            let treeList = [{id: 0, label: '所有资源', disabled: false}];
            res.data && res.data.forEach(item => {
              treeList.push({id: item.id, label: item.groupName, disabled: false});
            });
            this.deptOptions = treeList;
            this.$refs.tree.setCurrentKey(0);
            this.getList();
          }
        })
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        if (data.id === 0) {
          delete this.queryParams.id;
        } else {
          this.queryParams.id = data.id;
        }
        this.handleQuery();
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        listRegisterList(this.queryParams).then(response => {
          this.roleList = response.rows;
          this.queryParams.total = response.total;
          this.loading = false;
        })
      },
      // 处理子组件传递的新值
      handleValueChange(newValue) {
        // 父组件更新自身数据，实现同步
        this.showSearch = newValue;
        // console.log('父组件拿到新值:', newValue);
      },
      /** 搜索按钮操作 */
      handleQuery(val) {
        if (val && val === 1) {
          delete this.queryParams.id;
          this.$refs.tree.setCurrentKey(0);
        }
        this.queryParams.pageNum = 1;
        this.getList();
      },

      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryRef");
        this.handleQuery(1);
      },

      submitForm(num){
        if (num === 1) {
          this.$refs['noticeRef'].validate((valid) => {
            if (!valid) {
              return false;
            }
            this.open = false;
          });
        }
      },
      /** 取消按钮 */
      cancel(val) {
        this.open = false;
      },

      callback(result, rowData, selectChange, selectList) {
        if (result && result.fnCode) {
          switch (result.fnCode) {
            case 'edit':
              this.$router.push({
                path:'/resource/remoteManage/view',
                query:{
                  id: rowData.id
                }
              });
              break;
            case 'details':
              this.$router.push({
                path:'/resource/remoteManage/view',
                query:{
                  hardwareSn: rowData.hardwareSn,
                  readonly: true
                }
              });
              break;
            case 'result':
              this.open = true;
              // 获取详情
              getScriptResultBySn({hardwareSn: rowData.hardwareSn}).then(val => {
                this.timelineList = val && val.data && val.data.scriptResult || [];
              }).catch(() => {
                this.$modal.msgError("操作失败")
              });
              break;
            case 'delete':
              this.$modal.confirm('是否确认删除数据项？').then(function() {
                return delTopology(selectChange)
              }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功")
              }).catch(() => {});
              break;
            default:
          }
        }
      }
    }
  }
</script>
<style scoped>
  ::v-deep .lastBtnSty .el-form-item__content{
    margin-left: 10px!important;
  }
  ::v-deep .el-table__expanded-cell {
    background: #f2f2f2!important;
  }
  ::v-deep .el-timeline .el-timeline-item:last-child .el-timeline-item__tail {
    display: block!important;
  }
  ::v-deep .el-tree-node__label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
