<template>
  <div class="apiInterfaceList">
    <div class="tree marginR20">
      <div class="newGroup">
        <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="showAddInput = true" v-if="!showAddInput">新建分组</el-button>
        <div class="marginL10" v-else>
          <el-input
            placeholder="请输入内容"
            size="mini"
            style="width: 80%"
            v-model="addInputValue"
          ></el-input>
          <span style="width: 15%">
            <i class="el-icon-check" style="cursor: pointer" @click="confirm"></i>
            <i class="el-icon-close" style="cursor: pointer" @click="cancel"></i>
          </span>
        </div>
      </div>
      <div class="search">
        <el-input
          size="mini"
          v-model="searchGroup"
          placeholder="搜索分组"
          @keyup.enter.native="getApiGroup"
          prefix-icon="el-icon-search">
        </el-input>
      </div>
      <div class="groupWrap">
        <div class="marginB10">
          <i class="fa fa-bars w20" aria-hidden="true"></i>
          <span class="marginL20 f20">所有API</span>
        </div>
        <editInput 
          :tableData="groupData"
          @updateEdit="updateEdit"
          @delGroup="delGroup"
        />
      </div>
    </div>
    <div class="content">
      <div class="obpm-title">
        <div class="d-inline-block">
          <i class="fa fa-plug" aria-hidden="true"></i>
          <div class="title-name d-inline-block ml-2">API中心</div>
        </div>
        <div class="bar d-inline-block float-right">
          <el-button type="primary" size="small" @click="addNew">{{
            $t('btns.new')
          }}</el-button>
          <el-button type="danger" plain size="small" @click="remove">{{
            $t('btns.delete')
          }}</el-button>
        </div>
      </div>
      <el-form ref="form" :inline="true" :model="params" class="demo-form-inline marginT10">
        <el-form-item>
          <el-input 
            v-model="params.name"
            @change="getAPISList"
            size="mini" 
            clearable
            placeholder="请输入API名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="params.requestType" clearable placeholder="请选择API协议" size="mini">
            <el-option label="GET" value="get"></el-option>
            <el-option label="POST" value="post"></el-option>
            <el-option label="PUT" value="put"></el-option>
            <el-option label="DELETE" value="delete"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-input v-model="params.tags"
            @change="getAPISList"
            size="mini" clearable
            placeholder="请输入API标签"
          ></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button @click="getAPISList" type="primary" size="mini" plain>查询</el-button>
          <el-button @click="reset" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :height="tableHeight"
        :data="tableData.datas"
        @row-click="onRowClick"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="API名称">
        </el-table-column>
        <el-table-column
          prop="requestUrl"
          label="URL">
        </el-table-column>
        <el-table-column
          prop="requestType"
          label="方法/协议">
          <template slot-scope="scope">
            <el-tag effect="plain" v-if="scope.row.requestType === 'get'">GET</el-tag>
            <el-tag effect="plain" v-if="scope.row.requestType === 'post'" type="success">POST</el-tag>
            <el-tag effect="plain" v-if="scope.row.requestType === 'put'" type="warning">PUT</el-tag>
            <el-tag effect="plain" v-if="scope.row.requestType === 'delete'" type="danger">DELETE</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 'published'" type="success">已发布</el-tag>
            <el-tag  type="warning" v-if="scope.row.status === 'development'">开发</el-tag>
            <el-tag  type="info" v-if="scope.row.status === 'test'">测试</el-tag>
            <el-tag  type="danger" v-if="scope.row.status === 'abnormal'">异常</el-tag>
            <el-tag  type="info" v-if="scope.row.status === 'maintain'">维护</el-tag>
            <el-tag  type="danger" v-if="scope.row.status === 'abandoned'">废弃</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="text-right pt-1"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.pageNo"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="10"
        background
        layout="total, prev, pager, next, sizes"
        :total="tableData.rowCount">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {delMsg} from '@/utils/elementui'
import editInput from '@/components/Common/edit_input'
import {
  getAPISList,
  deleteApiList,
  getAPISGroup,
  createApiGroup,
  updateApiGroup,
  deleteApiGroup
} from '@/service/AdvancedToolAPI.js'
export default {
  name:'apiInterfaceList',
  data () {
    return {
      tableHeight: 300,
      multipleSelection: [], //将获取选中的数组放进去
      tableData: {},
      params: {
        requestType: '',
        name: '',
        status: '',
        tags: '',
        pageNo: 1,
        linesPerPage: 10,
      },
      groupData: [],
      showAddInput: false,
      addInputValue: '',
      searchGroup: '', //搜索分组绑定的值
    };
  },
  mounted(){
    this.getScollerHeight();
    this.getAPISList();
    this.getApiGroup()
  },
  methods:{
    handleCommand(val){
      console.log('点击了什么', val)
    },
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 32分页
        this.tableHeight = (clientHeight - 60 - 32 - 41 - 40 - 50 - 71 - 20 - 40) + 'px';
      }, 100)
    },
    //填充方法
    onRowClick(row){
      this.$router.push({path: `/home/softwaresdetails/advancedTool/apiInterface?edit=true&apiId=${row.id}`})
    },
    //更新参数
    updataParams(obj){
      Object.assign(this.params,obj)
    },
    addNew(){
      this.$router.push({path: '/home/softwaresdetails/advancedTool/apiInterface?edit=false'});
    },
    /**
     *  获取Excel列表的数据
     */
    async getAPISList() {
      const response = await getAPISList(this.params, sessionStorage.getItem('appId'))
      if (response.data.errcode == 0) {
        this.tableData = response.data.data
      }
    },
    /**
     * 当前页
     */
    handleCurrentChange(val) {
      let params = {
        ...this.params,
        pageNo: val,
      }
      this.params = params
      this.getAPISList()
    },

    /**
     * 切换分页，每页显示多少条
     */
    handleSizeChange(val) {
      let params = {
        ...this.params,
        linesPerPage: val,
      }
      this.params = params
      this.getAPISList()
    },
    /**
     * selectInputName
     * 名称查询
     */
    selectInputName() {
      this.getAPISList()
    },
    /**
     * 获取选中的表格数据
     */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /**
     * 移除
     */
    async remove() {
      let selectData = this.multipleSelection
      let data = []
      for (let i = 0; i < selectData.length; i++) {
        data.push(selectData[i].id)
      }
      if (data.length > 0) {
        try{
          await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
          const response = await deleteApiList(data)
          if (response.data.errcode == 0) {
            this.$message.success(this.$t('msg.remove_ss'))
            this.getAPISList()
          }
        }catch(e){
          console.log(e)
        }
      } else {
        this.$message.error(this.$t('msg.check_data'))
      }
    },

    /**
     * 重置
     */
    reset(){
      this.params= {
        name: '',
        requestType: '',
        status: '',
        tags: '',
        pageNo: 1,
        linesPerPage: 10,
      }
    },

    /**
     * 更新编辑
     */
    async updateEdit(val, flag){
      if(flag){
        // 更新的接口
        const response = await updateApiGroup({name: val.name}, val.id, sessionStorage.getItem('appId'))
        if(response.data.errcode == 0){
          this.$message.success('更新分组成功')
          this.getApiGroup()
        }
      }else{
        val.name = val.bakName
      }
    },

    async delGroup(val){
      const response = await deleteApiGroup([val.id])
      if(response.data.errcode == 0){
        this.$message.success('删除成功')
        this.getApiGroup()
      }
    },

    async confirm(){
      this.showAddInput = false
      const response = await createApiGroup({name: this.addInputValue}, sessionStorage.getItem('appId'))
      if(response.data.errcode==0){
        this.$message.success('添加分组成功')
        this.getApiGroup()
      }
    },
    cancel(){
      this.showAddInput = false
      this.addInputValue = ''
    },
    async getApiGroup(){
      let params = {
        name: this.searchGroup,
        pageNo: 1,
        linesPerPage: 10000
      }
      const response = await getAPISGroup(params, sessionStorage.getItem('appId'))
      let data = response.data.data.datas.map(item =>  {
        item.bakName = item.name,
        item.isEdit = false
        return{
          ...item,
        }
      })
      // 将值塞进数组中
      this.groupData = data
    }
  },
  components:{
    editInput
  }
}

</script>
<style lang='scss' scoped>
.apiInterfaceList{
  display: flex;
  .tree{
    flex: 2;
    border: 1px solid #eeeeee;
    .newGroup{
      margin: 10px;
    }
    .search{
      background-color: #f7f7f7;
      height: 40px;
      border: 1px solid #eeeeee;
      padding: 5px;
    }
    .groupWrap{
      color: #717171;
      padding: 10px 20px;
      box-sizing: border-box;
    }
  }
  .el-dropdown-link {
    cursor: pointer;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .content{
    flex: 8;
  }
}
</style>