<template>
  <div class="app-container">
    <el-card class="box-card">
      <div style="margin-bottom: 1%">
        <el-button size="small" @click="insertData" icon="el-icon-plus" >新增</el-button>
      </div>
      <el-table v-loading="loading" border
                :data="tableAllData.slice((page.currentPage-1)*page.pageSize,page.currentPage*page.pageSize)">
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column label="通道名称" align="center" prop="tunnelName"/>
        <el-table-column label="ip地址" align="center" prop="ip"/>
        <el-table-column label="端口号" align="center" prop="port"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <svg class="icon" aria-hidden="true" v-if="scope.row.status === '1'">
              <use xlink:href="#icon-zhengchang"></use>
            </svg>
            <svg class="icon" aria-hidden="true" v-else>
              <use xlink:href="#icon-lianjieduankai"></use>
            </svg>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"

            >修改
<!--              v-hasPermi="['dataQuery:windTowerStatusInfo:edit']"-->
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"

            >删除
<!--              v-hasPermi="['dataQuery:windTowerStatusInfo:remove']"-->
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page=page.currentPage
          :page-sizes="[10, 15, 30, 50]"
          :page-size=page.pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total=page.total>
        </el-pagination>
      </div>
<!--  弹框    -->
      <el-dialog :title="title" :visible.sync="open" width="40%" style="margin-top: 10%" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20" class="mb8">
            <el-col :span="12">
              <el-form-item label="通道名称:" prop="tunnelName">
                <el-input v-model="form.tunnelName" placeholder="请输入通道名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通道状态:" prop="status">
                <el-switch
                  style="display: flex;height: 36px"
                  v-model="form.status"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  active-text="正常"
                  inactive-text="停用">
                </el-switch>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row :gutter="20" class="mb8">
            <el-col :span="12">
            <el-form-item label="ip地址:" prop="ip">
              <el-input v-model="form.ip" placeholder="请输入ip地址"/>
            </el-form-item>
          </el-col>
            <el-col :span="12">
              <el-form-item label="端口:" prop="port">
                <el-input v-model="form.port" placeholder="请输入端口"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {list,addTunnelInfo,updateTunnelInfo,delTunnelInfo} from "@/api/biz/dataQuery/tunnelInfo";
import '../../../assets/icons/iconfont'
export default {
  name: "index",
  data(){
    const checktunnelName = (rule, value, callback) => {
      var s6 = this.tableAllData
      if (this.editFlag === 'edit') {
        s6 = editCheckDate(this.tableAllData, this.form)
      }
      if (this.form.tunnelName == null || this.form.tunnelName === '') {
        callback(new Error('不许为空'))
      }
      for (let i = 0; i < s6.length; i++) {
        if (this.modId === '') {
          // 新增
          if ((this.form.tunnelName.replace(/(^\s*)|(\s*$)/g, '') === s6[i].tunnelName)) {
            callback(new Error('通道名称不能重复'))
          }
        } else {
          // 修改
          if (this.modId !== s6[i].id) {
            if (this.form.tunnelName != null) {
              if ((this.form.tunnelName.replace(/(^\s*)|(\s*$)/g, '') === s6[i].tunnelName)) {
                callback(new Error('通道名称不能重复'))
              }
            }
          }
        }
      }
      callback()
    }
    // v1:展示数据集合 v2:当前编辑的数据对象
    function editCheckDate(v1, v2) {
      const v3 = []
      for (let i = 0; i < v1.length; i++) {
        if (v2.id === v1[i].id) {
          continue
        }
        v3.push(v1[i])
      }
      return v3
    }
    return{
      loading:false,
      tableAllData:[],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      title: '新增&保存',
      editFlag:'add',
      open:false,
      form:{},
      rules:{
        tunnelName: [{ required: true, trigger: 'blur', validator: checktunnelName }],
        ip: [{ required: true, trigger: 'blur' },
          {
            pattern: /^(?=(\b|\D))(((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{1,2})|(2[0-4]\d)|(25[0-5]))(?=(\b|\D))/,
            message: '请填写正确的ip'
          }],
        port: [{ required: true, trigger: 'blur' },
          { pattern: /^[0-9]*$/, message: '请填写正确的端口' }]
      },
      modId:'',//备用id

    }
  },
  mounted() {
    this.getTunnelInfo()
  },
  methods:{
    /*获取所有通道信息*/
    getTunnelInfo(){
      list().then(res=>{
        this.tableAllData = res.rows
        this.page.total = this.tableAllData.length
      }).catch(err=>{
        console.log('获取通道信息异常：'+ err)
      })
    },
    /*新增*/
    insertData(){
      this.editFlag = 'add'
      this.title = '新增&保存'
      this.resetForm()
      this.open = true
    },
    /*编辑*/
    handleUpdate(row){
      this.editFlag = 'edit'
      this.title = '修改&保存'
      this.modId = row.id
      console.log(row)
      this.form={
        id:row.id,
        tunnelName:row.tunnelName,
        ip:row.ip,
        port:row.port,
        status:row.status === '1'? true: false
      }
      this.open = true
    },
    /*删除*/
    handleDelete(row){
      const ids = row.id;
      this.$modal.confirm('是否确认删除通道名称为"' + row.tunnelName + '"信息及所有数据？').then(function () {
        return delTunnelInfo(ids);
      }).then(() => {
        this.getTunnelInfo();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /*保存*/
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.status = this.form.status === true? '1':'0'
          if (this.editFlag === 'edit') {
            updateTunnelInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getTunnelInfo();
            });
          } else {
            addTunnelInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getTunnelInfo();
            });
          }
        }
      });
    },
    /*取消*/
    cancel(){
      this.open = false
      this.resetForm()
    },
    /*重置*/
    resetForm(){
      this.form={
        id:null,
        tunnelName:null,
        ip:null,
        port:null,
        status: true
      }
    },

    /*pageSize改变*/
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.currentPage = 1

    },
    /*currentPage改变*/
    handleCurrentChange(val) {
      this.page.currentPage = val
    },
  }
}
</script>

<style scoped>
.icon {
  width: 2em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
