<template>
  <div class="autoIndex">
    <div class="searchArea">
      <el-form v-model="search" inline>
        <el-form-item class="form-item">
          <el-input
            v-model="search.blurNamespace"
            size="small"
            placeholder="命名空间"
          ></el-input>
        </el-form-item>

        <el-form-item class="form-item">
          <el-input
            v-model="search.blurServiceName"
            size="small"
            placeholder="服务名称"
          ></el-input>
        </el-form-item>
        <el-form-item class="form-item">
          <el-input
            v-model="search.exactVersion"
            size="small"
            placeholder="版本"
          ></el-input>
        </el-form-item>
        <el-form-item class="form-item" style="width: 30%">
          <el-button
            type="primary"
            size="small"
            class="search_button"
            @click="searchData"
            icon="el-icon-search"
            >查询</el-button
          >
          <el-button
            type="primary"
            @click="refresh"
            size="small"
            icon="el-icon-refresh"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="tableArea">
      <el-table
        v-loading="tableLoading"
        ref="singleTable"
        :data="tableData"
        :height="tableHeight"
        border
        drag-column
        class="yt-table-no-srcoll"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          prop="namespace"
          label="命名空间"
          align="center"
          :show-overflow-tooltip="true"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="serviceName"
          label="服务名"
          align="center"
          :show-overflow-tooltip="true"
          width="150"
        ></el-table-column>
        <el-table-column
          prop="version"
          label="版本"
          align="center"
          :show-overflow-tooltip="true"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="desc"
          label="配置描述"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="290">
          <template slot-scope="scope">
            <el-button
              size="mini"
              v-if="showHistory"
              @click="historyVersion(scope.row)"
              >历史版本1122</el-button
            >
            <el-button
              type="primary"
              size="mini"
              v-if="!showHistory"
              @click="goback"
              >返回</el-button
            >
            <el-button size="mini" @click="checkRow(scope.row, 'edit')"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="checkRow(scope.row, 'show')"
              >查看</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="checkRow(scope.row, 'publish')"
            >
              发布
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="foot-style">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 30, 40, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      :close-on-click-modal="closeFlag"
      v-if="dialogFormVisible"
      width="80%"
      :title="title"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        label-position="left"
        :model="form"
        :rules="rules"
        ref="form"
        :label-width="formLabelWidth"
      >
        <el-form-item label="配置描述" prop="desc">
          <el-input
            type="textarea"
            v-model="form.desc"
            :readonly="!isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item label="配置内容" prop="rules">
          <monaco-editor
            :language="'text'"
            :codes="form.content"
            @onMounted="textOnMounted"
            @onCodeChange="textOnCodeChange"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="isEdit">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import MonacoEditor from '@/components/monacoEditor'
export default {
  name: 'ConfigList',
  components: {
    MonacoEditor
  },
  data() {
    return {
      isEdit: false,
      showHistory: true,
      closeFlag: false,
      tableLoading: false, // 表格loading
      title: '新增',
      restaurants: [],
      tableHeight: '750px',
      tableData: [],
      userTag: '',
      search: {
        blurServiceName: '',
        blurNamespace: '',
        exactVersion: ''
      },
      dialogFormVisible: false,
      form: {
        scId: '',
        version: '',
        namespace: '',
        serviceName: '',
        desc: '',
        content: '',
        runningEnv: '',
        fileType: ''
      },
      formLabelWidth: '80px',
      rules: {
        // DataId: [
        //   { required: true, message: '请输入DataId', trigger: 'blur' }
        // ]
      },
      tagList: [{ tagname: '测试1' }, { tagname: '测试2' }, { tagname: 'test' }, { tagname: 'test2' }],
      total: 1,
      pageSize: 20,
      pageIndex: 1,
      textEditor: null,
      isShow: false
    }
  },
  mounted: function () {
    let h = document.body.clientHeight;
    this.tableHeight = h - 110;
    this.queryData();
    this.restaurants = this.loadAll();
  },
  watch: {
    dialogFormVisible: function (newV, oldV) {
      if (!newV) {
        this.cleraForm();
      }
    }
  },
  methods: {
    queryData: function (url, data) {
      let that = this,
        defaultParams = {
          pageSize: that.pageSize,
          currentPage: that.pageIndex
        },
        searchUrl = url || 'configCenter/microServiceConfig/getConfigsByPage',
        params = data || defaultParams;
      // defaultParams = {
      //   pageSize: that.pageSize,
      //   currentPage: that.pageIndex,
      //   blurServiceName: that.search.blurServiceName || '',
      //   blurNamespace: that.search.blurNamespace || 'eureka保留空间',
      //   blurCluster: that.search.blurCluster || '',
      //   exactVersion: that.search.exactVersion || ''
      // };
      that.tableLoading = true;
      that.axios.get(searchUrl, {
        params: params
      }
      ).then(function (response) {
        if (response) {
          let data = response.data.data;
          that.tableData = data;
          that.total = data.length;
          if (that.editScId) {
            that.$nextTick(() => {
              for (let i = 0; i < that.tableData.length; i++) {
                if (that.tableData[i].serviceName === that.editScId) {
                  that.$refs['singleTable'].setCurrentRow(that.tableData[i])
                  that.editScId = '';
                  break;
                }
              }
            })
          }
        }
        that.tableLoading = false;
      }).catch(function () {
        that.tableLoading = false;
      });
    },
    // 重置搜索
    refresh: function () {
      for (let i in this.search) {
        this.search[i] = ''
      }
      this.pageIndex = 1;
      this.searchData();
      // this.showHistory = true;
    },
    goback: function () {
      this.queryData();
      this.showHistory = true;
    },
    historyVersion: function (row) {
      let that = this,
        params = {
          pageSize: that.pageSize,
          currentPage: that.pageIndex,
          blurNamespace: '',
          blurServiceName: row.serviceName,
          exactVersion: ''
        }
      that.showHistory = false;
      that.queryData('configCenter/microServiceConfig/getConfigsByBlur', params);
    },
    searchData: function () {
      let that = this,
        params = {
          pageSize: that.pageSize,
          currentPage: that.pageIndex,
          blurNamespace: that.search.blurNamespace,
          blurServiceName: that.search.blurServiceName,
          exactVersion: that.search.exactVersion
        }
      that.queryData('configCenter/microServiceConfig/getConfigsByBlur', params);
    },
    checkRow: function (row, status) {
      let that = this;
      that.title = status === 'edit' ? '保存当前版本' : status === 'show' ? '查看当前版本' : '发布版本';
      for (let i in that.form) {
        that.form[i] = row[i]
      }
      that.isEdit = status === 'edit' || status === 'publish';
      that.dialogFormVisible = true;
    },
    cleraForm: function () {
      let that = this;
      that.form = {
        scId: '',
        version: '',
        namespace: '',
        serviceName: '',
        desc: '',
        content: '',
        runningEnv: '',
        fileType: ''
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    loadAll() {
      let tagArr = this.tagList;
      for (let i = 0; i < tagArr.length; i++) {
        tagArr[i].value = tagArr[i].tagname;
      }
      return tagArr
    },
    setForm: function () {
      let that = this;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let configData = JSON.stringify(that.form);
          if (that.title === '发布版本') {
            that.axios.post('configCenter/microServiceConfig/publish', configData, {
              diy: true,
              headers: {
                'Content-Type': 'application/json;charset=UTF-8'
              }
            }).then(res => {
              if (res.code === '0') {
                that.queryData();
                that.dialogFormVisible = false;
                that.editScId = that.form.serviceName;
                that.cleraForm();
                that.showHistory = true;
                that.$message.success('发布成功');
              }
            }).catch(function () {
            })
          } else {
            // 暂无新增
            that.axios.post('configCenter/microServiceConfig/save', configData, {
              diy: true,
              headers: {
                'Content-Type': 'application/json;charset=UTF-8'
              }
            }).then(function (response) {
              if (response.code === '0') {
                that.queryData();
                that.dialogFormVisible = false;
                that.showHistory = true;
                that.$message.success('修改成功');
                that.editScId = that.form.serviceName;
                that.cleraForm();
              }
            }).catch(function () {
            });
          }
        } else {
          return false;
        }
      });
    },
    handleCurrentChange(pageIndex) {
      this.pageIndex = pageIndex
      this.searchData();
    },
    handleSizeChange(pageSize) {
      this.pageIndex = 1
      this.pageSize = pageSize;
      this.searchData()
    },
    textOnMounted(edit) {
      this.jsonEditor = edit;
    },
    textOnCodeChange(value, event) {
      this.form.content = value;
      this.TextCodes = value;
    }
  }
}
</script>
<style>
.search_button {
  margin-left: 10px;
}
.autoIndex {
  padding: 15px;
}
.floatR {
  float: right;
}
.foot-style {
  margin: 5px 0 0;
  text-align: right;
}
.classTab {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  background: #eee;
  border-bottom: solid 1px #cecccc;
  text-align: left;
}

.classTab div {
  display: inline-block;
  cursor: pointer;
  color: #666;
  font-size: 12px;
  margin-right: 10px;
}

.classTab div span {
  margin: 0 5px;
  color: #666;
}

.classTab div:hover {
  color: #00c1de;
}

.choiceItem {
  color: #00c1de !important;
}

.pageTitle {
  width: 100%;
  height: 40px;
  line-height: 40px;
  border-left: solid 2px #0099cc;
  padding: 0 5px;
  font-size: 16px;
  color: #000;
  margin-bottom: 10px;
}
.pageTitle span {
  font-size: 12px;
  color: #ccc;
  margin-left: 10px;
}
.advancedQuery {
  width: auto;
  height: 28px;
  display: inline-block;
  line-height: 28px;
  color: #0099cc;
  cursor: pointer;
  margin-left: 20px;
}
.advancedQueryMenu {
  width: 100%;
  height: 38px;
  margin-bottom: 10px;
}
</style>
