<template>
  <div>
    <div class="menu-title">
      服务管理
    </div>
    <div class="menu-content">
      <div>
        <el-form :inline="true" :model="qo" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="qo.LIKES_name" placeholder="请输入服务名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="qo.LIKES_name" placeholder="请输入模型名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="qo.pageNo=1;queryData()">搜 索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table :data="result.records" style="width: 100%" ref="table">
          <el-table-column type="index" label="序号" width="100"></el-table-column>
          <el-table-column prop="name" label="服务名称"></el-table-column>
          <el-table-column prop="algorithmId" label="算法名称" :formatter="algorithmIdFormatter"></el-table-column>
          <!-- <el-table-column prop="version" label="版本"></el-table-column> -->
          <el-table-column prop="status" label="服务状态" :formatter="statusFormatter"></el-table-column>
          <el-table-column prop="url" label="接口地址"></el-table-column>
          <el-table-column prop="modifyTimeMillis" label="修改时间">
            <template slot-scope="scope">
              {{ scope.row.modifyTimeMillis | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column prop="createTimeMillis" label="创建时间">
            <template slot-scope="scope">
              {{ scope.row.createTimeMillis | timeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small"
                         @click.native.prevent="updateStatus(scope.row, 'start')" v-if="scope.row.status != 3">
                启动
              </el-button>
              <el-button @click.native.prevent="detailRow(scope.row)" type="text" size="small">
                详情
              </el-button>
              <el-button @click.native.prevent="updateStatus(scope.row, 'stop')" type="text" size="small" v-if="scope.row.status == 3">
                停止
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <el-pagination background
                       @current-change="handleCurrentChange"
                       :current-page="qo.pageNo"
                       :page-size="qo.pageSize"
                       layout="total, prev, pager, next"
                       :total="result.total">
        </el-pagination>
      </div>
    </div>
    <el-dialog
        title="服务详情"
        :visible.sync="cmdDialogVisible"
        @close="handleLogDialogClose"
        width="60%">
      <el-form ref="cmd" label-width="80px" :rules="rules" :model="cmd">
        <el-form-item label="请求地址" prop="address">
          <el-input placeholder="请输入请求地址" v-model="cmd.address"
                    disabled
                    class="input-with-select" @input="change($event)">
            <el-select v-model="cmd.requestType" slot="prepend" placeholder="请选择" style="width: 100px;">
              <el-option label="POST" value="post"></el-option>
              <el-option label="GET" value="get"></el-option>
              <el-option label="PUT" value="put"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-s-promotion" @click="submitHttp">发 送</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="参数">
          <el-table
              :data="params"
              ref="paramsTable"
              border
              @selection-change="handleSelectionChange"
              style="width: 100%">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                prop="type"
                label="参数类型">
              <template slot-scope="scope">
                <el-select v-model="scope.row.type" placeholder="请选择参数类型" :disabled="scope.row.isDisabled">
                  <el-option label="Int" value="int"></el-option>
                  <el-option label="Long" value="long"></el-option>
                  <el-option label="Double" value="double"></el-option>
                  <el-option label="String" value="string"></el-option>
                  <el-option label="Boolean" value="boolean"></el-option>
                  <el-option label="Float" value="float"></el-option>
                  <el-option label="Date" value="date"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
                prop="key"
                label="参数名">
              <template slot-scope="scope">
                <el-input v-model="scope.row.key" placeholder="请输入参数名" :disabled="scope.row.isDisabled"
                          @change="(val) => handleParamKeyChange(scope.row, val)"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                prop="value"
                label="参数值">
              <template slot-scope="scope">
                <template v-if="scope.row.index == 1">
                  <el-select v-model="scope.row.value" placeholder="请选择数据集">
                    <el-option :label="item.name" :value="item.id" :key="item.id"
                               v-for="item in dataSetList"></el-option>
                  </el-select>
                </template>
                <template v-if="scope.row.index != 1">
                  <template v-if="scope.row.type == 'boolean'">
                    <el-select v-model="scope.row.value" placeholder="请选择参数值">
                      <el-option label="True" value="true"></el-option>
                      <el-option label="False" value="false"></el-option>
                    </el-select>
                  </template>
                  <template v-if="scope.row.type == 'date'">
                    <el-date-picker
                        v-model="scope.row.value"
                        type="datetime"
                        placeholder="选择日期时间">
                    </el-date-picker>
                  </template>
                  <template v-if="scope.row.type != 'date' && scope.row.type != 'boolean'">
                    <el-input v-model="scope.row.value" placeholder="请输入参数值"></el-input>
                  </template>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="响应示例">
          <vue-json-editor
              v-model="resultJson"
              :mode="'code'"
              lang="zh"
              :show-btns="false"
              @json-change="onJsonChange"
              @json-save="onJsonSave"
              @has-error="onError"></vue-json-editor>
        </el-form-item>
        <div class="log-title-box">服务日志</div>
        <!--        <div class="log-box"></div>-->
        <log ref="log-item"></log>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request2';
import request3 from '@/utils/request3';
import vueJsonEditor from 'vue-json-editor';
import log from '@/components/log/index';
import request1, {getBaseUrl} from "@/utils/request";

var _this;
export default {
  name: "serviceManage",
  components: {
    vueJsonEditor,
    log
  },
  data() {
    return {
      qo: {
        pageNo: 1,
        pageSize: 10,
        LIKES_name: '',
      },
      result: {
        records: [],
        total: 0
      },
      cmdDialogVisible: false,
      cmd: {
        address: ''
      },
      params: [],
      paramsSelection: [],
      resultJson: {
        msg: 'success of test',
      },
      rules: {
        address: [
          {required: true, message: '请输入请求地址'}
        ],
      },
      algorithmList: [],
      statusList: {
        1: '保存状态',
        2: '开始',
        3: '运行中',
        4: '等待中',
        5: '结束',
        6: '发布失败',
        7: '取消',
        8: '训练中',
        9: '训练完成',
        10: '停止'
      },
      dataSetList: []
    }
  },
  mounted() {
    _this = this;
    _this.queryData();
    _this.queryAlgorithmList();
    _this.queryDataSetList();
  },

  filters: {
    timeFilter(val) {
      if (val > 0) {
        let dt = new Date(val);
        let year = dt.getFullYear();
        let month = dt.getMonth() + 1;
        let date = dt.getDate();
        let hour = dt.getHours();
        let minute = dt.getMinutes();
        let second = dt.getSeconds();
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
      } else {
        return "-";
      }
    }
  },
  methods: {
    queryDataSetList() {
      request1({
        url: '/remark_task/query_list',
        method: 'post',
        data: {}
      }).then(res => {
        _this.dataSetList = res.data;
      });
    },
    statusFormatter(row) {
      return _this.statusList[row.status] || '-';
    },
    algorithmIdFormatter(row) {
      let index = _this.algorithmList.findIndex(dataSet => {
        return row.algorithmId == dataSet.id;
      });
      return index >= 0 ? _this.algorithmList[index].name : '-';
    },
    queryAlgorithmList() {
      request({
        url: '/algorithm/list',
        method: 'post',
        data: {pageNo: 1, pageSize: 1000}
      }).then(res => {
        _this.algorithmList = res.list;
      });
    },
    // 数据改变是触发
    onJsonChange(value) {
      // console.log('value:', value)
    },
    // 点击保存时触发
    onJsonSave(value) {
      // console.log('value:', value)
    },
    onError(value) {
      // console.log('value:', value)
    },
    handleSelectionChange(val) {
      _this.paramsSelection = val;
    },
    handleParamKeyChange(row) {
      if (_this.params.length == row.index) {
        _this.params.push({
          index: _this.params.length + 1,
          type: 'string',
          key: '',
          value: ''
        });
        _this.$refs.paramsTable.toggleRowSelection(_this.params[_this.params.length - 1]);
      }
    },
    queryData() {
      request({
        url: '/model/serviceList',
        method: 'post',
        data: _this.qo
      }).then(res => {
        _this.result.records = res.list;
        _this.result.total = res.total;
      });
    },
    handleCurrentChange(val) {
      _this.qo.pageNo = val;
      _this.queryData();
    },
    handleLogDialogClose() {
      _this.$refs['log-item'].close();
    },
    detailRow(item) {
      _this.cmdDialogVisible = true;
      _this.$nextTick(() => {
        _this.$refs['log-item'].init({modelId: item.id, type: 'log_service'});
        _this.cmd = JSON.parse(JSON.stringify(item));
        if (!_this.cmd.requestType) {
          _this.cmd.requestType = "post";
        }
        _this.$refs.cmd.resetFields();
        _this.cmd.address = item.url;
        _this.params = [
          {
            index: 1,
            type: 'string',
            key: 'dataSetUrl',
            value: '',
            isDisabled: true
          }, {
            index: 2,
            type: 'string',
            key: '',
            value: ''
          }
        ];
        _this.$nextTick(() => {
          _this.$refs.paramsTable.toggleRowSelection(_this.params[0]);
          _this.$refs.paramsTable.toggleRowSelection(_this.params[1]);
        });

      });
    },
    change(e) {
      _this.$forceUpdate(e);
    },
    submitHttp() {
      let params = "";
      for (let i = 0; i < _this.paramsSelection.length; i++) {
        let pa = _this.paramsSelection[i];
        if (pa.key.toString().length > 0 && pa.value.toString().length > 0) {
          params += i == 0 ? '?' : '&';
          if (pa.isDisabled) {
            params += (pa.key + "=" + getBaseUrl() + "/es_remark_task/findbytaskidandtasktypeall/" + pa.value + "/1");
          } else {
            params += (pa.key + "=" + pa.value);
          }
        }
      }
      request3({
        url: _this.cmd.address + params,
        method: _this.cmd.requestType,
        data: {}
      }).then(res => {
        _this.$message.success('发送成功');
        _this.resultJson = res;
      });
      // console.log(_this.cmd);
    },
    updateStatus(item, action) { // 修改状态，重启start，停止stop
      let text = action === 'start' ? '启动' : '停止';
      _this.$confirm(`此操作将执行${text}操作, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: text+'中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        request({
          url: '/server/update/status',
          method: 'post',
          data: {
            modelId: item.id,
            action: action
          }
        }).then(res => {
          _this.$message.success(`${text}成功`);
          loading.close();
          _this.queryData();
        });
      }).catch(() => {
      });
    },
  }
}
</script>

<style lang="scss">
.jsoneditor-vue {
  height: 400px;
}


.jsoneditor-poweredBy {
  display: none;
}

.log-title-box {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.log-box {
  background-color: #c2c2c2;
  border-radius: 3px;
  min-height: 300px;
}
</style>
