<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-07-30 15:17:39
 * @LastEditors: 无尘
 * @LastEditTime: 2020-09-23 16:25:39
 -->
<template>
  <div class="api-body-content border-box">
    <div class="common-nav">
      <nav-bread :nav-path="navPath" />
    </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
            ref="envForm"
            :model="formData"
            label-width="94px"
            :rules="rules">
            <el-form-item label="参数类型:">
              {{ formData.proxyType == 0 ? 'http' : 'dubbo' }}
            </el-form-item>
            <el-form-item
              label="配置名称:"
              prop="proxyName">
              <limit-input
                :input-width="440"
                :disflag="$route.query.envSetFlag == 'show' ? true : false"
                :input-value.sync="formData.proxyName"
                :holder="'请输入配置名称'"
                :get-by-type="'word'"
                :max-length="20" />
            </el-form-item>
            <el-form-item
              label="配置code:"
              prop="proxyCode">
              <limit-input
                :input-width="440"
                :disflag="formData.backendProxyId ? true : false"
                :input-value.sync="formData.proxyCode"
                :holder="'请输入配置code'"
                :get-by-type="'word'"
                :max-length="20" />
            </el-form-item>
            <el-form-item
              label="备注:"
              prop="description">
              <limit-textarea
                :dis-input="$route.query.envSetFlag == 'show' ? true : false"
                :input-width="440"
                :input-value.sync="formData.description"
                :holder="'请输入备注内容'"
                :get-by-type="'word'"
                :max-length="100" />
            </el-form-item>
            <el-form-item
              v-if="!shoEnvFlag"
              label="">
              <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" />
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div
          v-if="shoEnvFlag"
          class="env-set-wrap">
          <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="请选择"
                    :disabled="$route.query.envSetFlag == 'show' ? true : false">
                    <el-option
                      v-for="item in envOptions"
                      :key="item.sceneCode"
                      :label="item.sceneName"
                      :value="item.sceneCode" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                v-if="$route.query.proxyType == 0"
                label="IP地址"
                width="550px">
                <template slot-scope="scope">
                  <div
                    v-for="(item, index) in scope.row.proxyParams"
                    :key="index"
                    :class="['ip-cell ', index == 0 ? '' : 'm-t-18']">
                    <el-input
                      v-model="item.url"
                      class="w-200 font-14"
                      placeholder="请输入ip地址"
                      :disabled="$route.query.envSetFlag == 'show' ? true : false" /><el-input
                        v-model="item.weight"
                        class="w-200 font-14 m-l-10"
                        placeholder="请输入权重值"
                        :disabled="$route.query.envSetFlag == 'show' ? true : false" />
                    <!-- && index < scope.row.proxyParams.length - 1 -->
                    <i
                      v-if="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
                      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)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                v-if="$route.query.proxyType == 1"
                label="注册中心"
                width="550px">
                <template slot-scope="scope">
                  <div
                    v-for="(item, index) in scope.row.proxyParams"
                    :key="index"
                    :class="['ip-cell w-206', index == 0 ? '' : 'm-t-18']">
                    <el-input
                      v-model="item.zookeeperUrl"
                      class="font-14"
                      placeholder="" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-button
                    v-if="tableData.length > 1"
                    :disabled="$route.query.envSetFlag == 'show' ? true : false"
                    type="text"
                    @click="handleDel(scope.$index, scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="add-row text-center pointer">
            <el-button
              :disabled="$route.query.envSetFlag == 'show' ? true : false"
              type="text"
              @click="toAddRow">
              <i class="el-icon-circle-plus-outline font-14 color-5584FF" /><span class="font-14 color-5584FF p-l-4">添加行</span>
            </el-button>
          </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, postRequest } 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: '正式'
        } */
      ]
    };
  },
  /* 接收数据 */
  mounted() {
    const that = this;
    that.$emit('showTab', 3);
    that.getEnvData();
    if (that.$route.query.backendProxyId) {
      that.getData();
    }
  },
  methods: {
    /**
     * @description: 显示环境配置
     * @author: 无尘
     */
    showEnvSet() {
      const that = this;
      that.shoEnvFlag = true;
    },
    /**
     * @description: 删除 ip
     * @param {Object} row
     * @param {Number} index
     * @param {Number} child
     * @returns {Boolean}
     * @author: 无尘
     */
    toDel(row, index, child) {
      if (this.$route.query.envSetFlag == 'show') {
        return false;
      }
      row.proxyParams.splice(child, 1);
    },
    /**
     * @description: 添加 ip
     * @param {Object} row
     * @param {Number} index
     * @param {Number} child
     * @returns {Boolean}
     * @author: 无尘
     */
    toAdd(row, index, child) {
      if (this.$route.query.envSetFlag == 'show') {
        return false;
      }
      row.proxyParams.push({
        balence: '',
        url: '',
        weight: '',
        zookeeperUrl: ''
      });
    },
    /**
     * @description: 删除环境
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    handleDel(index, row) {
      const that = this;
      that
        .$confirm('确定删除该环境?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.tableData.splice(index, 1);
        })
        .catch(() => {});
    },

    /**
     * @description: 添加行
     * @author: 无尘
     */
    toAddRow() {
      const that = this;
      that.tableData.push({
        sceneCode: '',
        proxyParams: [
          {
            balence: '',
            url: '',
            weight: '',
            zookeeperUrl: ''
          }
        ]
      });
    },
    /**
     * @description: 保存
     * @param {String} formName
     * @author: 无尘
     */
    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;
      let weightFlag = true;
      let ipFlag = true;

      that.tableData.forEach(ele => {
        if (ele.sceneCode == '') {
          spaceFlag = false;
        }
        if (that.formData.proxyType == 0) {
          ele.proxyParams.forEach(child => {
            const pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/g;
            if (pattern.test(child.url) === false) {
              ipFlag = false;
            }
            if (!(child.weight < 10000)) {
              weightFlag = false;
            }
            if (child.url == '' || child.weight == '') {
              spaceFlag = false;
            }
            that.$delete(child, 'zookeeperUrl');
          });
        } else {
          ele.proxyParams.forEach(child => {
            if (child.zookeeperUrl == '') {
              spaceFlag = false;
            }
            that.$delete(child, 'balence');
            that.$delete(child, 'url');
            that.$delete(child, 'weight');
          });
        }
      });
      if (!spaceFlag) {
        that.$message.error({
          duration: 1000,
          message: '请完善环境配置'
        });
        return false;
      }
      if (!weightFlag) {
        that.$message.error({
          duration: 1000,
          message: '请填写小于10000以内的权重值'
        });
        return false;
      }
      if (!ipFlag) {
        that.$message.error({
          duration: 1000,
          message: '请填写正确的 IP 地址'
        });
        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) : ''
      };
      postRequest(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
          });
        });
    },
    /**
     * @description: 获取环境列表
     * @author: 无尘
     */
    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
          });
        });
    },

    /**
     * @description: 获取数据
     * @author: 无尘
     */
    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
    }
  }
};
</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>
