<template>
    <div class="app-container pageTopForm">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" size="small" label-width="auto">
          <el-col :span="6">
              <el-form-item label="搜索" title="搜索" prop="queryParam">
                  <el-input
                      v-model="queryParams.queryParam"
                      placeholder="请输入公网IP/私网IP/设备SN/clientID"
                      clearable
                      @keyup.enter.native="handleQuery"/>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="在线状态" title="在线状态" prop="onlineStatus">
              <el-select
                v-model="queryParams.onlineStatus"
                placeholder="请选择在线状态"
                clearable>
                <el-option
                  v-for="dict in dict.type.rm_register_online_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="多公网IP状态" title="多公网IP状态" prop="multiPublicIpStatus">
              <el-select
                v-model="queryParams.multiPublicIpStatus"
                placeholder="请选择多公网IP状态"
                clearable>
                <el-option
                  v-for="dict in dict.type.rm_moreip_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="注册状态" title="注册状态" prop="registrationStatus">
              <el-select
                v-model="queryParams.registrationStatus"
                placeholder="请选择注册状态"
                clearable>
                <el-option
                  v-for="dict in dict.type.rm_register_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务名称" title="业务名称" prop="businessName">
              <el-select
                v-model="queryParams.businessName"
                placeholder="请选择业务名称"
                clearable>
                <el-option
                  v-for="item in busNameList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="逻辑节点标识" title="逻辑节点标识" prop="logicalNodeId">
              <el-select
                v-model="queryParams.logicalNodeId"
                placeholder="请选择逻辑节点标识"
                clearable>
                <el-option
                  v-for="item in logicalNodeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="lastBtnSty">
                <el-button type="primary" size="mini" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>

        <!-- 表格数据 -->
      <TableList :columns="columns" :config="config" :modelIdent="this.$options.name" :queryParams="queryParams" :tableList="roleList" @fnClick="callback" @fnRenderList="getList" @value-change="handleValueChange">
        <template #tempCopy="{ row, column}">
          {{row.clientId}}<el-link :underline="false" icon="el-icon-document-copy" title="复制" v-clipboard:copy="row.clientId" v-clipboard:success="clipboardSuccess" style="margin-left: 10px;color: #409EFF;"></el-link>
        </template>
        <!--    多公网IP状态    -->
        <template #tempMultipubStatus="{ row, column }">
          <dict-tag :options="dict.type.rm_moreip_status" :value="row.multiPublicIpStatus"/>
        </template>
        <!--    注册状态    -->
        <template #tempStatus="{ row, column }">
          <dict-tag :options="dict.type.rm_register_status" :value="row.registrationStatus"/>
        </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" height="300px" append-to-body>
        <div class="block" style="max-height: calc(100vh - 125px);overflow: auto;">
          <template v-if="timelineList && timelineList.length > 0">
            <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>
          </template>
          <el-empty v-else :image-size="200"></el-empty>
        </div>
      </el-dialog>
      <!--    下发业务    -->
      <el-dialog :title="title" :visible.sync="issueOpen" width="800px" append-to-body style="padding-bottom: 20px;">
        <BusinessIssuedDetails :open="`type_${issueOpen}`" :dialogRowData="dialogRowData" @dialogResult="fnDialogResult"></BusinessIssuedDetails>
      </el-dialog>
      <!--    下发脚本策略    -->
      <el-dialog :title="title" :visible.sync="scriptOpen" width="800px" append-to-body style="padding-bottom: 20px;">
        <severScriptStratDetails :open="`type_${scriptOpen}`" :dialogRowData="dialogRowData" @dialogResult="fnDialogResult"></severScriptStratDetails>
      </el-dialog>
      <!-- 添加监控策略 -->
      <el-dialog title="添加监控策略" :visible.sync="stratOpen" width="1200px" append-to-body>
        <MonitorStrategy :open="`type_${stratOpen}`" :dialogRowData="dialogRowData" @dialogResult="fnDialogResult"></MonitorStrategy>
      </el-dialog>
      <!--   选择公网业务IP    -->
      <el-dialog title="选择公网业务IP" :visible.sync="pubilcNetOpen" width="800px" append-to-body style="padding-bottom: 20px;">
        <Form ref="publicNetFormRef" :formList="pubilcNetFormList" :ruleFormData="pubilcNetRuleForm" :config="{labelWidth: '140px', buttonGroup: []}" @fnClick="callback"></Form>
        <div style="text-align: right;margin-right: 20px;margin-bottom: 20px;">
          <el-button type="primary" style="margin-left: 10px;" @click="submitPubilc">提交</el-button>
          <el-button @click="callback({fnCode: 'cancel'})">取消</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script setup name="Register">
    import Form from '@/components/form/index.vue';
    import {listHandle, networkList, getScriptResultBySn, getLogicalNode} from '@/api/disRevenue/resource';
    import {listAllBusinessList} from "@/api/disRevenue/earnManage"
    import TableList from '@/components/table/index.vue';
    import MonitorStrategy from '../serverMonitorStrat/monitorStrategy';
    import severScriptStratDetails from '../serverScriptStrat/details';
    import BusinessIssuedDetails from '../../earnManage/businessIssued/details';
    export default {
      name: 'ServerRegister',
      components: {TableList, MonitorStrategy,Form, BusinessIssuedDetails, severScriptStratDetails},
      dicts: ['rm_moreip_status', 'rm_register_status', 'rm_register_online_state', 'policy_method'],
      data() {
        return {
          open: false,
          stratOpen: false,
          roleList: [],
          busNameList: [],
          loading: true,
          showSearch: true,
          ids: [],
          single: true,
          meltiple: true,
          // 列显隐信息
          columns: {
            id: { label: `ID`,width: '50'},
            clientId: { label: `clientID`, minWidth: '320', slotName: 'tempCopy'},
            hardwareSn: { label: `设备SN`,minWidth: '200'},
            ip1Isp: { label: `IP1-运营商`, visible: true, minWidth: '90'},
            ip1Province: { label: `IP1-省`, visible: true, minWidth: '80'},
            ip1City: { label: `IP1-市`, minWidth: '80'},
            ip1PublicIp:{ label: `IP1-业务公网`,visible: true,minWidth: '120'},
            ip1InterfaceName: { label: `IP1-接口名称`, minWidth: '100'},
            ip1MacAddress: { label: `IP1-mac地址`, minWidth: '150'},
            ip1InterfaceType: { label: `IP1-接口类型`, minWidth: '100'},
            ip1Ipv4Address: { label: `IP1-IPv4地址`, minWidth: '120'},
            ip1Gateway: { label: `IP1-网关`, minWidth: '120'},
            ip2Isp: { label: `IP2-运营商`, minWidth: '90'},
            ip2Province: { label: `IP2-省`,minWidth: '80'},
            ip2City: { label: `IP2-市`, minWidth: '80'},
            ip2PublicIp:{ label: `IP2-业务公网`,minWidth: '120'},
            ip2InterfaceName: { label: `IP2-接口名称`, minWidth: '100'},
            ip2MacAddress: { label: `IP2-mac地址`, minWidth: '150'},
            ip2InterfaceType: { label: `IP2-接口类型`, minWidth: '100'},
            ip2Ipv4Address: { label: `IP2-IPv4地址`, minWidth: '120'},
            ip2Gateway: { label: `IP2-网关`, minWidth: '120'},
            ip3Isp: { label: `IP3-运营商`, minWidth: '90'},
            ip3Province: { label: `IP3-省`, minWidth: '80'},
            ip3City: { label: `IP3-市`, minWidth: '80'},
            ip3PublicIp:{ label: `IP3-业务公网`,minWidth: '120'},
            ip3InterfaceName: { label: `IP3-接口名称`, minWidth: '100'},
            ip3MacAddress: { label: `IP3-mac地址`, minWidth: '150'},
            ip3InterfaceType: { label: `IP3-接口类型`, minWidth: '100'},
            ip3Ipv4Address: { label: `IP3-IPv4地址`, minWidth: '120'},
            ip3Gateway: { label: `IP3-网关`, minWidth: '120'},
            mgmtIsp: { label: `管理网-运营商`, minWidth: '110'},
            mgmtProvince: { label: `管理网-省`,minWidth: '80'},
            mgmtCity: { label: `管理网-市`, minWidth: '80'},
            mgmtPublicIp:{ label: `管理网-业务公网`,minWidth: '120'},
            mgmtInterfaceName: { label: `管理网-接口名称`, minWidth: '120'},
            mgmtMacAddress: { label: `管理网-mac地址`, minWidth: '150'},
            mgmtInterfaceType: { label: `管理网-接口类型`, minWidth: '120'},
            mgmtIpv4Address: { label: `管理网-IPv4地址`, minWidth: '120'},
            mgmtGateway: { label: `管理网-网关`, minWidth: '120'},
            heartbeatInterval: { label: `心跳时间间隔`, minWidth: '100'},
            heartbeatCount: { label: `心跳次数`, minWidth: '80'},
            registrationStatus: { label: `注册状态`, slotName: 'tempStatus', minWidth: '80', visible: true },
            businessName: { label: `业务名称`, minWidth: '100', visible: true},
            logicalNodeId: { label: `逻辑节点标识`, minWidth: '120', visible: true},
            onlineStatus: { label: `在线状态`, slotName: 'tempOnlineStatus', minWidth: '100', visible: true },
            multiPublicIpStatus: { label: `多公网IP状态`, slotName: 'tempMultipubStatus', minWidth: '120', visible: true },
            createTime:{ label: `注册时间`,minWidth: '160'},
            onboardTime:{ label: `上机时间`,minWidth: '160'},
            agentVersion:{ label: `agent版本`,minWidth: '90'},
            machineCode:{ label: `金山machineCode`,minWidth: '160'},
          },
          config: {
            tableButton: {
              top: [
                {content: '添加金山machineCode', fnCode: 'add', type: 'primary', icon: 'el-icon-plus', hasPermi: 'resource:serverRegister:add'},
                {content: '修改业务名称', fnCode: 'edit', type: 'success', icon: 'el-icon-edit', hasPermi: 'resource:serverRegister:edit'},
                {content: '导出', fnCode: 'export', type: 'warning', icon: 'el-icon-download', hasPermi: 'resource:serverRegister:export'},
              ],
              line: [
                {content: '选择业务IP', fnCode: 'pubilcNet', type: 'text', icon: 'el-icon-thumb', showName: 'multiPublicIpStatus', showVal: '0', hasPermi: 'resource:serverRegister:pubilcNet'},
                {content: '图形监控', fnCode: 'echartView', type: 'text', icon: 'el-icon-data-analysis', hasPermi: 'resource:serverRegister:graphicAnalysis'},
                {content: '详情', fnCode: 'details', type: 'text', icon: 'el-icon-view', hasPermi: 'resource:serverRegister:details'},
                {title: '更多', more: [
                    {content: '下发业务', fnCode: 'issueBusiness', type: 'text', icon: 'el-icon-circle-check', hasPermi: 'resource:serverRegister:issueBusiness'},
                    {content: '下发脚本策略', fnCode: 'issueScript', type: 'text', icon: 'el-icon-circle-check', hasPermi: 'resource:serverRegister:issueScript'},
                    {content: '下发监控策略', fnCode: 'issueMonitor', type: 'text', icon: 'el-icon-circle-check', hasPermi: 'resource:serverRegister:issueMonitor'},
                    {content: '查看执行结果', fnCode: 'result', type: 'text', icon: 'el-icon-s-check', hasPermi: 'resource:serverRegister:result'},
                  ]
                },{}
                // {content: '注册', fnCode: 'enroll', showName: 'registrationStatus', showVal: '0', type: 'text', icon: 'el-icon-circle-check', hasPermi: 'resource:register:enroll'},
                // {content: '取消注册', fnCode: 'unenroll', showName: 'registrationStatus', showVal: '1', type: 'text', icon: 'el-icon-circle-close', hasPermi: 'resource:register:unenroll'},
              ]
            }
          },
          queryParams: {
            pageNum: 1,
            pageSize: 10,
            total: 0
          },
          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'}
          ],
          issueOpen: false,
          scriptOpen: false,
          title: '',
          formList: [],
          ruleForm: {},
          pubilcNetOpen: false,
          pubilcNetFormList: [{
            config: {title: '',labelWidth: '140px', colSpan: 'disBlock m0Auto'},
            controls: {
              id: {label: 'ID',hidden: true},
              publicIp: {label: '业务公网IP', span: 18, eventName:'change', type: 'select',multiple: true, multipleLimit: 3, options: [], required: true},
              descriptionOne: {label: '', span: 18, type: 'textarea',rows: 15, disabled: true},
              mgmtIp: {label: '管理网-公网IP', eventName:'change', span: 18, type: 'select',options: [], required: true},
              descriptionTwo: {label: '', span: 18, type: 'textarea', rows: 15, disabled: true}
            }
          }],
          pubilcNetRuleForm: {publicIp: []},
          ipContentList: {},
          dialogRowData: {},
          logicalNodeList: [],

        }
      },
      created() {
        this.getList();
        this.fnBusNameList();
        this.fnLogicalNode();
      },
      activated() {
        this.$nextTick(() => {
          this.getList();
        });
      },
      methods: {
        fnBusNameList() {
          listAllBusinessList().then(val => {
            this.busNameList = val && val.data.map(item => {
              return Object.assign({label: item.businessName, value: item.businessName});
            });
          });
        },
        fnLogicalNode() {
          getLogicalNode().then(val => {
            this.logicalNodeList = val && val.map(item => {
              return Object.assign({label: item.logicalNodeId, value: item.logicalNodeId});
            });
          });
        },
        // 处理子组件传递的新值
        handleValueChange(newValue) {
          // 父组件更新自身数据，实现同步
          this.showSearch = newValue;
          // console.log('父组件拿到新值:', newValue);
        },
        /** 查询角色列表 */
        getList() {
          this.loading = true;
          listHandle(this.addDateRange(this.queryParams)).then(response => {
            this.roleList = response.rows;
            this.queryParams.total = response.total;
            this.loading = false;
          })
        },

        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParams.pageNum = 1
          this.getList()
        },

        /** 重置按钮操作 */
        resetQuery() {
          this.$refs['queryRef'].resetFields();
          this.queryParams = {pageNum: 1, pageSize: 10,total: 0};
          // this.resetForm("queryRef");
          this.handleQuery();
        },

        /** 多选框选中数据 */
        handleSelectionChange(selection) {
          this.ids = selection.map(item => item.roleId);
          this.single = selection.length != 1;
          this.multiple = !selection.length;
        },
        /** 复制代码成功 */
        clipboardSuccess() {
          this.$modal.msgSuccess("复制成功")
        },
        fnDialogResult(res){
          this.stratOpen = false;
          this.issueOpen = false;
          this.scriptOpen = false;
        },
        callback(result, rowData, selectChange, selectList) {
          if (result && result.fnCode) {
            switch (result.fnCode) {
              case 'add':
                this.$router.push("/resource/serverRegister/edit");
                break;
              case 'edit':
                console.log('selectList===',selectList);
                let clientIdList = '';
                if (selectList && selectList.length > 0) {
                  selectList.map(item => {
                    clientIdList+=item.clientId + '\n';
                  });
                }
                this.$router.push({
                  path:'/resource/serverRegister/edit',
                  query: {id: rowData.id, type: 'edit', clientIdList: clientIdList}
                });
                break;
              case 'details':
                this.$router.push({
                  path:'/resource/serverRegister/edit',
                  query: {id: rowData.id, readonly: true}
                });
                break;
              case 'echartView':
                this.$router.push({
                  path:'/resource/serverRegister/monitorChart',
                  query: {clientId: rowData.clientId}
                });
                break;
              case 'result':
                this.timelineList = [];
                // 获取详情
                getScriptResultBySn({clientId: rowData.clientId}).then(val => {
                  this.open = true;
                  this.timelineList = val && val.data && val.data.scriptResult || [];
                }).catch(() => {
                  this.open = true;
                  this.$modal.msgError("操作失败")
                });
                break;
              case 'pubilcNet':
                this.pubilcNetOpen = true;
                this.pubilcNetRuleForm = {publicIp: [],mgmtIp: '', descriptionOne: '', descriptionTwo: ''};
                this.$nextTick(() => {
                  // 5. 最后执行重置
                  if (this.$refs['publicNetFormRef']?.$refs.ruleForm) {
                    this.$refs['publicNetFormRef'].$refs.ruleForm.resetFields();
                  }
                });
                networkList({clientId: rowData.clientId}).then(res => {
                  let ipList = [];
                  res && res.data.map(item => {
                    this.ipContentList[item.id] = item;
                    ipList.push({label: item.publicIp, value: item.id});
                  });
                  this.pubilcNetFormList[0].controls.publicIp['options'] = ipList;
                  this.pubilcNetFormList[0].controls.mgmtIp['options'] = ipList;
                });
                break;
              case 'publicIp':
                let content = '';
                this.pubilcNetRuleForm = Object.assign({}, this.pubilcNetRuleForm, this.$refs.publicNetFormRef.$refs.ruleForm.model);
                if (rowData && rowData.length > 0) {
                  rowData.forEach(item => {
                    content+= '运营商：' + this.ipContentList[item].isp + '<br>' + '省：' + this.ipContentList[item].province + '<br>'
                      + '市：' + this.ipContentList[item].city + '<br>' + '公网IP：' + this.ipContentList[item].publicIp + '<br>'
                      + '接口名称：' + this.ipContentList[item].interfaceName + '<br>' + 'mac地址：' + this.ipContentList[item].macAddress + '<br>'
                      + '接口类型：' + this.ipContentList[item].interfaceType + '<br>' + 'IPv4地址：' + this.ipContentList[item].ipv4Address + '<br>'
                      + '网关：' + this.ipContentList[item].gateway + '<br><br>';
                  });
                }
                this.$set(this.pubilcNetRuleForm, 'descriptionOne', content);
                break;
              case 'mgmtIp':
                let contentTow = '';
                this.pubilcNetRuleForm = Object.assign({}, this.pubilcNetRuleForm, this.$refs.publicNetFormRef.$refs.ruleForm.model);
                if (rowData) {
                  contentTow+= '运营商：' + this.ipContentList[rowData].isp + '<br>' + '省：' + this.ipContentList[rowData].province + '<br>'
                    + '市：' + this.ipContentList[rowData].city + '<br>' + '公网IP：' + this.ipContentList[rowData].publicIp + '<br>'
                    + '接口名称：' + this.ipContentList[rowData].interfaceName + '<br>' + 'mac地址：' + this.ipContentList[rowData].macAddress + '<br>'
                    + '接口类型：' + this.ipContentList[rowData].interfaceType + '<br>' + 'IPv4地址：' + this.ipContentList[rowData].ipv4Address + '<br>'
                    + '网关：' + this.ipContentList[rowData].gateway + '<br><br>';
                }
                this.$set(this.pubilcNetRuleForm, 'descriptionTwo', contentTow);
                break;
              case 'issueBusiness':
                this.issueOpen = true;
                this.title = '下发业务任务';
                this.dialogRowData = rowData;
                break;
              case 'issueScript':
                this.scriptOpen = true;
                this.title = '添加脚本策略';
                this.dialogRowData = rowData;
                break;
              case 'executionMethod':
                if (rowData && rowData === '1') {
                  this.formList[0].controls.scheduledTime['hidden'] = false;
                } else {
                  this.formList[0].controls.scheduledTime['hidden'] = true;
                }
                break;
              case 'issueMonitor':
                this.stratOpen = true;
                this.dialogRowData = rowData;
                break;
              case 'submit':
                break;
              case 'cancel':
                this.issueOpen = false;
                this.pubilcNetOpen = false;
                break;
              case 'export':
                // let dataList = [];
                // Object.keys(this.columns).forEach(item => {
                //   if (item.visible) {
                //     dataList.push(item.prop);
                //   }
                // });
                // this.download("/system/registration/export", {properties: dataList,}, `资源管理_${new Date().getTime()}.xlsx`);
                let paramsList = Object.assign({}, this.queryParams,rowData);
                this.download("system/switchManagement/export", paramsList, `交换机管理_${new Date().getTime()}.xlsx`, null, 'json');
                break;
              default:

            }
          }
        },
        // form验证
        fnFormValid(val, model) {
          return new Promise((resolve) => {
            this.ruleFormData = {};
            const formValid = this.$refs[`${val}`].$refs.ruleForm;
            // 3. 操作form（如验证）
            formValid.validate((valid) => {
              if (valid) {
                if (formValid.model?.deployDevice) {
                  formValid.model.deployDevice = formValid.model.deployDevice.join('/n');
                }
                this[`${model}`] = formValid.model;
                resolve(true);
              } else {
                resolve(false);
              }
            });
          });
        },
        async submit(){
          if (!await this.fnFormValid('formRef', 'ruleFormData')) return;
          let fnType = addMachine;
          if (dataVal && dataVal.id) {
            fnType = updateTopology;
          }
          if(this.loading) return;
          this.loading = true;
          fnType(dataVal).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.issueOpen = false;
            this.loading = false;
          }).catch(() => {
            this.$modal.msgError("操作失败")
          });
        },
        async submitPubilc() {
          if (!await this.fnFormValid('publicNetFormRef', 'pubilcNetRuleForm')) return;
          let params = [];
          this.pubilcNetRuleForm.publicIp.forEach(item => {
            if (item && item === this.pubilcNetRuleForm.mgmtIp) {
              params.push({id: item, status: 3, interfaceName: this.ipContentList[item].interfaceName});
              delete this.pubilcNetRuleForm.mgmtIp;
            } else {
              params.push({id: item, status: 1, interfaceName: this.ipContentList[item].interfaceName});
            }
          });
          if (this.pubilcNetRuleForm && this.pubilcNetRuleForm.mgmtIp) {
            params.push({id: this.pubilcNetRuleForm.mgmtIp, status: 2, interfaceName: this.ipContentList[this.pubilcNetRuleForm.mgmtIp].interfaceName});
          }
          networkList({bindNetworkMsg: params}).then(res => {
            this.$modal.msgSuccess(res.msg);
            this.pubilcNetOpen = false;
            this.getList();
          });
        },
      }
    }
</script>

<style scoped>
  ::v-deep .lastBtnSty .el-form-item__content{
    margin-left: 10px!important;
  }
  ::v-deep .el-dialog__body {
    padding: 0 0 10px!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>
