<template>
  <div>
    <div>
      <el-form :inline="true" class="orderform" size="mini">
        <el-row>
          <el-form-item label="接口名称:">
            <el-input v-model="tag" style="width: 250px" placeholder="请输入..." class="search_tag" clearable/>
          </el-form-item>
          <!-- <el-form-item label="角色:">
            <el-select v-model="select_role" clearable placeholder="请选择状态" size="mini">
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"/>
            </el-select>
          </el-form-item> -->
          <el-form-item label="状态:">
            <el-select v-model="select_value" clearable placeholder="请选择状态" size="mini">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="接口类型:">
            <el-select v-model="apiTypeVal" clearable placeholder="请选择接口类型">
              <el-option
                v-for="item in apiTypes"
                :key="item.name"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btn_search()"><i class="el-icon-search"/> 搜索</el-button>
            <el-button @click="btn_clear()"><i class="el-icon-remove-outline"/> 重置</el-button>
            <el-button type="primary" @click="addApi()"><i class="el-icon-plus"/> 添加</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="tableData"
        :highlight-current-row="true"
        :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
        border align="center">
        <el-table-column
          prop="id"
          label="序列号"/>
        <el-table-column
          prop="name"
          label="接口名称"/>
        <el-table-column
          prop="url"
          label="请求地址"/>
        <!-- <el-table-column
          prop="callLimit"
          label="调用限制"/> -->
        <el-table-column
          prop="qpsLimit"
          label="QPS限制"/>
        <el-table-column
          :formatter="formatStatus"
          prop="status"
          label="接口状态"/>
        <!-- <el-table-column
          prop="apiType.name"
          label="接口类型"/> -->
        <el-table-column label="接口类型">
          <template slot-scope="scope">
            <span v-if="scope.row.apiType">{{ typeName(scope.row.apiType.id) }}</span>
            <span v-else/>
          </template>
        </el-table-column>
        <el-table-column
          prop="version"
          label="接口版本"/>
        <el-table-column
          prop="description"
          label="接口介绍"/>
        <el-table-column
          fixed="right"
          label="操作" width="160px">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetail(scope.row)">查看详情</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <!--el-button type="text" @click="handleDisable(scope.row)">停用/启用</el-button-->
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="pageNo"
          :page-sizes="[10, 50, 100, 300,1000]"
          :page-size="pageSize"
          :total="totalDataNumber"
          layout="sizes,total, prev, pager, next"
          class="table-pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>

    </div>

    <el-dialog :visible.sync="addFormVisible" title="新增接口" width="70%">
      <el-form :model="addForm" :rules="rules" style="height: 500px;overflow: hidden;overflow-y: auto;">
        <div class="flex">
          <div class="w-30">
            <el-form-item :label-width="formLabelWidth" label="接口名称" prop="name">
              <el-input v-model="addForm.name" placeholder="请输入类型名称"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口地址" prop="url">
              <el-input v-model="addForm.url" placeholder="请输入接口地址"/>
            </el-form-item>
            <!-- <el-form-item :label-width="formLabelWidth" label="调用量限制" prop="callLimit">
              <el-input v-model="addForm.callLimit" placeholder="请输入调用量限制"/>
            </el-form-item> -->
            <el-form-item :label-width="formLabelWidth" label="QPS限制" prop="qpsLimit">
              <el-input v-model="addForm.qpsLimit" placeholder="请输入QPS限制"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口状态" prop="status">
              <el-select v-model="addForm.status" placeholder="请选择接口状态">
                <el-option
                  v-for="item in options"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口类型" prop="apiType">
              <el-select v-model="addForm.apiTypeId" placeholder="请选择接口类型">
                <el-option
                  v-for="item in apiTypes"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口版本">
              <el-input v-model="addForm.version" placeholder="请输入接口版本"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="备注">
              <el-input
                v-model="addForm.description"
                type="textarea"
                maxlength="100"
                show-word-limit
                placeholder="请输入备注,最多100个字"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="黑名单">
              <el-input v-model="addForm.blackList" placeholder="多个请以英文逗号隔开"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="白名单">
              <el-input v-model="addForm.whiteList" placeholder="多个请以英文逗号隔开"/>
            </el-form-item>
          </div>
          <div class="flex-1 w-70" style="padding:0 20px;overflow:auto;height: 860px">
            <el-form-item label="请求方式">
              <el-select v-model="addForm.extJson.method" placeholder="请选择请求方式">
                <el-option
                  v-for="item in ['GET','POST']"
                  :key="item"
                  :label="item"
                  :value="item"/>
              </el-select>
            </el-form-item>
            <el-form-item label="请求headers">
              <div style="display: flex; justify-content: flex-end;margin-bottom: 10px;"><el-button size="mini" plain icon="el-icon-plus" @click.native="handleExtJsonAdd('headers')">添加参数</el-button></div>
              <el-table
                :data="addForm.extJson.headers"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                border>
                <el-table-column
                  prop="name"
                  label="参数名称">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入参数名称"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="required"
                  label="是否必填">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.required" placeholder="请选择是否必填">
                      <el-option
                        v-for="item in ['是','否']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="default"
                  label="默认值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.default" placeholder="请输入默认值"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="50">
                  <template slot-scope="scope">
                    <!-- <el-button type="text" @click="handleExtJsonAdd('headers')">添加</el-button> -->
                    <el-button type="text" @click="handleExtJsonDelete(scope.$index, 'headers')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="请求参数">
              <el-table
                :data="addForm.extJson.params"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                border>
                <el-table-column
                  prop="name"
                  label="参数名称">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入参数名称"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="type"
                  label="参数类型">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type" placeholder="请选择参数类型">
                      <el-option
                        v-for="item in ['String','Integer','Long','Double','Float','Boolean','Date','Array','Object']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="required"
                  label="是否必填">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.required" placeholder="请选择是否必填">
                      <el-option
                        v-for="item in ['是','否']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="default"
                  label="默认值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.default" placeholder="请输入默认值"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleExtJsonAdd('params')">添加</el-button>
                    <el-button type="text" @click="handleExtJsonDelete(scope.$index, 'params')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="返回参数">
              <i v-if="!isShow" size="mini" class="el-icon-caret-right" @click="isShow = !isShow"/>
              <i
                v-else
                size="mini"
                class="el-icon-caret-bottom"
                @click="isShow = !isShow"/>
              <el-table
                v-show="isShow"
                :data="addForm.extJson.returnParams"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                :tree-props="{children: 'children'}"
                border
                row-key="name"
                default-expand-all>
                >
                <el-table-column
                  prop="name"
                  label="参数名称"
                  width="150"/>
                <el-table-column
                  prop="value"
                  label="参数值"
                  width="100"/>
                <el-table-column
                  prop="type"
                  label="参数类型"
                  width="100"/>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="返回示例" required>
              <!-- <json-editor v-model="addForm.extJson.response" style="height: 100%"/> -->
              <vue-json-editor
                ref="jsonEditor"
                v-model="addForm.extJson.response"
                class="json-editor"
                lang="zh"
                mode="code"
                @json-change="onJsonChange($event,'add')"
                @json-save="onJsonSave"
                @has-error="onError($event,'add')"
              />
            </el-form-item>
          </div>

        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="btnAddCancel">取 消</el-button>
        <el-button type="primary" @click="btnAddSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="editFormVisible" title="编辑接口" width="70%">
      <el-form :model="editForm" :rules="rules" style="height: 500px;overflow: hidden;overflow-y: auto;">
        <div class="flex">
          <div class="w-30">
            <el-form-item :label-width="formLabelWidth" label="接口名称" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入接口名称"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口地址" prop="address">
              <el-input v-model="editForm.url" placeholder="请输入接口地址"/>
            </el-form-item>
            <!-- <el-form-item :label-width="formLabelWidth" label="调用量限制" prop="callLimit">
              <el-input v-model="editForm.callLimit" placeholder="请输入调用量限制"/>
            </el-form-item> -->
            <el-form-item :label-width="formLabelWidth" label="QPS限制" prop="qpsLimit">
              <el-input v-model="editForm.qpsLimit" placeholder="请输入QPS限制"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口状态" prop="status">
              <el-select v-model="editForm.status" placeholder="请选择接口状态">
                <el-option
                  v-for="item in options"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口类型" prop="apiType">
              <el-select v-model="editForm.apiTypeId" placeholder="请选择接口类型">
                <el-option
                  v-for="item in apiTypes"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="接口版本">
              <el-input v-model="editForm.version" placeholder="请输入接口版本"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="备注">
              <el-input
                v-model="editForm.description"
                type="textarea"
                show-word-limit
                maxlength="100"
                placeholder="请输入备注,最多100个字"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="黑名单">
              <el-input v-model="editForm.blackList" placeholder="多个请以英文逗号隔开"/>
            </el-form-item>
            <el-form-item :label-width="formLabelWidth" label="白名单">
              <el-input v-model="editForm.whiteList" placeholder="多个请以英文逗号隔开"/>
            </el-form-item>
          </div>
          <div class="flex-1 w-70" style="padding:0 20px;overflow:auto">
            <el-form-item label="请求方式">
              <el-select v-model="editForm.extJson.method" placeholder="请选择请求方式">
                <el-option
                  v-for="item in ['GET','POST']"
                  :key="item"
                  :label="item"
                  :value="item"/>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="请求类型">
              <el-select v-model="editForm.extJson.type" placeholder="请选择请求方式">
                <el-option
                  v-for="item in ['add','select']"
                  :key="item"
                  :label="item === 'add' ? '入库' : '查询'"
                  :value="item"/>
              </el-select>
            </el-form-item> -->
            <el-form-item label="请求headers">
              <div style="display: flex; justify-content: flex-end;margin-bottom: 10px;"><el-button size="mini" plain icon="el-icon-plus" @click.native="handleExtJsonAdd('headers','edit')">添加参数</el-button></div>
              <el-table
                :data="editForm.extJson.headers"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                border>
                <el-table-column
                  prop="name"
                  label="参数名称">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入参数名称"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="required"
                  label="是否必填">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.required" placeholder="请选择是否必填">
                      <el-option
                        v-for="item in ['是','否']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="default"
                  label="默认值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.default" placeholder="请输入默认值"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="50">
                  <template slot-scope="scope">
                    <!-- <el-button type="text" @click="handleExtJsonAdd('headers','edit')">添加</el-button> -->
                    <el-button type="text" @click="handleExtJsonDelete(scope.$index, 'headers','edit')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item label="请求参数">
              <el-table
                :data="editForm.extJson.params"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                border>
                <el-table-column
                  prop="name"
                  label="参数名称">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入参数名称"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="type"
                  label="参数类型">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type" placeholder="请选择参数类型">
                      <el-option
                        v-for="item in ['String','Integer','Long','Double','Float','Boolean','Date','Array','Object']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="required"
                  label="是否必填">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.required" placeholder="请选择是否必填">
                      <el-option
                        v-for="item in ['是','否']"
                        :key="item"
                        :label="item"
                        :value="item"/>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="default"
                  label="默认值">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.default" placeholder="请输入默认值"/>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleExtJsonAdd('params','edit')">添加</el-button>
                    <el-button type="text" @click="handleExtJsonDelete(scope.$index, 'params','edit')">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="editForm.extJson.type != 'add'" label="返回参数">
              <i v-if="!isShow" size="mini" class="el-icon-caret-right" @click="isShow = !isShow"/>
              <i
                v-else
                size="mini"
                class="el-icon-caret-bottom"
                @click="isShow = !isShow"/>
              <el-table
                v-show="isShow"
                :data="editForm.extJson.returnParams"
                :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
        :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}"
                :tree-props="{children: 'children'}"
                border
                row-key="name"
                default-expand-all
              >
                <el-table-column
                  prop="name"
                  label="参数名称"
                  width="150">
                  <!-- <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入参数名称"/>
                  </template> -->
                </el-table-column>
                <el-table-column
                  prop="value"
                  label="参数值"
                  width="100"/>
                <el-table-column
                  prop="type"
                  label="参数类型"
                  width="100"/>
                <el-table-column
                  prop="description"
                  label="参数说明">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.description" placeholder="请输入参数说明"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="editForm.extJson.type != 'add'" label="返回示例" required>
              <!-- <json-editor v-model="editForm.extJson.response" style="height: 100%"/> -->

              <vue-json-editor
                ref="jsonEditor"
                v-model="editForm.extJson.response"
                :show-btns="false"
                :expanded-on-start="true"
                class="json-editor"
                lang="zh"
                mode="code"
                @json-change="onJsonChange($event,'edit')"
                @json-save="onJsonSave"
                @has-error="onError($event,'edit')"
              />
            </el-form-item>
            <!--            <el-form-item :label-width="formLabelWidth" label="使用说明录入">-->
            <!--              <json-editor v-model="editForm.extJson" style="height: 100%"/>-->
            <!--            </el-form-item>-->
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnUpdateCancel">取 消</el-button>
        <el-button type="primary" @click="btnUpdateSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="disableFormVisible"
      title="提示"
      width="30%">
      <span v-if="status !== 0">确定对选择接口进行 <b>停用</b> 处理? </span>
      <span v-if="status === 0">确定对选择接口进行 <b>启用</b> 处理? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="disableFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDisable">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="提示"
      width="30%">
      <span>确定删除选择接口? </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import vueJsonEditor from 'vue-json-editor'
import APP_CONFIG from "../../../public/config";
export default {
  name: 'Index',
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  components: { vueJsonEditor },
  data() {
    return {
      rules: {
        name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
        url: [{ required: true, message: '请输入接口地址', trigger: 'blur' }],
        // callLimit: [{ required: true, message: '请输入调用量限制', trigger: 'blur' }],
        qpsLimit: [{ required: true, message: '请输入QPS限制', trigger: 'blur' }],
        status: [{ required: true, message: '请选择接口状态', trigger: 'blur' }],
        apiType: [{ required: true, message: '请选择接口类型', trigger: 'blur' }]
      },
      tag: '',
      select_value: '', // 用户状态
      select_role: '', // 接口角色
      options: [{
        value: 0,
        label: '未发布'
      }, {
        value: 1,
        label: '发布'
      }],
      roles: [],
      options1: [{
        value: 0,
        label: '免费使用'
      }, {
        value: 1,
        label: '付费开通'
      }, {
        value: 2,
        label: '测试使用'
      }, {
        value: 3,
        label: 'VIP使用'
      }],
      allData: [], // 所有前端分页数据
      tableData: [], // 表格数据 仅展示当前页的数据
      pageNo: 1, // 当前页数
      totalDataNumber: 0, // 总记录数
      pageSize: 10,
      formLabelWidth: '100px', // 弹出框form宽
      disableFormVisible: false,
      addFormVisible: false,
      editFormVisible: false,
      addForm: {
        name: '',
        url: '',
        callLimit: '',
        qpsLimit: '',
        status: '',
        apiTypeId: '',
        version: '',
        docUrl: '',
        description: '',
        extJson: '',
        blackList:'',
        whiteList:''
      },
      editForm: {
        id: '',
        name: '',
        url: '',
        callLimit: '',
        qpsLimit: '',
        status: '',
        apiTypeId: '',
        version: '',
        docUrl: '',
        description: '',
        extJson: '',
        blackList:'',
        whiteList:''
      },
      status: '',
      id: '',
      apiTypes: [],
      deleteId: '',
      deleteDialogVisible: false,
      apiTypeVal: '',
      hasJsonFlag: true,
      isShow: true
    }
  },
  created() {
    this.searchAllApiTypes()
    this.searchAllRoles()
    this.btn_search()
  },
  mounted() {
  },
  methods: {
    onJsonChange(value, type) {
      if (typeof value === 'object') {
        this.onJsonSave(value, type)
      }
      // 实时保存
    },
    onJsonSave(value, type) {
      const arr = []
      if (type === 'add') {
        this.addForm.extJson.response = value
        this.jsonPath(arr, value)
        this.addForm.extJson.returnParams = arr
      } else {
        this.editForm.extJson.response = value
        this.jsonPath(arr, value)
        this.editForm.extJson.returnParams = arr
      }
      this.hasJsonFlag = true
    },
    onError(value, type) {
      if (type === 'edit') {
        this.$message.error('请输入正确的json格式')
        this.editForm.extJson.returnParams = []
      } else {
        this.$message.error('请输入正确的json格式')
        this.addForm.extJson.returnParams = []
      }
      this.hasJsonFlag = false
    },
    // 检查json
    typeName(id) {
      const name = this.apiTypes.filter(val => val.id === id)[0].name
      return name
    },
    // 跳转详情
    handleDetail(item) {
      this.$router.push({
        path: `/apimngr/detail/${item.id}`
      })
    },
    searchAllRoles() {
      const vm = this
      axios.get(process.env.BASE_API + '/role/list', {
        params: {}
      }).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.roles = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.roles = obj.data
          } else {
            vm.roles = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    formatStatus(ob) {
      if (ob.status === 0) {
        return '未发布'
      } else if (ob.status === 1) {
        return '发布'
      } else {
        return '未知'
      }
    },
    searchAllApiTypes() {
      const vm = this
      axios.get(process.env.BASE_API + '/apitype/list', {}).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.apiTypes = []
        } else {
          if (parseInt(obj.total) > 0) {
            vm.apiTypes = obj.data
          } else {
            vm.apiTypes = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_search() {
      const vm = this
      axios.get(process.env.BASE_API + '/apimngr/list', {
        params: {
          tag: this.tag,
          status: this.select_value,
          roleId: this.select_role,
          apiTypeId: this.apiTypeVal
        }
      }).then(function(response) {
        const obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
          vm.totalDataNumber = 0
          vm.allData = []
          vm.tableData = []
        } else {
          vm.totalDataNumber = parseInt(obj.total)
          if (vm.totalDataNumber > 0) {
            vm.allData = obj.data
            try {
              // vm.allData.forEach(function(item) {
              //   item.extJson = item.extJson ? JSON.parse(item.extJson) : ''
              // })
            } catch (e) {
              // console.log(e)
            }
            // try {
            //   vm.allData.forEach(function(item) {
            //     item.extJson = item.extJson ? JSON.parse(item.extJson) : ''
            //   })
            // } catch (e) {
            //   vm.allData.forEach(function(item) {
            //     item.extJson = ''
            //   })
            // }
            vm.tableData = obj.data.slice(0, vm.pageSize)
            // console.log(vm.tableData)
          } else {
            vm.allData = []
            vm.tableData = []
          }
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    btn_clear() {
      this.tag = ''
      this.select_value = ''
      this.select_role = ''
      this.apiTypeVal = ''
      this.btn_search()
    },
    handleCurrentChange() {
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.tableData = this.allData.slice((this.pageNo - 1) * this.pageSize, this.pageNo * this.pageSize)
    },
    addApi() {
      const code = {
        'method': 'GET',
        'params': [
          {
            'name': 'token',
            'type': 'string',
            'required': '是',
            'description': 'token'
          }
        ],
        'returnParams': [
        ],
        'response': {
          code: 200,
          msg: 'success',
          data: {
            'acid': '123456'
          }
        },
        'headers': []
      }
      const arr = []
      this.jsonPath(arr, code.response)
      code.returnParams = arr
      this.addForm.name = ''
      this.addForm.url = ''
      this.addForm.callLimit = ''
      this.addForm.qpsLimit = ''
      this.addForm.status = ''
      this.addForm.apiTypeId = ''
      this.addForm.description = ''
      this.addFormVisible = true
      this.addForm.extJson = code
    },
    btnAddCancel() {
      this.addFormVisible = false
      this.addForm.name = ''
      this.addForm.description = ''
    },
    btnAddSubmit() {
      if (this.addForm.name === '' || this.addForm.name === undefined) {
        this.$message.info('请输入接口名称，不能为空')
        return
      }
      if (this.addForm.url === '' || this.addForm.url === undefined) {
        this.$message.info('请输入接口地址，不能为空')
        return
      }
      // if (this.addForm.callLimit === '' || this.addForm.callLimit === undefined) {
      //   this.$message.info('请输入接口调用量限制，不能为空')
      //   return
      // }
      if (this.addForm.qpsLimit === '' || this.addForm.qpsLimit === undefined) {
        this.$message.info('请输入接口qps限制，不能为空')
        return
      }
      if (this.addForm.status === '' || this.addForm.status === undefined) {
        this.$message.info('请选择接口状态，不能为空')
        return
      }
      if (this.addForm.apiTypeId === '' || this.addForm.apiTypeId === undefined) {
        this.$message.info('请选择接口类型，不能为空')
        return
      }
      if (this.hasJsonFlag && typeof this.addForm.extJson.response !== 'object') {
        return this.$message.error('请输入标准JSON 格式')
      }
      const vm = this
      const params = new URLSearchParams()
      params.append('name', vm.addForm.name)
      params.append('url', vm.addForm.url)
      params.append('callLimit', vm.addForm.callLimit)
      params.append('qpsLimit', vm.addForm.qpsLimit)
      params.append('status', vm.addForm.status)
      params.append('apiTypeId', vm.addForm.apiTypeId)
      params.append('description', vm.addForm.description)
      params.append('version', vm.addForm.version)
      params.append('docUrl', vm.addForm.docUrl)
      params.append('blackList', vm.addForm.blackList)
      params.append('whiteList', vm.addForm.whiteList)
      params.append('extJson', JSON.stringify(vm.addForm.extJson))
      axios.post(process.env.BASE_API + '/apimngr/insert', params).then(function(response) {
        const obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.addForm.name = ''
          vm.addForm.description = ''
          vm.addForm.version = ''
          vm.addFormVisible = false
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleEdit(row) {
      this.editForm.id = row.id
      this.editForm.name = row.name
      this.editForm.url = row.url
      this.editForm.callLimit = row.callLimit
      this.editForm.qpsLimit = row.qpsLimit
      this.editForm.status = row.status
      this.editForm.blackList = row.blackList
      this.editForm.whiteList = row.whiteList
      if (row.apiType) {
        this.editForm.apiTypeId = row.apiType.id
      }
      this.editForm.version = row.version
      this.editForm.docUrl = row.docUrl
      if (row.extJson) {
        this.editForm.extJson = JSON.parse(row.extJson)
        console.log(this.editForm.extJson)
        if (typeof this.editForm.extJson.response !== 'object' && this.editForm.extJson.response) {
          this.editForm.extJson.response = JSON.parse(this.editForm.extJson.response)
        }
        if (!this.editForm.extJson.headers) {
          this.editForm.extJson.headers = []
        }
      } else {
        this.editForm.extJson = {
          method: 'GET',
          params: [],
          returnParams: [],
          response: {
            code: 200,
            msg: 'success',
            data: {
              'acid': '123456'
            }
          },
          headers: []
        }
      }
      if (row.description === null) {
        this.editForm.description = ''
      } else {
        this.editForm.description = row.description
      }
      this.editFormVisible = true
    },
    btnUpdateCancel() {
      this.editFormVisible = false
      this.editForm.name = ''
      this.editForm.description = ''
    },
    btnUpdateSubmit() {
      if (this.editForm.name === '' || this.editForm.name === undefined) {
        this.$message.info('请输入接口名称，不能为空')
        return
      }
      if (this.editForm.url === '' || this.editForm.url === undefined) {
        this.$message.info('请输入接口地址，不能为空')
        return
      }
      // if (this.editForm.callLimit === '' || this.editForm.callLimit === undefined) {
      //   this.$message.info('请输入接口调用量限制，不能为空')
      //   return
      // }
      if (this.editForm.qpsLimit === '' || this.editForm.qpsLimit === undefined) {
        this.$message.info('请输入接口qps限制，不能为空')
        return
      }
      if (this.editForm.status === '' || this.editForm.status === undefined) {
        this.$message.info('请选择接口状态，不能为空')
        return
      }
      if (this.editForm.apiTypeId === '' || this.editForm.apiTypeId === undefined) {
        this.$message.info('请选择接口类型，不能为空')
        return
      }
      var vm = this
      var params = new URLSearchParams()
      // vm.editForm.extJson.response = JSON.stringify(vm.editForm.extJson.response)
      params.append('id', vm.editForm.id)
      params.append('name', vm.editForm.name)
      params.append('url', vm.editForm.url)
      params.append('callLimit', vm.editForm.callLimit)
      params.append('qpsLimit', vm.editForm.qpsLimit)
      params.append('status', vm.editForm.status)
      params.append('apiTypeId', vm.editForm.apiTypeId)
      params.append('description', vm.editForm.description)
      params.append('version', vm.editForm.version)
      params.append('docUrl', vm.editForm.docUrl)
      params.append('blackList', vm.editForm.blackList)
      params.append('whiteList', vm.editForm.whiteList)
      params.append('extJson', JSON.stringify(vm.editForm.extJson))
      axios.post(process.env.BASE_API + '/apimngr/update', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.editForm.name = ''
          vm.editForm.description = ''
          vm.editFormVisible = false
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDelete(row) {
      this.deleteId = row.id
      this.deleteDialogVisible = true
    },
    submitDelete() {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', this.deleteId)
      axios.post(process.env.BASE_API + '/apimngr/delete', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.btn_search()
          vm.deleteDialogVisible = false
        }
      }).catch(function(error) {
        alert(error)
      })
    },
    handleDisable(row) {
      this.id = row.id
      this.status = row.status
      this.disableFormVisible = true
    },
    submitDisable() {
      var vm = this
      var params = new URLSearchParams()
      params.append('id', vm.id)
      if (vm.status === 1) {
        params.append('status', 0)
      } else {
        params.append('status', 1)
      }
      axios.post(process.env.BASE_API + '/apimngr/disable', params).then(function(response) {
        var obj = response.data
        if (obj.code !== 10000) {
          vm.$message.error(obj.message)
        } else {
          vm.$message(obj.message)
          vm.btn_search()
        }
      }).catch(function(error) {
        alert(error)
      })
      this.disableFormVisible = false
    },

    handleExtJsonAdd(type, isEdit) {
      if (isEdit === 'edit') {
        this.editForm.extJson[type].push({
          name: '',
          type: '',
          required: '',
          description: '',
          default: ''
        })
        return
      }
      this.addForm.extJson[type].push({
        name: '',
        type: '',
        required: '',
        description: '',
        default: ''
      })
    },
    handleExtJsonDelete(index, type, isEdit) {
      if (isEdit === 'edit') {
        if (type !== 'headers') {
          if (this.editForm.extJson[type].length === 1) {
            this.$message.error('至少保留一个参数')
            return
          }
        }

        this.editForm.extJson[type].splice(index, 1)
        return
      }
      if (type !== 'headers') {
        if (this.editForm.extJson[type].length === 1) {
          this.$message.error('至少保留一个参数')
          return
        }
      }
      this.addForm.extJson[type].splice(index, 1)
    },
    jsonPath(arr, json) {
      const type = this.validateType(json)
      if (type === 'object') {
        for (const key in json) {
          const item = {
            name: key,
            description: ''
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.children = []
            this.jsonPath(item.children, json[key])
          } else {
            item.value = json[key]
          }
          arr.push(item)
        }
      } else if (type === 'array') {
        json = json[0]
        if (json === undefined || typeof json !== 'object') return
        for (const key in json) {
          const item = {
            name: key,
            description: ''
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.children = []
            this.jsonPath(item.children, json[key])
          } else {
            item.value = json[key]
          }
          arr.push(item)
        }
      }
    },
    validateType(val) {
      // 校验JSON数据类型
      const type = typeof val
      if (type === 'object') {
        if (Array.isArray(val)) {
          return 'array'
        } else if (val === null) {
          return 'null'
        } else {
          return 'object'
        }
      } else {
        return type
      }
    }
  }
}
</script>

<style>
.orderform {
  padding-top: 20px;
  padding-left: 10px;
  padding-right: 10px;
}

.mydiv {
  float: right;
  margin-right: 10px;
}
.jsoneditor-menu{

  background-color: #000 !important;
  border-bottom: 1px solid #000 !important;
}

.jsoneditor,.jsoneditor-mode-code{
  height: 500px !important;
}
.jsoneditor-contextmenu ul li button{
  color: #fff !important;
}
.jsoneditor-contextmenu ul li button:hover{
  background-color: #909090 !important;
}
</style>
