<template>
  <el-dialog :title="ruleId ? '编辑流控规则' : '新建流控规则'" :visible.sync="dialogVisible" width="400px" @close="close('form')">
    <div class="dialog-body">
      <el-form :model="form" :rules="rule" ref="form" label-width="100px" class="demo-ruleForm" label-position="right">
        <el-form-item label="流控范围" prop="rangeType">
          <template>
            <el-radio v-model="form.rangeType" :label="0">项目</el-radio>
            <el-radio v-model="form.rangeType" :label="1">分组</el-radio>
            <el-radio v-model="form.rangeType" :label="2">接口</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="流控内容" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" @change="getGroupList">
            <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="groupId" v-if="form.rangeType !== 0">
          <el-select v-model="form.groupId" placeholder="请选择分组" :disabled="form.projectId === ''" @change="getApiList">
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="interfaceId" v-if="form.rangeType === 2">
          <el-select v-model="form.interfaceId" placeholder="请选择接口" :disabled="form.groupId === ''">
            <el-option v-for="item in apiList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阈值类型" prop="grade">
          <template>
            <el-radio v-model="form.grade" :label="1">QPS</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="阈值" prop="count">
          <el-input v-model="form.count" placeholder="请输入阈值" class="w-220"></el-input>
        </el-form-item>
        <el-form-item label="流控方式" prop="rangeType">
          <template>
            <el-radio v-model="form.strategy" :label="0">快速失败</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="分布式限流" prop="count">
          <el-switch v-model="form.distFlag"> </el-switch>
        </el-form-item>
        <el-form-item label="是否开启" prop="count">
          <el-switch v-model="form.enableFlag"> </el-switch>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close('form')">取消</el-button>
      <el-button type="primary" @click="submitForm('form')">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getRequest } from '@/api/api';
export default {
  props: {
    ruleId: {
      type: String,
      default() {
        return '';
      }
    },
    sceneCode: {
      type: String,
      default() {
        return '';
      }
    }
  },
  data() {
    let countValidator = (rule, value, callback) => {
      let reg = /^(0|\+?[1-9][0-9]*)$/;
      if (!reg.test(value)) {
        callback(new Error('阈值必须输入正整数'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: true,
      projectList: [],
      groupList: [],
      apiList: [],
      form: {
        rangeType: 0,
        rangeInfo: '',
        projectId: '',
        projectName: '',
        groupId: '', //分组id
        groupName: '',
        interfaceId: '',
        interfaceName: '',
        ruleContent: '',
        grade: 1,
        count: '',
        strategy: 0,
        distFlag: false,
        enableFlag: false
      },
      rule: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
        interfaceId: [{ required: true, message: '请选择接口', trigger: 'change' }],
        count: [{ required: true, message: '请选择阈值', trigger: 'blur' }, { validator: countValidator, trigger: 'blur' }]
      }
    };
  },
  created() {
    this.dialogVisible = true;
    this.getProjectList();
    if (this.ruleId) {
      this.getInfo();
    }
  },
  methods: {
    getInfo() {
      var that = this;
      let params = {
        ruleId: this.ruleId
      };
      getRequest('/gateway-manage//rule/ratelimiter/detail', params)
        .then(res => {
          if (res.data.code == '0000') {
            this.form.rangeType = res.data.result.rangeType;
            if (this.form.rangeType === 0) {
              this.getGroupList();
            } else if (this.form.rangeType === 1) {
              this.getGroupList();
            } else if (this.form.rangeType === 2) {
              this.getApiList();
              this.getGroupList();
            }
            this.form.projectId = res.data.result.projectId;
            this.form.interfaceId = res.data.result.interfaceId;
            this.form.groupId = res.data.result.groupId;
            this.form.grade = res.data.result.grade;
            this.form.count = res.data.result.count;
            this.form.strategy = res.data.result.strategy;
            this.form.distFlag = res.data.result.distFlag === 1 ? true : false;
            this.form.enableFlag = res.data.result.enableFlag === 1 ? true : false;
          } else {
            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;
      this.form.groupId = '';
      this.form.interfaceId = '';
      let parmas = {
        type: 0,
        id: this.form.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
          });
        });
    },
    getApiList() {
      var that = this;
      this.form.interfaceId = '';
      let parmas = {
        type: 1,
        id: this.form.groupId
      };
      getRequest('/gateway-manage/plugin/interface/tree', parmas)
        .then(res => {
          if (res.data.code == '0000') {
            if (res.data.result) {
              this.apiList = res.data.result;
            } else {
              this.apiList = [];
            }
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    submitForm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.form.rangeType === 0) {
            //项目
            this.form.projectName = this.projectList.find(item => {
              return item.id === this.form.projectId;
            }).name;
            this.form.ruleContent = this.form.projectName;
            this.form.rangeInfo = this.form.projectId;
          } else if (this.form.rangeType === 1) {
            //分组
            this.form.projectName = this.projectList.find(item => {
              return item.id === this.form.projectId;
            }).name;
            this.form.groupName = this.groupList.find(item => {
              return item.id === this.form.groupId;
            }).name;
            this.form.ruleContent = this.form.projectName + '-' + this.form.groupName;
            this.form.rangeInfo = this.form.groupId;
          } else if (this.form.rangeType === 2) {
            //分组
            this.form.projectName = this.projectList.find(item => {
              return item.id === this.form.projectId;
            }).name;
            this.form.groupName = this.groupList.find(item => {
              return item.id === this.form.groupId;
            }).name;
            this.form.interfaceName = this.apiList.find(item => {
              return item.id === this.form.interfaceId;
            }).name;
            this.form.ruleContent = this.form.projectName + '-' + this.form.groupName + '-' + this.form.interfaceName;
            this.form.rangeInfo = this.form.interfaceId;
          }
          let params = {
            sceneCode: this.sceneCode,
            rangeType: this.form.rangeType,
            rangeInfo: this.form.rangeInfo,
            ruleContent: this.form.ruleContent,
            grade: this.form.grade,
            count: this.form.count,
            strategy: this.form.strategy,
            distFlag: this.form.distFlag ? 1 : 0,
            enableFlag: this.form.enableFlag ? 1 : 0
          };
          if (this.ruleId) {
            params.rateLimiterId = this.ruleId;
          }
          getRequest('/gateway-manage//rule/ratelimiter/save', params).then(res => {
            if (res.data.code == '0000') {
              this.dialogVisible = false;
              this.$emit('getList');
              this.$emit('cancelAdd');
            } else {
              this.$message.error(res.data.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    close(form) {
      this.$refs[form].resetFields();
      this.$emit('cancelAdd');
    }
  }
};
</script>
<style lang="less" scoped>
.w-220 {
  width: 220px;
}
</style>
