<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-calendar"></i> API接口管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>API接口管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type='primary' size='small' @click='init_root_services'>创建根服务</el-button>
      </div>
      <div class='services-main'>
        <div class="services-tree">
          <el-input
              placeholder="输入关键字进行过滤"
              v-model="filterText">
          </el-input>
          <el-tree
              class='tree-padding'
              :data="api_management_tree"
              :props='default_props'
              :filter-node-method="filterNode"
              :load="loadNode"
              lazy
              node-key="id"
              :default-expand-all="false"
              draggable
              @node-click="select_service"
              @node-drop="drop_service"
              :expand-on-click-node="false"
              ref="tree"
              >
                  <span class="custom-tree-node shortname" slot-scope="{ node, data }">
                    <span v-if="node.label.length < 18">
                      <i :class="data.icon"></i>{{ node.label }} </span>
                     <el-tooltip v-else :content="node.label" class="item" effect="dark" placement="top-start">
                            <span ><i :class="data.icon"></i> {{ node.label | ellipsis(18) }} </span>
                    </el-tooltip>
                          <el-dropdown trigger="click" @command='handle_command'>
                              <span class="el-dropdown-link">
                                <i class="el-icon-arrow-down el-icon--right"></i>
                              </span>
                              <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item :command="{'ops': 'add', 'data': data}">创建</el-dropdown-item>
                                <el-dropdown-item :command="{'ops': 'edit', 'data': data}">编辑</el-dropdown-item>
                                <el-dropdown-item :command="{'ops': 'delete', 'data': data}">删除</el-dropdown-item>
                              </el-dropdown-menu>
                          </el-dropdown>
                  </span>
          </el-tree>
        </div>
        <div class='interface-tree'>
          <div class="interface-tree">
            <interface_list
                            :interfaces="service_interfaces"
                            :service_id="service_id"
                            :apiInterfaceId= "api_interface_id"
            ></interface_list>
          </div>
        </div>
        <el-dialog
            :title="edit_api_management.title"
            :visible.sync="edit_api_management.dialog_visible"
            width="35%">
          <el-form :model="edit_api_management" label-width="80px" :rules="edit_api_management_rule" ref="edit_service"
                   label-position="left">
            <el-form-item label="父节点" prop="parent" v-if="0 !== edit_api_management.parent">
              {{edit_api_management.parent_name}}
            </el-form-item>
            <el-form-item label="服务名称" prop="name">
              <el-input v-model="edit_api_management.name"></el-input>
            </el-form-item>
            <el-form-item label="服务描述" prop="description">
              <el-input type="textarea" :rows="3" v-model="edit_api_management.description"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
                    <el-button @click="edit_api_management.dialog_visible = false">取 消</el-button>
                    <el-button type="primary" @click="submit_form">确 定</el-button>
                </span>
        </el-dialog>
      </div>
    </el-card>

  </div>
</template>

<script>
import {
  getApiManagementRequest,
  putApiManagementRequest,
  postApiManagementRequest,
  deleteApiManagementRequest,
  getApiInterfaceRequest, postApiManagementTreeRequest
} from '../../../../api/apiAutomation/apiManagement';
import interface_list from '../interface/interface_list'
export default {
  name: "apiManagementPage",
  components: {
    interface_list
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {

    return{
      service_interfaces: [],
      api_management_tree: [],
      default_props: {
        children: 'children',
        label: 'name',
        isLeaf: 'isLeaf'
      },
      filterText: '',

      edit_api_management: {
        dialog_visible: false,

        mode: 'add',
        title: '创建服务',

        id: -1,
        name: '',
        description: '',

        parent: 0,
        parent_name: '',


      },
      edit_api_management_rule: {
        name: [
          {required: true, message: '请输入服务名称', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur'}
        ],
        description: [
          {required: true, message: '请输入服务描述', trigger: 'blur'},
        ],
      },
      service_id: 1,
      api_interface_id: 0,

    }


  },
  filters: {
    ellipsis(value, len) {
      if (!value) return ''
      if (value.length > len) {
        return value.slice(0, len) + '..'
      }
      return value
    }
  },
  methods: {
    get_api_management_fun(){
      getApiManagementRequest().then(data => {
        if (true === data.data.success){
          this.api_management_tree = data.data.data
        }else {
          this.$message.error(data.data.message)
        }
      })
    },
    loadNode(node, resolve) {
      if (node.level == 0) {
        console.log(node.level)
      }
      if (node.level >= 1 && node.level <2) {
        let req = {
          "parent":node.data.id,
          "isLeaf": 'false'
        }
        postApiManagementTreeRequest(req).then(data => {
          if (true === data.data.success){
            this.resolve = data.data.data
            return resolve(data.data.data);
          }else {
            this.$message.error(data.data.message)
          }
        })

      }

      if (node.level == 2) {
        let req = {
          "parent":node.data.id,
          "isLeaf": 'true'
        }
        postApiManagementTreeRequest(req).then(data => {
          if (true === data.data.success){
            data.data.data.forEach(item=>{
              if(true === item.isParent){
                item.isLeaf = true
              }
            })
            return resolve(data.data.data)
          }else {
            this.$message.error(data.data.message)
          }
        })
      }
    },


    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    update_service_req(req) {
      req = {
        name: this.edit_api_management.name,
        description: this.edit_api_management.description,
        parent: this.edit_api_management.parent
      }
      postApiManagementRequest(this.edit_api_management.id, req).then(data => {
        if (true === data.data.success) {
          this.get_api_management_fun();
          this.edit_api_management.dialog_visible = false;
        } else {
          this.$message.error('创建失败');
        }
      })
    },

    select_service(data) {
      this.service_id = data.id;
      getApiInterfaceRequest(this.service_id).then(data => {
        if (true === data.data.success) {
          this.api_interface_id = this.service_id
          this.service_interfaces = data.data.data
        } else {
          this.$message.error('获取用例失败');
        }
      })
    },
    interface_service(data) {
      getApiInterfaceRequest(data).then(data => {
        if (true === data.data.success) {
          this.service_interfaces = data.data.data
        } else {
          this.$message.error('获取用例失败');
        }
      })
    },

    submit_form(){
      this.$refs.edit_service.validate((valid) => {
        if (valid) {
          if ('add' === this.edit_api_management.mode) {
            this.add_service_req();
          } else {
            this.update_service_req();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    init_root_services(){
      this.edit_api_management.dialog_visible = true
      this.edit_api_management.mode = 'add';
      this.edit_api_management.name = '';
      this.edit_api_management.description = '';
      this.edit_api_management.title = '创建服务';
      this.edit_api_management.parent = 0;
      this.edit_api_management.parent_name = '';
      this.edit_api_management.id = -1;

    },
    init_children_service(parent_data){
      this.init_root_services();
      this.edit_api_management.parent = parent_data.id;
      this.edit_api_management.parent_name = parent_data.name

    },
    drop_service(node1, node2, position, event) {
      this.init_drop_service(node1.data, node2.data);
      this.update_service_req();
    },

    init_drop_service(data1, data2) {
      this.edit_api_management.parent = data2.id;
      this.edit_api_management.id = data1.id;
      this.edit_api_management.name = data1.name;
      this.edit_api_management.description = data1.description;
    },
    handle_command(command) {
      let ops = command.ops;
      let data = command.data;

      switch (ops) {
        case 'add':
          this.init_children_service(data);
          break;
        case 'edit':
          this.init_edit_service(data);
          break;
        case 'delete':
          this.init_delete_service(data)
          this.delete_service_req();
          break;
      }
    },

    init_delete_service(data) {
      this.edit_api_management.id = data.id;
    },

    init_edit_service(data) {
      this.edit_api_management.dialog_visible = true;
      this.edit_api_management.mode = 'edit';
      this.edit_api_management.name = data.name;
      this.edit_api_management.description = data.description;
      this.edit_api_management.title = "编辑服务";
      this.edit_api_management.parent = data.parent;
      this.edit_api_management.parent_name = data.parent_name;
      this.edit_api_management.id = data.id;
    },


    delete_service_req(){
      this.$confirm('此操作将永久删除服务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() =>{
        deleteApiManagementRequest(this.edit_api_management.id).then(data=> {
          if (true === data.data.success){
            this.get_api_management_fun();
          }else {
            this.$message.error('删除失败')
          }
        })
      })
    },


    add_service_req(req){
      req = {
        name: this.edit_api_management.name,
        description: this.edit_api_management.description,
        parent: this.edit_api_management.parent
      }
      putApiManagementRequest(req).then(data => {

        if (true === data.data.success){
          this.get_api_management_fun()
          this.edit_api_management.dialog_visible = false
          this.$message.success("创建成功")
        }else {
          this.$message.error("创建失败")
        }
      })
    },
  },

  mounted() {
    this.get_api_management_fun()
  }
}
</script>

<style scoped>
.services-main {
  display: flex;
}

.services-tree {
  width: 35%;
  border-right: solid 1px #e6e6e6;
  padding: 10px 5px 0 5px;
  min-height: 500px;
}

.tree-padding {
  padding-top: 10px;
  overflow:auto;
  max-height: 500px;
}

.interface-tree {
  width: 100%;
  padding: 10px 5px 0 10px;
}
/deep/ .el-tree>.el-tree-node {
  display: inline-block;
  min-width: 100%;
}

.shortname{
  width: 350px;
  overflow: hidden !important;
  white-space: nowrap !important;
  text-overflow:ellipsis !important;
  display: block !important;
}
/deep/.el-tree {
  min-width: 100%;
  display: inline-block;
}

/deep/.is-focusable{
  padding-bottom: 5px;
}
</style>