<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-09-05 10:03:31
 * @LastEditors: 无尘
 * @LastEditTime: 2019-10-21 10:48:40
 -->
<template>
  <div class="api-body-content border-box">
    <div class="common-nav">
      <nav-bread :navPath="navPath"></nav-bread>
      <div class="change-env" @click="goEnvList"><span>切换环境</span><i class="iconfont iconicon-qihuan" @click="goEnvList(item)"></i></div>
    </div>
    <div class="api-body-main common-body-main border-box">
      <div class="api-main-content border-box">
        <div class="env-tab-wrap">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <div v-if="activeName !== 'third'" class="search-box">
              <div class="left">
                <el-input v-model="search" :placeholder="activeName === 'first' ? '请输入接口名称/流控ID' : '请输入接口名称/熔断ID'" prefix-icon="el-icon-search" clearable class="w-320" @keyup.enter.native="getSearchList()" @clear="getSearchList()"> </el-input>
                <el-select v-model="projectId" placeholder="请选择项目" class="w-140 marginLeft10" size="small" style="display:inline-block" clearable @change="getChange">
                  <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                </el-select>
                <el-select v-model="groupId" placeholder="请选择分组" class="w-140 marginLeft10" size="small" style="display:inline-block" clearable :disabled="projectId === ''" @change="getSearchList">
                  <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                </el-select>
              </div>
              <div>
                <el-button type="primary" v-if="activeName === 'first'" @click="addFluid">新建流控规则</el-button>
                <el-button type="primary" v-if="activeName === 'second'" @click="addFusing">新建熔断规则</el-button>
                <el-button type="primary" @click="publish" :disabled="publishNum <= 0">{{ publishNum > 0 ? '待发布' + '（' + publishNum + '）' : '发布' }}</el-button>
              </div>
            </div>
            <el-tab-pane label="流控规则" name="first">
              <fluidList v-if="activeName === 'first'" :tableData="tableData" @getList="getList" :sceneCode="sceneCode" v-loading="loading"></fluidList>
            </el-tab-pane>
            <el-tab-pane label="熔断规则" name="second">
              <fusingList v-if="activeName === 'second'" :tableData="tableData" @getList="getList" :sceneCode="sceneCode" v-loading="loading"></fusingList>
            </el-tab-pane>
            <el-tab-pane label="告警配置" name="third">
              <warnSet v-if="activeName === 'third'" :tableData="tableData" @getList="getList" :sceneCode="sceneCode" @changeFlag="changeFlag" v-loading="loading"></warnSet>
            </el-tab-pane>
          </el-tabs>
          <div style="text-align:right;margin-top:20px;" v-if="total !== 0 && (activeName === 'first' || activeName === 'second')">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next" :total="total"> </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <selectEnv v-if="showdialog" :pluginId="pluginId" :pluginType="pluginType" @closeDialog="closeDialog"></selectEnv>
    <newRule v-if="showRuleDialog" :sceneCode="sceneCode" @cancelAdd="cancelAdd" @getList="getList"></newRule>
    <newSet v-if="showFlusDialog" :sceneCode="sceneCode" @cancelAddFlus="cancelAddFlus" @getList="getList"></newSet>
  </div>
</template>
<script>
import navBread from '@/components/nav/nav-bread.vue';
import { getRequest } from '@/api/api';
import selectEnv from '@/components/plug/environment-list';
import fluidList from '@/components/plug/fluid-rule';
import fusingList from '@/components/plug/fusing-rule';
import warnSet from '@/components/plug/warn-set';
import newRule from '@/components/plug/new-rule';
import newSet from '@/components/plug/rule-set';
export default {
  name: 'envManage',
  components: {
    navBread,
    selectEnv,
    fluidList,
    fusingList,
    warnSet,
    newRule,
    newSet
  },
  data() {
    return {
      // 面包屑参数
      navPath: [
        {
          name: '插件管理',
          path: '/pluginManage'
        },
        {
          name: 'AHAS',
          path: ''
        }
      ],
      activeName: 'first',
      search: '',
      showdialog: false,
      pluginId: '',
      sceneCode: '',
      pluginType: 0,
      projectList: [],
      projectId: '',
      groupList: [],
      groupId: '',
      total: 0,
      currentPage: 1,
      pageSize: 20,
      pageSizes: [20, 40, 60, 80],
      tableData: [],
      loading: false,
      showRuleDialog: false,
      showFlusDialog: false,
      publishNum: 0
    };
  },
  created() {
    this.pluginId = this.$route.query.pluginId;
    this.sceneCode = this.$route.query.sceneCode;
    this.getProjectList();
    this.getList();
    // this.getUpdateStatus();
  },
  methods: {
    /**
     * tab 切换
     */
    /* eslint-disable */
    handleClick(tab, event) {
      this.search = ''
      this.projectId= ''
      this.groupId= ''
      this.getList()
      // this.getUpdateStatus();
    },
    goEnvList() {
      this.showdialog = true;
      this.pluginId = this.pluginId;
    },
    closeDialog() {
      this.showdialog = false;
    },
    // 分页
    handleSizeChange(size) {
      //设置每页条数
      this.pageSize = size;
      this.getList();
    },
    handleCurrentChange(page) {
      //设置跳到第几页
      this.currentPage = page;
      this.getList();
    },
    getChange() {
      this.groupId = ''
      this.currentPage = 1
      this.getGroupList()
      this.getList()
    },
    getSearchList() {
      if(this.activeName === 'first'||this.activeName === 'second') {
        this.currentPage = 1
        this.getGroupList()
        this.getList()

      }
    },
    //获取列表
    getList() {
      let url = ''
      let params = {}
      if(this.activeName === 'first') {//流控规则
        url='/gateway-manage/rule/ratelimiter/list'
        params = {
          projectId:this.projectId?this.projectId:null,
          groupId:this.groupId?this.groupId:null,
          search:this.search?this.search:null,
          sceneCode:this.sceneCode,
          currentPage:this.currentPage,
          pageSize:this.pageSize
        }
      }else if(this.activeName === 'second') {
        url='/gateway-manage/rule/degrade/list'
        params = {
          projectId:this.projectId?this.projectId:null,
          groupId:this.groupId?this.groupId:null,
          search:this.search?this.search:null,
          sceneCode:this.sceneCode,
          currentPage:this.currentPage,
          pageSize:this.pageSize
        }
      }else if(this.activeName === 'third') {
        url='/gateway-manage/rule/alarm/list'
        params = {
          sceneCode:this.sceneCode
        }
      }
      this.tableData= []
      this.loading = true
      var that = this
      getRequest(url, params)
        .then(res => {
          if (res.data.code == '0000') {
            if(this.activeName === 'first') {
              if (res.data.result.result) {
                this.tableData = res.data.result.result;
                this.total=res.data.result.totalCount
              } else {
                this.total=0
                this.tableData = [];
              }
              for(let item of this.tableData) {
                item.enableFlag=item.enableFlag===1?true:false
              }
            }else if(this.activeName === 'second') {
              if (res.data.result.result) {
                this.tableData = res.data.result.result;
                this.total=res.data.result.totalCount
              } else {
                this.total=0
                this.tableData = [];
              }
              for(let item of this.tableData) {
                item.enableFlag=item.enableFlag===1?true:false
              }
            }else if(this.activeName === 'third'){
              if (res.data.result) {
                this.tableData = res.data.result;
              } else {
                this.tableData = [];
              }
              for(let item of this.tableData) {
                item.enableFlag = item.enableFlag === 1?true:false
                item.editStatus = false
              }
            }
            this.loading = false
            this.getUpdateStatus();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    changeFlag(item) {
      var that = this;
      // item.enableFlag = !item.enableFlag
      let params = {
        alarmType: item.alarmType,
        enableFlag: item.enableFlag ? 1 : 0,
        sceneCode: this.sceneCode
      };
      // return
      getRequest('/gateway-manage/rule/alarm/enable', params)
        .then(res => {
          if (res.data.code == '0000') {
            this.getList()
          } else {
            item.enableFlag = !item.enableFlag;
            this.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    //获取项目列表
    getProjectList() {
      var that = this;
      getRequest('/gateway-manage/plugin/interface/tree', {})
        .then(res => {
          if (res.data.code == '0000') {
            if (res.data.result) {
              this.projectList = res.data.result;
            } else {
              this.projectList = [];
            }
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    //获取分组列表
    getGroupList() {
      var that = this;
       let parmas = {
        type:0,
        id:this.projectId
      }
      getRequest('/gateway-manage/plugin/interface/tree',parmas)
        .then(res => {
          if (res.data.code == '0000') {
            if (res.data.result) {
              this.groupList = res.data.result;
            } else {
              this.groupList = [];
            }
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    // 新建流控规则
    addFluid() {
      this.showRuleDialog = true
    },
    cancelAdd() {
      this.showRuleDialog = false
    },
    // 新建熔断规则
    addFusing() {
      this.showFlusDialog  = true
    },
    cancelAddFlus() {
      this.showFlusDialog  = false
    },
    //发布
    publish() {

      let params = {
        sceneCode: this.sceneCode
      };
      let url = ''
      if(this.activeName ==='first') {
        url = '/gateway-manage/rule/ratelimiter/publish'
      }else if(this.activeName ==='second'){
        url = '/gateway-manage/rule/degrade/publish'
      }
      var that = this;
      this.$confirm('确定要发布吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        getRequest(url, params)
          .then(res => {
            if (res.data.code == '0000') {
              this.getList();
              // this.getUpdateStatus();
            } else {
              this.$message.error(res.data.message);
            }
          })
          .catch(function(error) {
            that.$message.error({
              duration: 1000,
              message: error.message
            });
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消发布'
        });
      });

    },
     // 获取更新状态
    getUpdateStatus(val) {
      let params = {
        sceneCode: val ? val : this.sceneCode
      };
      let url = ''
      if(this.activeName === 'first') {
        url = '/gateway-manage/rule/ratelimiter/has/edit'
      }else{
        url = '/gateway-manage/rule/degrade/has/edit'
      }
      getRequest(url, params).then(res => {
        if (res.data.code == '0000') {
          this.publishNum = res.data.result
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
  },
  watch: {
    $route: {
      handler: function(val, oldVal) {},
      // 深度观察监听
      deep: true
    },
    $route(to, from) {
      this.pluginId = this.$route.query.pluginId
      this.sceneCode = this.$route.query.sceneCode
      this.getList()
      // this.getUpdateStatus()
      // if(this.activeName === 'first') {
      //   this.$refs.fluItem.getUpdateStatus(this.sceneCode)
      // }else if(this.activeName === 'second'){
      //   this.$refs.fusItem.getUpdateStatus(this.sceneCode)
      // }
    }
  },



};
</script>

<style lang="less" scoped>
.w-320{
  width:320px;
}
.w-140{
  width:140px;
}
.marginLeft10{
  margin-left:10px;
}
.common-nav{
  // position: fixed;
  // z-index:10;
    .change-env{
      position:fixed;
      right:20px;
      font-size:12px;
      top:63px;
      width:85px;
      height:26px;
      color:#606266;
      line-height:26px;
      text-align: center;
      background:#EBECF0;
      border-radius:40px;
      cursor: pointer;
      i{
        font-size:12px;
      }
    }
    .change-env:hover{
      // box-shadow: 0px 2px 10px 0px rgba(213, 213, 213, 0.5);
      cursor: pointer;
    }
}
.search-box{
  display:flex;
  justify-content: space-between;
  margin-top:5px;
  .left{
    font-size:0
  }
}

.el-tabs {
  /deep/ .el-tabs__content {
    padding-bottom: 10px;
  }
}

</style>
