<template>
  <div class="newService">
    <div class="newService-head flex-wrap">
      <div class="manageTitle">{{ title }}</div>
      <div class="icons flex-wrap">
        <div class="icons-list start">
          <span class="icons-list-box"></span>
          <span class="icons-list-text">启用</span>
        </div>
        <div class="icons-list stop">
          <span class="icons-list-box"></span>
          <span class="icons-list-text">停用</span>
        </div>
        <div class="icons-list error">
          <span class="icons-list-box"></span>
          <span class="icons-list-text">异常</span>
        </div>
      </div>
    </div>
    <div class="newService-content flex-wrap">
      <div class="newService-content-left">
        <div class="newService-content-left-top">
          <div class="flex head">
            <div class="title">机器列表</div>
            <el-button @click="handleAdd" class="serButton" size="small">新增</el-button>
          </div>
          <div class="search">
            <el-input size="small" placeholder="请输入内容" clearable prefix-icon="el-icon-search" v-model="search">
            </el-input>
          </div>
        </div>
        <div class="newService-content-left-bottom">
          <template v-if="dataList.length">
            <el-scrollbar ref="scroll" style="height: 100%">
              <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
                <div v-for="(item,index) in dataList" :key="index" @click.stop="handleClick(item,index)" :class="index == activeIndex ? 'active':''" class="contents flex">
                  <div class="left">
                    <span :class="item.deploystate ? 'success' : 'error'" class="box"></span>
                    <el-tooltip class="item" effect="dark" :content="item.deployNodeName" placement="top">
                      <span class="txt">{{ item.deployNodeName }}</span>
                    </el-tooltip>
                  </div>
                  <div v-show="activeIndex == index" class="right">
                    <template v-if="!flag && item.deployNodeID">
                      <template v-if="item.serviceType == 4">
                        <span @click.stop="handleStart" v-if="!item.deploystate" class="start">启用</span>
                        <span @click.stop="handleStop" v-else class="stop">停用</span>
                      </template>
                      <template v-else>
                        <span @click.stop="handleRest(item)" class="rest">重置</span>
                      </template>
                    </template>
                    <span @click.stop="handleError" class="error">删除</span>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </template>
          <template v-else>
            <el-empty description="暂无数据"></el-empty>
          </template>
        </div>
      </div>
      <div class="newService-content-right">
        <div class="newService-content-right-top">
          <div class="flex">
            <div class="title">机器配置 {{ dataObj.deployNodeName }}</div>
            <el-button type="primary" @click="handleSave" :disabled="flag" class="bcButton" size="small">保存</el-button>
          </div>
          <div class="demo-form">
            <el-form label-width="70px" :model="formInline">
              <el-row :gutter="40">
                <el-col :span="6">
                  <el-form-item label="机器名称">
                    <el-input clearable v-model="formInline.deployNodeName" :disabled="activeIndex == null" size="small" placeholder="请输入服务名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="IP及端口">
                    <el-input clearable v-model="formInline.serviceURL" :disabled="activeIndex == null" size="small" placeholder="请输入IP及端口"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="部署位置">
                    <el-input clearable v-model="formInline.filepath" :disabled="activeIndex == null" size="small" placeholder="请输入部署位置"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
        <div :style="formInline.serviceType != 4 ? 'height: calc(100% - 180px);':'height: calc(100% - 305px);'" class="newService-content-right-bottom">
          <Table :dataId="dataId" :dataContent="msgContent" width="860px" tableHeight="calc(100% - 30px)" dataTitle="服务列表" />
        </div>
      </div>
    </div>
    <Dialog :flag="rmFlag">
      <div class="airportInfoDialog">
        <div class="title del-title">删除</div>
        <div class="content del-content">
          <span class="el-icon-error error r10"></span>您是否确认删除<span class="error l10">{{ dataObj.deployNodeName }}</span>
          ？
        </div>
        <div class="foot right Delfoot">
          <el-button size="medium" class="r24" @click="tableRemove" type="danger">删除</el-button>
          <el-button size="medium" @click="rmFlag = false">取消</el-button>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<script>
import Table from './components/table.vue'
import Dialog from "@/layout/components/Dialog/index.vue"
import { Query, newData, modifyData, moveData, start, stop } from "@/api/webApi"
import pf from '@/layout/mixin/publicFunc'
import * as _ from 'lodash'
export default {
  name: 'NewService',
  components: { Table, Dialog },
  mixins: [pf],
  data () {
    return {
      title: '服务设置',
      search: '',
      arrs: [],
      flag: true,
      formInline: {
        deployNodeName: '',
        serviceURL: '',
        filepath: ''
      },
      serviceType: [
        {
          label: '接收',
          value: 1
        },
        {
          label: '采集',
          value: 4
        }
      ],
      activeIndex: null,
      pageIndex: 0,
      pageSize: 9999,
      dataContent: {},
      queryId: '',
      dataObj: {},
      dataType: 'edit',
      noMore: false,
      loading: false,
      dataId: 8,
      msgContent: {},
      jqList: [],
      rmFlag: false
    }
  },
  computed: {
    dataList () {
      return this.arrs.filter(data => !this.search || data.serviceName.toLowerCase().includes(this.search.toLowerCase()))
    }
  },
  created () {
    const { title, qid } = this.$route.meta
    this.title = title
    this.queryId = qid
    this.getQuery(qid)
  },
  updated () {
    this.scrollDown()
  },
  methods: {
    async getQuery (id) {
      try {
        this.loading = true;
        const { code, returnData } = await Query({
          serviceId: id,
          page: ++this.pageIndex,
          pageSize: this.pageSize,
          dataContent: this.dataContent,
          event: '0'
        })
        if (code == 0) {
          if (returnData.length === 0) {
            this.pageIndex--;
            this.noMore = true;
          }
          this.arrs.push(...returnData)
          if (this.dataType == 'add') {
            const item = this.arrs[this.arrs.length - 1]
            if (Object.keys(item).length) {
              this.dataObj = item
              this.flag = false
              this.msgContent = item
            }
          }
          this.loading = false;
        } else {
          this.pageIndex--;
          this.loading = false;
        }
      } catch (error) {
        this.pageIndex--;
        this.loading = false;
      }
    },
    async getMsgList (id) {
      try {
        const { code, returnData } = await Query({
          serviceId: id,
          page: 1,
          pageSize: 99,
          dataContent: {},
        })
        if (code == 0) {
          this.jqList = returnData
        }
      } catch (error) {
        this.jqList = []
      }
    },
    load () {
      if (!this.noMore) {
        this.getQuery(this.queryId);
      }
    },
    scrollDown () {
      if (this.$refs['scroll'] && this.dataType == 'add') {
        this.$refs['scroll'].wrap.scrollTop = this.$refs['scroll'].wrap.scrollHeight
      }
    },
    resetTable () {
      this.pageIndex = 0;
      this.noMore = false;
      this.arrs = [];
    },
    //服务列表-新增
    handleAdd () {
      const datas = this.arrs.filter(item => item.deployNodeName == '新建机器')
      if (datas && datas.length) {
        return
      }
      this.dataType = 'add'
      this.flag = false
      this.dataObj.deployNodeName = '新建机器'
      this.arrs.push({ deployNodeName: '新建机器' })
      this.activeIndex = this.arrs.length - 1
      for (const key in this.formInline) {
        if (Object.hasOwnProperty.call(this.formInline, key)) {
          this.formInline[key] = null
        }
      }
      this.msgContent = {}
    },
    //服务列表-点击
    handleClick (item, index) {
      this.dataType = 'edit'
      this.dataObj = _.cloneDeep(item)
      this.formInline = _.cloneDeep(item)
      this.activeIndex = index
      this.flag = false
      this.msgContent = item
    },
    //服务列表-启用
    handleStart () {
      if (this.dataObj.deployNodeID && this.dataType == 'edit') {
        this.dataObj.runState = 1
        this.controlService(1, this.dataObj)
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].deployNodeID) {
        this.arrs[this.arrs.length - 1].runState = 1
        this.controlService(1, this.arrs[this.arrs.length - 1])
      }
      else {
        this.$message.error('请先添加当前服务后再操作')
      }
    },
    //服务列表-停用
    handleStop () {
      if (this.dataObj.deployNodeID && this.dataType == 'edit') {
        this.dataObj.runState = 0
        this.controlService(0, this.dataObj)
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].deployNodeID) {
        this.arrs[this.arrs.length - 1].runState = 0
        this.controlService(0, this.arrs[this.arrs.length - 1])
      }
      else {
        this.$message.error('请先添加当前服务后再操作')
      }
    },
    //服务列表-重置
    handleRest (item) {
      this.controlService(0, item)
    },
    //服务列表-保存
    async handleSave () {
      if (this.dataObj.deployNodeID && this.dataType == 'edit') {
        const { code } = await this.getChangeList(this.queryId, this.formInline, 2, 'deployNodeID')
        if (code) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
        } else {
          this.$message.success('操作失败')
        }
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].deployNodeID) {
        this.formInline.deployNodeID = this.arrs[this.arrs.length - 1].deployNodeID
        const { code } = await this.getChangeList(this.queryId, this.formInline, 2, 'deployNodeID')
        if (code) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
        } else {
          this.$message.success('操作失败')
        }
      } else if (this.dataType == 'add') {
        const { code } = await this.getChangeList(this.queryId, this.formInline, 1)
        if (code) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
        } else {
          this.$message.success('操作失败')
        }
      }
      else {
        this.$message.error('请先选中服务后再操作')
      }
    },
    async tableRemove () {
      if (this.dataObj.deployNodeID && this.dataType == 'edit') {
        const { code } = await this.getChangeList(this.queryId, this.dataObj, 3)
        if (code) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
        } else {
          this.$message.success('操作失败')
        }
        this.msgContent = {}
        this.activeIndex = null;
        this.dataObj = {};
        for (const key in this.formInline) {
          if (Object.hasOwnProperty.call(this.formInline, key)) {
            this.formInline[key] = null
          }
        }
        this.flag = true
      } else if (this.dataType == 'add' && this.arrs[this.arrs.length - 1].deployNodeID) {
        const { code } = await this.getChangeList(this.queryId, this.arrs[this.arrs.length - 1], 3)
        if (code) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
        } else {
          this.$message.success('操作失败')
        }
        this.msgContent = {
          service_id: ''
        }
        this.activeIndex = null;
        this.dataObj = {};
        for (const key in this.formInline) {
          if (Object.hasOwnProperty.call(this.formInline, key)) {
            this.formInline[key] = null
          }
        }
        this.flag = true
        this.dataType = 'edit'
      }
      else {
        this.arrs.splice(this.activeIndex, 1)
        this.activeIndex = null
        this.flag = true
        this.dataObj = {}
      }
      this.rmFlag = false
    },
    //服务列表-删除
    handleError () {
      this.rmFlag = true
    },
    //服务列表-增/删/改
    async generalDataReception (event, data) {
      try {
        const params = {
          serviceId: this.queryId,
          dataContent: data,
          event: `${event}`,
        };
        const { code } =
          event == 1
            ? await newData(params)
            : event == 2
              ? await modifyData(params)
              : await moveData(params);
        if (code == 0) {
          this.$message.success("操作成功");
          this.resetTable();
          this.getQuery(this.queryId);
        } else {
          this.$message.error("操作失败");
        }
      } catch (error) {
        this.$message.error("操作失败");
      }
    },

    //服务启停
    async controlService (event, data) {
      try {
        const params = {
          serviceId: data.deployNodeID
        };
        const { code } =
          event == 1
            ? await start(params)
            : await stop(params);
        if (code == 0) {
          this.$message.success('操作成功')
          this.resetTable()
          this.getQuery(this.queryId)
          // this.generalDataReception(2, data)
        } else {
          this.$message.error("操作失败");
        }
      } catch (error) {
        this.$message.error("操作失败");
      }
    },
  }
}
</script>

<style lang="scss" scoped>
@import "./css/index.scss";
</style>
