<template>
  <div class="bigdata-api-list">
    <div class="category-list">
      <div class="btns">
        <el-button class="el-icon-edit" plain size="small" type="primary" @click="showCategory = true">编辑分类</el-button>
        <el-button icon="el-icon-plus" plain size="small" type="primary" @click="onEditCategory(null)">添加分类</el-button>
      </div>
      <el-input
        v-model="categoryKey"
        clearable
        placeholder="搜索分类"
        size="small"
        style="margin-bottom: 20px"
        @input="onSearchCategory"
      ></el-input>
      <el-menu :default-active="nowCategoryId" @select="onSelectCategory">
        <el-menu-item index="">
          <div class="name" style="flex: 1">全部分类</div>
        </el-menu-item>
        <el-menu-item v-for="category in categoryListSearched" :key="category.id" :index="category.id">
          <div class="name" style="flex: 1">{{ category.categoryName }}</div>
        </el-menu-item>
      </el-menu>
    </div>
    <div class="main-wrapper">
      <div class="my-menu">
        <div style="display: flex">
          <el-input v-model="searchKey" clearable placeholder="输入名称以筛选" size="small"></el-input>
          <el-button icon="el-icon-search" size="small" style="margin-left: 10px" type="primary" @click="getData">
            搜索
          </el-button>
        </div>
        <el-dropdown @command="onAdd">
          <el-button icon="el-icon-plus" plain size="small" type="primary">新建API</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">自定义SQL</el-dropdown-item>
<!--            <el-dropdown-item command="2">第三方查询</el-dropdown-item>-->
            <el-dropdown-item command="3">sql入库</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-table :data="tableData" border height="calc(100% - 120px)" size="small" :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
                :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
        <el-table-column label="名称" prop="apiName"></el-table-column>
        <el-table-column label="关键词" prop="apiKey"></el-table-column>
        <el-table-column label="请求地址" prop="apiUrl"></el-table-column>
        <el-table-column align="center" label="使用说明" width="90px">
          <template v-slot="{ row }">
            <el-button size="mini" type="text" @click="onShowSetting(row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="220px">
          <template slot-scope="api">
<!--            <el-button plain size="mini" type="success" @click="onPush(api.row)"> 发布</el-button>-->
            <el-button size="mini" type="text" @click="onCopy(api.row)"> 复制</el-button>
            <el-button size="mini" type="text" @click="onEditApi(api.row)"> 修改</el-button>
            <el-button size="mini" type="text" @click="onDelApi(api.row)"> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mydiv">
        <el-pagination
          :current-page.sync="page.current"
          :page-size="page.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="page.total"
          class="my-paging"
          layout="sizes,total, prev, pager, next"
          @size-change="sizeChange"
          @current-change="getData"
        ></el-pagination>
      </div>
    </div>
    <el-dialog :visible.sync="showCategory" append-to-body title="分类列表">
      <el-table :data="categoryList" border size="mini">
        <el-table-column label="分类名" prop="categoryName"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="onEditCategory(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="onDelCategory(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="showEditCategory" append-to-body title="编辑分类" width="400px">
      <el-form label-width="80px" size="mini">
        <el-form-item label="分类名">
          <el-input v-model="categoryForm.categoryName"></el-input>
        </el-form-item>
      </el-form>
      <el-button
        size="mini"
        style="width: 100px; margin: 30px auto 0; display: block"
        type="primary"
        @click="onEditCategoryConfirm"
      >
        保存
      </el-button>
    </el-dialog>
    <el-dialog
      :visible.sync="showSetting"
      append-to-body
      custom-class="api-list-setting"
      title="接口使用说明"
      width="900px"
    >
      <div class="title">请求地址</div>
      <div style="padding: 0 20px; font-size: 16px">{{ setting.apiUrl }}</div>
      <div class="title">请求方式</div>
      <div style="padding: 0 20px; font-size: 16px">{{ setting.type }}</div>
      <div class="title">请求头</div>
      <json-viewer :expand-depth="2" :value="setting.headers" sort></json-viewer>
      <div class="title">参数设置</div>
      <el-table :data="setting.params" border size="mini" max-height="200px">
        <el-table-column label="参数名" prop="name"></el-table-column>
        <el-table-column label="参数code" prop="key"></el-table-column>
        <el-table-column label="数据类型" prop="type"></el-table-column>
      </el-table>
      <div class="title">返回数据</div>
      <el-table :data="setting.fields" border size="mini" max-height="200px">
        <el-table-column label="字段名" prop="name"></el-table-column>
        <el-table-column label="字段code" prop="key"></el-table-column>
        <el-table-column label="字段类型" prop="type"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="showPush" append-to-body custom-class="api-list-setting" title="发布" width="900px">
      <el-form label-width="120px" size="mini">
        <el-form-item label="接口名称">
          <el-input v-model="pushFrom.name"></el-input>
        </el-form-item>
        <el-form-item label="接口地址">
          <el-input v-model="pushFrom.url"></el-input>
        </el-form-item>
        <el-form-item label="调用量限制">
          <el-input-number v-model="pushFrom.callLimit"></el-input-number>
        </el-form-item>
        <el-form-item label="QPS限制">
          <el-input-number v-model="pushFrom.qpsLimit"></el-input-number>
        </el-form-item>
        <el-form-item label="接口状态">
          <el-switch v-model="pushFrom.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="接口类型">
          <el-select v-model="pushFrom.apiTypeId" placeholder="请选择">
            <el-option v-for="item in apiTypeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接口版本号">
          <el-input v-model="pushFrom.version"></el-input>
        </el-form-item>
        <el-form-item label="接口描述">
          <el-input v-model="pushFrom.description" type="textarea"></el-input>
        </el-form-item>
        <!--提交-->
        <el-form-item>
          <el-button type="primary" @click="onPushConfirm">提交发布</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  dataapicategoryList,
  dataapiPage,
  dataapicategorySubmit,
  dataapicategoryRemove,
  dataapiRemove,
  api as prefix
} from '@/api/report/report';
import * as reportApis from "@/api/report/report";
import {random} from "lodash";
import { Base64 } from 'js-base64';
import APP_CONFIG from "../../../public/config";
export default {
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    }
  },
  data() {
    return {
      page: {total: 0, size: 20, current: 1},
      showCategory: false,
      showEditCategory: false,
      nowCategoryId: '',
      categoryKey: '',
      categoryListSearched: [],
      categoryList: [],
      tableData: [],
      searchKey: '',
      categoryForm: {},
      setting: {
        apiUrl: '',
        type: '',
        headers: {},
        params: [],
        fields: []
      },
      showSetting: false,
      //发布
      showPush: false,
      //接口类型列表
      apiTypeList: [],
      pushFrom: {
        name: '', //接口名称
        url: '', //接口地址
        callLimit: 10000, //调用次数
        qpsLimit: 2, //qps限制
        status: 1, //状态
        apiTypeId: 0, //接口类型
        description: '', //描述
        version: '', //版本
      }
    };
  },
  created() {
    this.getCategory();
  },
  methods: {
    onShowSetting(api) {
      let {apiUrl, apiType, note, apiHeaders, queryParam, apiMethod} = api;
      note = JSON.parse(note || '{}');
      queryParam = JSON.parse(queryParam || '[]');
      let showFields = note.showFields || [];
      let params = note.params || [];
      this.setting.apiUrl = apiUrl;
      if (apiType == 1) {
        this.setting.type = 'get';
        this.setting.headers = {};
        this.setting.params = params.map(i => ({name: i.name, key: i.key, type: i.datatype}));
        this.setting.fields = showFields.map(i => ({
          name: i.columnComments,
          key: i.columnName,
          type: i.dataType == 0 ? '维度' : '指标'
        }));
      } else if (apiType == 2) {
        this.setting.type = apiMethod;
        this.setting.headers = JSON.parse(apiHeaders || '{}');
        this.setting.params = params.map(i => ({name: i.name, key: i.key, type: i.datatype}));
        this.setting.fields = showFields.map(i => ({
          name: i.columnComments,
          key: i.columnName,
          type: i.dataType == 0 ? '维度' : '指标'
        }));
      } else {
        this.setting.type = 'post';
        this.setting.headers = {};
        this.setting.params = queryParam.map(i => ({name: i.title, key: i.paramName, type: i.columnType}));
        this.setting.fields = [];
      }
      this.showSetting = true;
    },
    getData() {
      let {size, current} = this.page;
      let data = {size, current, apiName: this.searchKey, categoryId: this.nowCategoryId};
      dataapiPage(data).then(res => {
        let {records, total} = res.data;
        records.forEach(item => {
          if (item.apiType == 1 || item.apiType == 3) {
            item.apiUrl =  prefix + item.apiUrl;
          }
        });
        this.tableData = records;
        this.page.total = total;
      });
    },
    onDelApi(api) {
      this.$confirm("确定删除此接口?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        dataapiRemove(api.id)
          .then((res) => {
            this.$message({type: "success", message: "删除成功"});
            this.getData();
          })
          .catch(() => {
          });
      });
    },
    onEditApi({apiType, id}) {
      let path = `/apimngr/apisql?id=` + id;
      if (apiType == 3){
        path = '/apimngr/apiedit3?id=' + id;
      }
      window.open(this.$router.resolve({path}).href, "_blank");
    },
    onAdd(type) {
      let path = '/apimngr/apisql';
      if (type == 3){
        path = '/apimngr/apiedit3';
      }
      window.open(this.$router.resolve({path}).href, "_blank");
    },
    onDelCategory(category) {
      this.$confirm("确定删除此分类?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        dataapicategoryRemove(category.id)
          .then((res) => {
            this.$message({type: "success", message: "删除成功"});
            this.getCategory();
          })
          .catch(() => {
          });
      });
    },
    onEditCategory(category) {
      if (!category) {
        this.categoryForm = {categoryName: '', orderIndex: 0};
      } else {
        this.categoryForm = {...category};
      }
      this.showEditCategory = true;
    },
    onEditCategoryConfirm() {
      if (!this.categoryForm.categoryName) {
        return this.$message({message: '请输入分类名', type: 'warning'});
      }
      dataapicategorySubmit(this.categoryForm).then(res => {
        this.$message({message: '已提交', type: 'success'});
        this.showEditCategory = false;
        this.getCategory();
      });
    },
    getCategory() {
      dataapicategoryList().then(res => {
        this.categoryList = res.data.sort((a, b) => a.orderIndex > b.orderIndex ? 1 : -1);
        this.categoryListSearched = [...this.categoryList];
        this.getData();
      }).catch((res)=>{
      });
    },
    onSelectCategory(id) {
      this.nowCategoryId = id;
      this.getData();
    },
    onSearchCategory() {
      this.categoryListSearched = this.categoryList.filter(i => i.categoryName.includes(this.categoryKey));
    },
    sizeChange(size) {
      this.page.size = size;
      this.getData();
    },
    onCopy(data) {
      console.log(data)
      // let showFields = [...this.availableParamList,];
      // let params = this.paramsList;
      // data.note = JSON.stringify({showFields, params});
      // data.apiHeaders = JSON.stringify({...this.headerObject});
      delete data.id;
      data.apiName = data.apiName + '_copy';
      data.apiKey = data.apiName + random(1000, 9999);
      reportApis.dataapiSubmit(Base64.encode(JSON.stringify(data))).then((res) => {
        this.$message({type: "success", message: "保存成功"});
        this.getData();
      });
    },
    onPush(e) {
      console.log(e)
      this.showPush = true;
      this.$request({
        url: 'http://10.10.15.26:8080/gateway-api/api/apitype/list',
        method: 'get',
        headers: {
          token:'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDE4ODUzOTAsInVzZXJuYW1lIjoiYWRtaW4ifQ.K4UwaVqSiX3CO3YZb8wjc911P-BGMJO_wc600hb1ppk'
        }
      }).then(res =>　{
        let typeList = res.data;
        this.apiTypeList = typeList.data;
        this.showPush = true;
        this.pushFrom = {
          name: e.apiName, //接口名称
          url: e.apiUrl, //接口地址}
          callLimit: 10000, //调用次数
          qpsLimit: 2, //qps限制
          status: e.apiStatus, //状态
          apiTypeId: this.apiTypeList[0].id, //接口类型
          description: '', //描述
          version: '1.0.0', //版本
        };
      }).catch(err => {
        console.log(err)
      })
    },
    onPushConfirm() {
      if (!this.pushFrom.name) {
        return this.$message({message: '请输入接口名称', type: 'warning'});
      }
      if (!this.pushFrom.url) {
        return this.$message({message: '请输入接口地址', type: 'warning'});
      }
      if (!this.pushFrom.callLimit) {
        return this.$message({message: '请输入调用次数', type: 'warning'});
      }
      if (!this.pushFrom.qpsLimit) {
        return this.$message({message: '请输入qps限制', type: 'warning'});
      }
      if (!this.pushFrom.apiTypeId) {
        return this.$message({message: '请选择接口类型', type: 'warning'});
      }
      if (!this.pushFrom.description) {
        return this.$message({message: '请输入描述', type: 'warning'});
      }
      if (!this.pushFrom.version) {
        return this.$message({message: '请输入版本', type: 'warning'});
      }
      this.$request({
        url: 'http://10.10.15.26:8080/gateway-api/api/apimngr/insert',
        method: 'post',
        data: this.pushFrom,
        headers: {
          token:'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDE4ODUzOTAsInVzZXJuYW1lIjoiYWRtaW4ifQ.K4UwaVqSiX3CO3YZb8wjc911P-BGMJO_wc600hb1ppk'
        }
      }).then(res => {
        this.$message({message: '已提交', type: 'success'});
        this.showPush = false;
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.bigdata-api-list {
  display: flex;
  overflow: hidden;
  height: 100%;
  .btns {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    .el-button {
      width: 125px;
    }
  }
  .category-list {
    flex: 0 0 260px;
    padding-top: 10px;
    padding-right: 10px;
    border-right: 1px solid #ccc;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .el-menu {
      flex: 1;
      overflow-y: auto;
      .el-menu-item {
        padding: 0 5px 0 10px;
        display: flex;
        align-items: center;
        height: 50px;
        line-height: 50px;
        .name {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
      }
    }
  }
  .main-wrapper {
    flex: 1;
    padding: 10px 10px 0;
    overflow-y: auto;
  }
}
.api-list-setting {
  .el-dialog__body {
    max-height: 800px;
    overflow:hidden;;
    overflow-y: auto;
  }
  .title {
    color: #409eff;
    font-weight: 600;
    margin: 10px;
  }
  .jv-container .jv-code {
    padding: 0 20px;
  }
}
.my-menu {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 5px;
  margin-right: -8px;
}
.mydiv {
  float: right;
  margin-top: 10px;
  margin-right: 10px;
}
</style>
