<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-07-30 15:17:39
 * @LastEditors: 无尘
 * @LastEditTime: 2019-10-09 10:48:11
 -->
<template>
  <div class="api-body-content border-box">
    <div class="common-nav">
      <nav-bread :navPath="navPath"></nav-bread>
    </div>
    <div class="api-body-main common-body-main border-box">
      <div class="api-main-content border-box">
        <div class="base-set-wrap">
          <div class="set-title font-14 color-303133">基础配置</div>
          <el-form :model="formData" label-width="94px" :rules="rules" ref="envForm">
            <el-form-item label="参数类型:">
              {{ formData.proxyType == 0 ? 'http' : 'dubbo' }}
            </el-form-item>
            <el-form-item label="配置名称:" prop="proxyName">
              <limitInput :inputWidth="440" :inputValue.sync="formData.proxyName" :holder="'请输入配置名称'" :getByType="'word'" :maxLength="20"> </limitInput>
            </el-form-item>
            <el-form-item label="配置code:" prop="proxyCode">
              <limitInput :inputWidth="440" :disflag="formData.setId ? true : false" :inputValue.sync="formData.proxyCode" :holder="'请输入配置code'" :getByType="'word'" :maxLength="20"> </limitInput>
            </el-form-item>
            <el-form-item label="备注:" prop="description">
              <limit-textarea :inputWidth="440" :inputValue.sync="formData.description" :holder="'请输入备注内容'" :getByType="'word'" :maxLength="100"> </limit-textarea>
            </el-form-item>
            <el-form-item label="" v-if="!shoEnvFlag">
              <div class="show-set-env" @click="showEnvSet"><span class="font-14 color-5584FF">添加环境配置</span><i class="iconfont iconxiala1 font-14 color-5584FF p-l-10"></i></div>
            </el-form-item>
          </el-form>
        </div>
        <div class="env-set-wrap" v-if="shoEnvFlag">
          <div class="set-title font-14 color-303133">环境配置</div>
          <div class="env-set-body">
            <el-table :data="tableData" style="width: 100%">
              <el-table-column prop="envName" label="配置名称" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-select v-model="scope.row.sceneCode" placeholder="请选择">
                    <el-option v-for="item in envOptions" :key="item.sceneCode" :label="item.sceneName" :value="item.sceneCode"> </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column v-if="$route.query.proxyType == 0" label="IP地址" width="550px">
                <template slot-scope="scope">
                  <div :class="['ip-cell ', index == 0 ? '' : 'm-t-18']" v-for="(item, index) in scope.row.proxyParams" :key="index">
                    <el-input class="w-200 font-14" v-model="item.url" placeholder="请输入ip地址"></el-input><el-input class="w-200 font-14 m-l-10" v-model="item.weight" placeholder="请输入权重值"></el-input>
                    <i v-if="scope.row.proxyParams.length > 1 && index < scope.row.proxyParams.length - 1" class="inline-block vertical-middle pointer el-icon-minus font-14 p-l-10" @click="toDel(scope.row, scope.$index, index)"></i>
                    <i v-if="scope.row.proxyParams.length - 1 == index" class="inline-block vertical-middle pointer el-icon-plus font-14 p-l-10" @click="toAdd(scope.row, scope.$index, index)"></i>
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-if="$route.query.proxyType == 1" label="注册中心" width="550px">
                <template slot-scope="scope">
                  <div :class="['ip-cell w-206', index == 0 ? '' : 'm-t-18']" v-for="(item, index) in scope.row.proxyParams" :key="index">
                    <el-input class="font-14" v-model="item.zookeeperUrl" placeholder=""></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-button v-if="tableData.length > 1" @click="handleDel(scope.$index, scope.row)" type="text">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="add-row text-center pointer" @click="toAddRow"><i class="el-icon-circle-plus-outline font-14 color-5584FF"></i><span class="font-14 color-5584FF p-l-4">添加行</span></div>
        </div>
        <div class="save-wrap" :style="{ 'padding-left': shoEnvFlag ? '0' : '97px' }">
          <el-button :disabled="$route.query.envSetFlag == 'show' ? true : false" type="primary" @click="handleSave('envForm')">保存</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import navBread from '@/components/nav/nav-bread.vue';
import limitInput from '@/components/limit-input.vue';
import limitTextarea from '@/components/limit-textarea.vue';
import { getRequest } from '@/api/api';
import showMsg from '@/assets/js/showmsg';
import errMsg from '@/assets/js/error';
export default {
  name: 'createEnvSet',
  components: {
    navBread,
    limitInput,
    limitTextarea
  },
  data() {
    return {
      // 面包屑参数
      navPath: [
        {
          name: '环境管理',
          path: '/envManage'
        },
        {
          name: '配置列表',
          path: '/envManage?tabChildid=second'
        },
        {
          name: this.$route.query.backendProxyId ? '修改配置' : this.$route.query.envSetFlag == 'show' ? '查看配置' : '新增配置',
          path: ''
        }
      ],
      formData: {
        backendProxyId: this.$route.query.backendProxyId || '',
        proxyType: this.$route.query.proxyType || '0',
        proxyCode: '',
        proxyName: '',
        description: '',
        envParams: ''
      },
      rules: {
        proxyName: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
        proxyCode: [{ required: true, message: '请输入配置code', trigger: 'blur' }]
      },
      shoEnvFlag: false, // 是否显示环境配置
      tableData: [
        {
          sceneCode: '',
          proxyParams: [
            {
              balence: 'random',
              url: '',
              weight: '',
              zookeeperUrl: ''
            }
          ]
        }
      ],
      envOptions: [
        /*  {
          sceneCode: '1',
          sceneName: '测试'
        },
        {
          sceneCode: '2',
          sceneName: '正式'
        } */
      ]
    };
  },
  methods: {
    /**
     * 显示环境配置
     */
    showEnvSet() {
      const that = this;
      that.shoEnvFlag = true;
    },
    /**
     * 删除 ip
     */
    toDel(row, index, child) {
      row.proxyParams.splice(child, 1);
    },
    /**
     * 添加 ip
     */
    toAdd(row, index, child) {
      row.proxyParams.push({
        balence: '',
        url: '',
        weight: '',
        zookeeperUrl: ''
      });
    },
    /**
     * 删除环境
     */
    handleDel(index, row) {
      const that = this;
      that
        .$confirm('确定删除该环境?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.tableData.splice(index, 1);
        })
        .catch(() => {});
    },

    /**
     * 添加行
     */
    toAddRow() {
      const that = this;
      that.tableData.push({
        sceneCode: '',
        proxyParams: [
          {
            balence: '',
            url: '',
            weight: '',
            zookeeperUrl: ''
          }
        ]
      });
    },
    /**
     * 保存
     */
    handleSave(formName) {
      const that = this;
      that.formData.proxyName = String(that.formData.proxyName).replace(/\s+/g, '');
      that.formData.proxyCode = String(that.formData.proxyCode).replace(/\s+/g, '');
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.saveData();
        } else {
          return false;
        }
      });
    },
    saveData() {
      const that = this;
      let spaceFlag = true;
      that.tableData.forEach(ele => {
        if (ele.sceneCode == '') {
          spaceFlag = false;
        }
        if (that.formData.proxyType == 0) {
          ele.proxyParams.forEach(child => {
            spaceFlag = child.url == '' || child.weight == '' ? false : true;
            that.$delete(child, 'zookeeperUrl');
          });
        } else {
          ele.proxyParams.forEach(child => {
            spaceFlag = child.zookeeperUrl == '' ? false : true;
            that.$delete(child, 'balence');
            that.$delete(child, 'url');
            that.$delete(child, 'weight');
          });
        }
      });
      if (!spaceFlag) {
        that.$message.error({
          duration: 1000,
          message: '请完善环境配置'
        });
        return false;
      }
      // console.log(that.tableData);
      let para = {
        backendProxyId: that.formData.backendProxyId,
        proxyType: that.formData.proxyType,
        proxyName: that.formData.proxyName,
        proxyCode: that.formData.proxyCode,
        description: that.formData.description,
        envParams: that.shoEnvFlag ? JSON.stringify(that.tableData) : ''
      };
      getRequest(that.$route.query.backendProxyId ? '/gateway-manage/update-proxy' : '/gateway-manage/create-proxy', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            showMsg.showmsg('保存成功', 'success');
            that.$router.push(`/envManage?tabChildid=second`);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 获取环境列表
     */
    getEnvData() {
      const that = this;
      getRequest('/gateway-manage/list-all-scene', {})
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            that.envOptions = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },

    /**
     *  获取数据
     */
    getData() {
      const that = this;
      let para = {
        backendProxyId: that.formData.backendProxyId
      };
      getRequest('/gateway-manage/get-proxy', para)
        .then(res => {
          let resData = res.data;
          if (resData.code == '0000') {
            that.formData = resData.result;
            let newEnvParams = JSON.parse(resData.result.envParams);
            // newEnvParams.forEach(ele => {
            //   ele.proxyParams = JSON.parse(ele.proxyParams);
            // });
            that.tableData = newEnvParams;
            if (that.tableData.length) {
              that.shoEnvFlag = true;
            }
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  watch: {
    $route: {
      handler: function(val, oldVal) {},
      // 深度观察监听
      deep: true
    }
  },

  /* 接收数据 */
  mounted() {
    const that = this;
    that.$emit('showTab', 3);
    that.getEnvData();
    if (that.$route.query.backendProxyId) {
      that.getData();
    }
  }
};
</script>

<style lang="less" scoped>
.w-206 {
  width: 206px;
}
.w-200 {
  width: 200px;
}
.vertical-middle {
  vertical-align: middle;
}
.ip-cell {
  font-size: 0;
}
.set-title {
  margin-bottom: 20px;
  font-weight: 600;
}
.show-set-env {
  cursor: pointer;
}
.add-row {
  padding: 14px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 51px;
}
</style>
