<template>
  <div class="sy-content">
    <el-row>
      <el-col :span="12">
        <el-form ref="queryForm" :inline="true" size="small" :model="queryParams">
          <el-form-item label="" prop="queryVal">
            <el-input placeholder="请输入采集器名称/IP" prefix-icon="el-icon-search" v-model="queryParams.queryVal"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handelSearch">搜索</el-button>
            <el-button type="info" icon="el-icon-refresh" size="small" @click="handelReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="12">
        <el-row style="float:right">
          <el-button size="small" icon="el-icon-plus" type="primary" style="margin-bottom: 20px"
                     @click="handelAdd">新增
          </el-button>

          <el-button size="small" icon="el-icon-download" type="primary" style="margin-bottom: 20px"
                     @click="downloadApp">采集器下载
          </el-button>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">

        <el-table ref="table" :loading="loading" :data="tableList" row-key="id" border stripe
                  header-row-class-name="headBackground">
          <!--          <el-table-column label="序号" type="index" width="70" align="center" />-->
          <el-table-column key="clientName" label="名称" prop="clientName" show-overflow-tooltip/>
          <el-table-column key="ipAddr" label="IP地址" prop="ipAddr" show-overflow-tooltip/>
          <el-table-column key="onLine" label="在线状态" prop="onLine" show-overflow-tooltip width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.onLine === 1 ? 'success' : 'info'">{{
                  scope.row.onLine === 1 ? "在线" : "离线"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column key="runStatus" label="运行状态" prop="runStatus" show-overflow-tooltip width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.runStatus === 1 ? 'success' : 'danger'">{{
                  scope.row.runStatus === 1 ? "运行" :
                    "停止"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <!--          <el-table-column key="createTime" label="创建时间" prop="createTime" show-overflow-tooltip />-->
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="500">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-tickets" @click="handelEdit(scope.row)">编辑
              </el-button>
              <el-button :disabled="scope.row.onLine !== 1"
                         size="mini" type="text" icon="el-icon-tickets" @click="handelConfig(scope.row.id)">配置
              </el-button>
              <el-button :disabled="scope.row.onLine !== 1"
                         size="mini" type="text" icon="el-icon-s-order"
                         @click="handelLog(scope.row.id)">日志
              </el-button>
              <el-button :disabled="scope.row.onLine !== 1"
                         size="mini" type="text" icon="el-icon-refresh" @click="refreshConfig(scope.row.id,scope.row.clientName,true)">刷新配置
              </el-button>
              <el-button v-if="(!scope.row.runStatus || scope.row.runStatus === 0)" :disabled="scope.row.onLine !== 1"
                         size="mini" type="text" icon="el-icon-video-play" :style="scope.row.onLine === 1?'color: #67c23a;':''"
                         @click="handelStart(scope.row.id, scope.row.clientName)">启动
              </el-button>
              <el-button v-if="scope.row.runStatus === 1" :disabled="scope.row.onLine !== 1"
                         size="mini" type="text"
                         icon="el-icon-video-pause" style="color: #f56c6c;" @click="handelStop(scope.row.id, scope.row.clientName)">停止
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" style="color: #f56c6c;"
                         @click="deleteCollector(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit"
                    align="right" @pagination="getCollectorList"/>
      </el-col>
    </el-row>

    <el-dialog :title="diatitle" :visible.sync="dialogAdd" width="800px" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="90px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入采集器名称"/>
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="addForm.ip" placeholder="请输入IP地址"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handelAddSubmit" size="mini">确定</el-button>
        <el-button @click="handelAddCancel()" size="mini">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="高级设置" :visible.sync="dialogSetting" width="800px" :close-on-click-modal="false">
      <el-form ref="configForm" :model="configForm" :rules="configRules" label-width="120px">
        <el-row :span="24">
          <el-col :span="11">
            <el-form-item label="间隔取整" prop="roundInterval">
              <el-radio-group v-model="configForm.roundInterval">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="将采集的间隔时间取整。比如，如果interval设置为10s，但我们在1分02秒启动了telegraf服务，那么采集的时间会取整到1分10秒，1分20秒，1分30秒"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
          <el-col :span="11">
            <el-form-item label="刷新间隔" prop="flushInterval">
              <el-input placeholder="请输入刷新间隔" v-model="configForm.flushInterval">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="所有output的输出间隔，这个参数不应该设的比interval（所有input组件的采集间隔）小"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :span="11">
            <el-form-item label="发送量" prop="metricBatchSize">
              <el-input placeholder="请输入发送量" v-model="configForm.metricBatchSize">
                <template slot="append">条</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="telegraf一批次从output组件向外发送数据的大小，网络不稳定时可以减小此参数。"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
          <el-col :span="11">
            <el-form-item label="缓存量" prop="metricBufferLimit">
              <el-input placeholder="请输入发送量" v-model="configForm.metricBufferLimit">
                <template slot="append">条</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="telegraf会为每个output插件创建一个缓冲区，来缓存指标数据，并在output成功将数据发送后，将成功发送的数据从缓冲区删除。所以，metriac_buffer_limit参数应该至少是metric_batch_size参数的两倍"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :span="11">
            <el-form-item label="采集抖动" prop="collectionJitter">
              <el-input placeholder="请输入采集抖动" v-model="configForm.collectionJitter">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="这个参数会在采集的时间点上加一个随机的抖动，这样可以避免很多插件同时查询一些消耗资源的指标，从而对被观测的系统产生不可忽视的影响。"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
          <el-col :span="11">
            <el-form-item label="刷新抖动" prop="flushJitter">
              <el-input placeholder="请输入刷新抖动" v-model="configForm.flushJitter">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-tooltip class="item" effect="dark"
                        content="对output的输出时间加上一个随机的抖动，这主要是为了避免大量的Telegraf实例在同样的时间同时执行写入操作，出现较大的写入峰值。比如，flush_jitter设为5s，flush_interval设为10s意味着会在10~15秒的时候进行一次输出。"
                        placement="top">
              <i class="el-icon-question" style="line-height: 36px;margin-left: 5px;"></i>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handelSettingSubmit()" size="mini">确定</el-button>
        <el-button @click="handelSettingCancel()" size="mini">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="配置采集器" :visible.sync="dialogConfig" width="800px" :close-on-click-modal="false" :before-close="handelConfigCancel">
      <el-row :span="24">
        <el-button size="mini" icon="el-icon-plus" type="primary" style="margin-bottom: 20px"
                   @click="itemAddBtn">新增
        </el-button>
        <el-button size="mini" icon="el-icon-setting" type="primary" style="margin-bottom: 20px"
                   @click="itemSettingBtn">高级设置
        </el-button>
      </el-row>
      <el-row :span="24">

        <el-table :data="itemTableData" height="250" border style="width: 100%">
          <el-table-column label="序号" type="index" width="70" align="left"/>
          <el-table-column key="group_name" label="数据组" align="left" prop="group_name" show-overflow-tooltip>
          </el-table-column>
          <el-table-column key="userName" label="创建用户" align="left" prop="userName" show-overflow-tooltip>
          </el-table-column>
          <el-table-column key="interval" label="采集间隔" align="left" prop="interval" show-overflow-tooltip/>
          <el-table-column key="unit" label="单位" align="left" prop="unit" show-overflow-tooltip/>
          <el-table-column label="操作" align="left" width="250" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-show="scope.row.isupdate==1" size="mini" type="text" icon="el-icon-edit"
                         @click="editItem(scope.row)">修改
              </el-button>
              <el-button v-show="scope.row.isupdate==1" size="mini" type="text" icon="el-icon-delete"
                         @click="delItem(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="false" type="primary" @click="handelConfigSubmit()" size="mini">确定</el-button>
        <el-button @click="handelConfigCancel()" size="mini">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="日志" :visible.sync="dialogLog" width="800px" :close-on-click-modal="false">
      <div style="height: 600px;overflow-y: auto;">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item v-for="item in LogList" :title="item.path + '（' + item.itemGroupName + '）'" :name="item.index">
            <div v-for="txt in item.log">{{ txt }}</div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-dialog>
    <el-dialog title="数据组配置" :visible.sync="groupDialog" width="500px" :close-on-click-modal="false">
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="120px">
        <el-form-item label="采集数据组" prop="itemGroupId">
          <el-select v-model="itemForm.itemGroupId" placeholder="请选择数据组" style="width: 100%;" @change="itemGroupChange">
            <el-option v-for="group in itemGroupList" :key="group.id" :label="group.groupName" :value="group.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采集间隔" prop="interval">
          <el-input placeholder="请输入采集间隔" v-model="itemForm.interval">
            <template slot="append">
              <div class="unit-my">
                <el-select v-model="itemForm.unit" style="width: 80px">
                  <el-option label="毫秒" value="ms"/>
                  <el-option label="秒" value="s" :disabled="isSubscribe"/>
                  <el-option label="分" value="m" :disabled="isSubscribe"/>
                  <el-option label="时" value="h" :disabled="isSubscribe"/>
                  <el-option label="天" value="d" :disabled="isSubscribe"/>
                </el-select>
              </div>

            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="itemFormSub" size="mini">确定</el-button>
        <el-button @click="itemFormClose()" size="mini">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {showLoading} from "@/utils/cqcy";
import {
  getClientStatus,
  getCollectorInfo,
  getCollectorInfoPage, getErrorFile,
  getLogFile,
  refreshConfig,
  saveCollector,
  saveConfigInfo,
  startClient,
  stopClient,
  deleteCollectorApi
} from "@/api/collector";
import {
  getAllItemGroup
} from '@/api/source/itemGroup';

export default {
  name: "index",
  data() {
    return {
      isSubscribe: false,
      dialogSetting: false,
      activeName: '0',
      loading: true,
      diatitle:'新增采集器',
      groupDialog: false,
      queryParams: {
        page: 1,
        limit: 10,
        queryVal: ''
      },
      tableList: [],
      total: 0,
      dialogAdd: false,
      addForm: {
        id: null,
        name: '',
        ip: ''
      },
      addRules: {
        name: [{
          required: true,
          message: '采集器名称不能为空',
          trigger: 'blur'
        }],
        ip: [{
          required: true,
          message: 'IP地址格式错误',
          pattern: '^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$',
          trigger: 'blur'
        }],
      },
      itemGroupList: [],
      dialogConfig: false,
      configForm: {
        id: 0,
        // 默认数据收集间隔
        interval: '1',
        // 是否在整点收集数据0、否1、是
        roundInterval: 1,
        // telegraf一批次从output组件向外发送数据的大小
        metricBatchSize: '1000',
        // 缓存指标数据，并在output成功将数据发送后，将成功发送的数据从缓冲区删除。metriac_buffer_limit参数应该至少是metric_batch_size参数的两倍
        metricBufferLimit: '10000',
        // 在采集的时间点上加一个随机的抖动，这样可以避免很多插件同时查询一些消耗资源的指标
        collectionJitter: '0',
        // output的输出间隔，这个参数不应该设的比interval
        flushInterval: '10',
        // output的输出时间加上一个随机的抖动，这主要是为了避免大量的Telegraf实例在同样的时间同时执行写入操作
        flushJitter: '0',
        // 收集的指标四舍五入为指定的精度
        precision: '',
        // 主机名
        hostname: '',
        // 不要在 Telegraf 代理中设置host标记0、否1、是
        omitHostname: 1,
        // 采集失败重试间隔
        restartDelay: '10',
        itemGroupId: ''
      },
      configRules: {
        interval: [{
          required: true,
          message: '收集间隔格式错误',
          pattern: '^([1-9][0-9]*)$',
          trigger: 'blur'
        }],
        roundInterval: [{
          required: true,
          message: '间隔取整不能为空',
          trigger: 'blur'
        }],
        metricBatchSize: [{
          required: true,
          message: '发送量格式错误',
          pattern: '^(0|[1-9][0-9]*)$',
          trigger: 'blur'
        }],
        metricBufferLimit: [{
          required: true,
          message: '缓存量隔格式错误',
          pattern: '^(0|[1-9][0-9]*)$',
          trigger: 'blur'
        }],
        collectionJitter: [{
          required: true,
          message: '采集抖动格式错误',
          pattern: '^(0|[1-9][0-9]*)$',
          trigger: 'blur'
        }],
        flushJitter: [{
          required: true,
          message: '输出抖动格式错误',
          pattern: '^(0|[1-9][0-9]*)$',
          trigger: 'blur'
        }],
        flushInterval: [{
          required: true,
          message: '输出间隔格式错误',
          pattern: '^([1-9][0-9]*)$',
          trigger: 'blur'
        }],
        restartDelay: [{
          required: true,
          message: '采集重试格式错误',
          pattern: '^([1-9][0-9]*)$',
          trigger: 'blur'
        }],
        omitHostname: [{
          required: true,
          message: '忽略主机名不能为空',
          trigger: 'blur'
        }],
        itemGroupId: [{
          required: true,
          message: '请选择要采集的数据组',
          trigger: 'blur'
        }],
      },
      dialogLog: false,
      LogList: [],
      statusTask: null,
      itemForm: {
        itemGroupId: '',
        interval: '10',
        unit: 's'
      },
      itemRules: {
        itemGroupId: [{
          required: true,
          message: '请选择要采集的数据组',
          trigger: 'blur'
        }],
        interval: [{
          required: true,
          //message: '采集间隔格式错误',
          //pattern: '^([1-9][0-9]*)$',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if(!/^([1-9][0-9]*)$/.test(value)){
              callback("采集间隔格式错误")
              return
            } else if (this.isSubscribe && parseInt(value) < 10) {
              callback("OPC UA 订阅模式采集间隔最低只支持10毫秒")
              return
            }
            callback()
          },
        }],
      },
      itemTableData: [],
      isItemEdit: false
    }
  },
  created() {
    this.getCollectorList();
    this.statusTask = setInterval(() => {
      this.getClientStatusByList();
      this.getClientErrorList();
    }, 15000)

  },
  beforeDestroy() {
    if (this.statusTask) {
      clearInterval(this.statusTask)
      this.statusTask = null
    }
  },
  methods: {
    itemGroupChange(e) {
      const data = this.itemGroupList.filter(item => item.id == e)[0]
      this.isSubscribe = data.subscribe == 1
      if (data.subscribe == 1) {
        this.itemForm.unit = 'ms'
        this.itemForm.interval = data.uaInterval
      }
    },
    /** 搜索 */
    handelSearch(event) {
      this.$resetBtn(event)
      this.queryParams.page = 1
      this.getCollectorList()
    },
    /** 重置按钮操作 */
    handelReset(event) {
      this.$refs['queryForm'].resetFields()
      this.handelSearch(event)
    },
    getCollectorList() {
      getCollectorInfoPage(this.queryParams).then((json) => {
        this.tableList = json.data.list || [];
        this.total = json.data.count || 0;
        this.getClientStatusByList();
      })
    },
    getClientStatusByList() {
      const data = this.tableList;
      if (data && data.length) {
        for (let i = 0; i < data.length; i++) {
          getClientStatus(data[i].ipAddr).then((json) => {
            const client = json.data;
            this.tableList[i].onLine = client.onLine;
            this.tableList[i].runStatus = client.runStatus;
          }).catch(e => {
            console.error(e)
          })
        }
      }
    },
    getClientErrorList() {
      const data = this.tableList;
      if (data && data.length) {
        // for (let i = 0; i < data.length; i++) {
        //   if (data[i].onLine === 1 && data[i].runStatus === 1) {
        //     getErrorFile(data[i].ipAddr).then((json) => {
        //       const client = json.data;
        //       if (client.logStatus === 1) {
        //         this.$message.error(`监测到${data[i].clientName}【${data[i].ipAddr}】近15分钟内有错误日志产生，请检查配置或联系维护人员`);
        //       }
        //     })
        //   }
        //
        // }
      }
    },
    handelAdd() {
      this.diatitle = '新增采集器'
      this.dialogAdd = true
    },
    handelAddCancel() {
      this.dialogAdd = false
      if (this.$refs['addForm']) {
        this.$refs['addForm'].resetFields()
      }
      this.addForm = {
        id: null,
        name: '',
        ip: ''
      }
    },
    handelAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          saveCollector(this.addForm).then((json) => {
            if (json.code != 200) {
              this.$message({
                message: json.msg,
                type: 'warning'
              })
              return;
            }
            this.$message({
              message: (this.addForm.id ? '编辑' : '新增') + '成功',
              type: 'success'
            })
            this.handelAddCancel()
            this.getCollectorList()
          })
        }
      })
    },
    handelConfig(id) {
      this.getAllItemGroup();
      getCollectorInfo(id).then((json) => {
        const data = json.data || {};
        this.configForm = {
          id,
          interval: (data.interval || 1).toString(),
          roundInterval: data.roundInterval || 1,
          metricBatchSize: (data.metricBatchSize || 1000).toString(),
          metricBufferLimit: (data.metricBufferLimit || 10000).toString(),
          collectionJitter: (data.collectionJitter || 0).toString(),
          flushInterval: (data.flushInterval || 10).toString(),
          flushJitter: (data.flushJitter || 0).toString(),
          precision: data.precision || '',
          hostname: data.hostname || '',
          omitHostname: data.omitHostname || 1,
          restartDelay: (data.restartDelay || 10).toString(),
          // itemGroupId: JSON.parse(data.itemGroupIds || '[]')
        }
        if (data.itemJson) {
          const itemData = JSON.parse(data.itemJson || '[]')
          this.itemTableData = itemData.map(item => {
            return {
              group_name: item.group_name,
              isupdate: item.isupdate,
              userName: item.userName,
              itemGroupId: item.itemGroupId,
              interval: item.itemInterval,
              unit: item.itemUnit
            }
          })
        }
        this.dialogConfig = true
      });
    },
    refreshConfig(id,clientName, showLoad) {
      let loading = null
      if(showLoad)loading = showLoading(this, '加载中，请稍候···')
      refreshConfig({
        id: id,
        clientName: clientName
      }).then((json) => {
        if(showLoad){
          loading.close()
          this.$message({
            message: json.msg,
            type: 'success'
          })
        }
        this.getClientStatusByList()
      }).catch(() => {
        if(showLoad)loading.close()
      })
    },
    getAllItemGroup() {
      let params = {
        page: 1,
        limit: 9999
      }
      getAllItemGroup(params).then((res) => {
        this.itemGroupList = res.data.itemGroupList
      })
    },
    handelConfigCancel() {
      if (this.$refs['configForm']) {
        this.$refs['configForm'].resetFields()
      }
      this.dialogConfig = false
      this.itemTableData = []
      //let data = this.configForm
      //this.refreshConfig(data.id,"")
    },
    handelConfigSubmit() {
      this.saveConfigInfo((data) => {
        this.refreshConfig(data.id,"", true)
        this.handelConfigCancel()
      })

    },
    saveConfigInfo(callback) {
      if (this.itemTableData.length === 0) {
        this.$message({
          message: '请配置需要采集的数据组',
          type: 'warning'
        })
        return;
      }
      const loading = showLoading(this, '加载中，请稍候···')
      let data = this.configForm;
      data.itemJson = JSON.stringify(this.itemTableData)
      saveConfigInfo(data).then((json) => {
        loading.close()
        if (json.code != 200) {
          this.$message({
            message: json.msg,
            type: 'warning'
          })
          return;
        }
        this.$message({
          message: '配置成功',
          type: 'success'
        })
        if (callback) callback(data)
      }).catch(() => {
        loading.close()
        this.handelConfig(data.id)
      })
    },
    handelStart(id, clientName) {
      const loading = showLoading(this, '加载中，请稍候···')
      startClient({
        id: id,
        clientName: clientName
      }).then((json) => {
        loading.close()
        this.$message({
          message: json.msg,
          type: 'success'
        })
        this.getClientStatusByList()
      }).catch(() => {
        loading.close()
      })
    },
    handelStop(id, clientName) {
      const loading = showLoading(this, '加载中，请稍候···')
      stopClient({
        id: id,
        clientName: clientName
      }).then((json) => {
        loading.close()
        this.$message({
          message: json.msg,
          type: 'success'
        })
        this.getClientStatusByList()
      }).catch(() => {
        loading.close()
      })
    },
    handelLog(id) {
      const loading = showLoading(this, '加载中，请稍候···')
      getLogFile(id).then((json) => {
        loading.close()
          getCollectorInfo(id).then((json2) => {
            if (json2.data?.itemJson) {
              const itemData = JSON.parse(json2.data.itemJson || '[]')
              let obj = {}
              itemData.forEach(item => {
                obj[item.itemGroupId] = item.group_name
              })
              this.LogList = json.data.map(item => {
                let id = item.path.substring(item.path.lastIndexOf('_') + 1)
                id = id.substring(0, id.indexOf('.'))
                item.itemGroupName = obj[id]
                return item
              })
            }
            this.dialogLog = true

          })
      }).catch(() => {
        loading.close()
      })
    },
    itemAddBtn() {
      this.groupDialog = true
      this.isItemEdit = false
      this.itemForm = {
        itemGroupId: '',
        interval: '10',
        unit: 's'
      }
    },
    itemFormSub() {
      this.$refs['itemForm'].validate((valid) => {
        if (!valid) return;

        let data = this.itemForm
        if (this.isItemEdit) {
          if (data.oldItemGroupId !== data.itemGroupId) {
            const arr = this.itemTableData.filter(item => {
              return data.itemGroupId === item.itemGroupId
            })
            if (arr.length) {
              this.$message({
                message: '当前数据组已配置',
                type: 'warning'
              })
              return
            }
          }
          this.itemTableData = this.itemTableData.map(item => {
            if (item.itemGroupId === data.oldItemGroupId) {
              return data
            }
            return item
          })
        } else {
          const arr = this.itemTableData.filter(item => {
            return data.itemGroupId === item.itemGroupId
          })
          if (arr.length) {
            this.$message({
              message: '当前数据组已配置',
              type: 'warning'
            })
            return
          }
          this.itemTableData.push(data)
        }
        this.saveConfigInfo((data) => {
          this.itemFormClose()
          this.handelConfig(data.id)
        })
      })
    },
    itemFormClose() {
      this.groupDialog = false
      this.itemForm = {
        itemGroupId: '',
        interval: '10',
        unit: 's'
      }
      this.isItemEdit = false
    },
    editItem(row) {
      const arr = this.itemTableData.filter(item => {
        return row.itemGroupId === item.itemGroupId
      })
      this.itemForm = {
        oldItemGroupId: arr[0].itemGroupId,
        itemGroupId: arr[0].itemGroupId,
        interval: arr[0].interval,
        unit: arr[0].unit
      }
      this.groupDialog = true
      this.isItemEdit = true
    },
    delItem(row) {
      this.itemTableData = this.itemTableData.filter(item => {
        return row.itemGroupId !== item.itemGroupId
      })
      this.saveConfigInfo((data) => {
        this.handelConfig(data.id)
      })
    },
    deleteCollector(row) {
      if (row.runStatus === 1 && row.onLine === 1) {
        this.$message({
          message: '采集器已启动，请先停止采集器再删除',
          type: 'warning'
        })
        return
      }
      this.$confirm('是否删除该采集器?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCollectorApi(row.id).then(json => {
          this.$message({
            type: json.code === 200 ? 'success' : 'warning',
            message: json.code === 200 ? '删除成功！' : json.msg
          });
          this.getCollectorList()
        })

      }).catch(() => {

      });
    },
    downloadApp() {
      window.open(process.env.VUE_APP_BASE_API + '/cy-collector.7z')
    },
    itemSettingBtn() {
      this.dialogSetting = true
    },
    handelSettingSubmit() {
      this.$refs['configForm'].validate((valid) => {
        if (valid) {
          this.saveConfigInfo((data) => {
            this.dialogSetting = false
            this.handelConfig(data.id)
          })
        }
      })
    },
    handelSettingCancel() {
      this.dialogSetting = false
    },
    handelEdit(row) {
      this.diatitle = '编辑采集器'
      this.dialogAdd = true
      this.addForm = {
        id: row.id,
        ip: row.ipAddr,
        name: row.clientName
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.unit-my {
  input {
    width: 80px;
  }
}
.fixed-width .el-button--mini {
  padding: 7px 0px;
}
</style>
