<template>
  <div class="execution">
    <basic-container>
      <div class="box">
        <div>
          <el-button-group>
            <el-button type="primary" icon="el-icon-search" :loading="tableLoading" @click="getList()">刷新</el-button>
            <el-button type="primary" icon="el-icon-circle-plus-outline"
                       @click="handleAdd()" :loading="tableLoading">
              添加
            </el-button>
          </el-button-group>
        </div>
      </div>

      <el-divider></el-divider>
      <el-table
        :data="tableData"
        :header-cell-style="{background:'#ECF1FE'}"
        border
        style="width: 100%">
        <el-table-column
          prop="channelName"
          label="通道名称"
          align="center"
          width="300">
        </el-table-column>
        <el-table-column
          align="center"
          prop="remoteIp"
          label="远端IP">
        </el-table-column>
        <el-table-column
          align="center"
          prop="remotePort"
          label="远端端口">
        </el-table-column>
        <el-table-column
          align="center"
          prop="anChannelType"
          :formatter="formatAnChannelType"
          label="通道类型">
        </el-table-column>
        <el-table-column
          align="center"
          prop="useStatus"
          :formatter="formatStatus"
          label="使用状态">
        </el-table-column>
        <el-table-column
          align="center"
          prop="username"
          label="用户名">
        </el-table-column>
        <el-table-column
          align="center"
          prop="password"
          label="密码">
        </el-table-column>

        <el-table-column
          align="center"
          label="操作"
          width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              :loading="tableLoading"
              @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              :loading="tableLoading"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
            <el-button
              size="mini"
              type="success"
              :loading="tableLoading"
              @click="handleInfo(scope.$index, scope.row)">路径信息
            </el-button>
            <!--            <el-button-->
            <!--              size="mini"-->
            <!--              type="info"-->
            <!--              :loading="tableLoading"-->
            <!--              @click="handleReconnect(scope.$index, scope.row)">重连-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="this.page.pageSize"
        layout="->,total, sizes, prev, pager, next, jumper"
        :total="this.page.total">
      </el-pagination>
    </basic-container>

    <!--编辑弹框-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
      :before-close="handleClose">
      <el-form ref="elform" :model="form" :rules="rules" label-width="100px">
        <el-form-item prop="channelName" label="通道名称">
          <el-input :disabled="dialogType=='edit'" v-model="form.channelName"></el-input>
        </el-form-item>
        <el-form-item prop="remoteIp" label="远端地址(ip)">
          <el-input v-model="form.remoteIp"></el-input>
        </el-form-item>
        <el-form-item prop="remotePort" label="远端端口">
          <el-input v-model="form.remotePort"></el-input>
        </el-form-item>
        <el-form-item prop="anChannelType" label="通道类型">
          <el-select v-model="form.anChannelType">
            <el-option
              v-for="item in anChannelTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="useStatus" label="是否使用">
          <el-select v-model="form.useStatus">
            <el-option
              v-for="item in useStatuss"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" @click="onAdd" v-if="this.dialogType==='add'">添加</el-button>
        <el-button type="primary" @click="onEdit" v-if="this.dialogType==='edit'">编辑</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>

    <!--路径信息弹框-->
    <el-dialog
      title="路径信息"
      :visible.sync="dialogInfoVisible"
      :close-on-click-modal="false"
      width="70%">
      <parsing-url :channelId=this.passvalueChannelId :channelInfo="channelInfo" :param="new Date()"></parsing-url>
    </el-dialog>


  </div>
</template>

<script>
import {fetchList, addObj, putObj, delObj} from '@/api/an/ParsingChannel'
import {mapGetters} from 'vuex'
import ParsingUrl from '@/views/an/parsingChannel/parsingUrl'

import mixin from '@/mixins/mixin.js'

export default {
  name: 'parsingChannel',
  components: {
    ParsingUrl
  },
  mixins: [mixin],
  data() {


    const validateTunnelId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入通道标识'))
      }
      tunnelById(this.form.stationCode, value).then(response => {
        if (window.boxType === 'edit') callback()
        let result = response.data.data
        if (result !== null) {
          callback(new Error('标识已存在'))
        } else {
          callback()
        }
      })


    }

    return {
      anChannelTypes:[{label:"ftp下载",value:"E1"},{label:"云端下载",value:"E2"},{label:"本地解析",value:"E3"}],
      useStatuss:[{label:"使用",value:"E1"},{label:"停用",value:"E2"}],
      dialogVisible: false,
      dialogInfoVisible: false,
      passvalueChannelId: '',
      channelInfo: '',//此行的通道信息
      dialogType: '',
      tunnelTypes: [],
      form: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,

      rules: {
        channelName: {required: true, message: '请输入通道名称', trigger: 'blur'},
        remoteIp: [{required: true, message: 'ip不能为空', 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'
          }],
        remotePort: [{required: true, message: '端口不能为空', trigger: 'blur'},
          {pattern: /^[0-9]*$/, message: '请填写正确的端口'}],
        // username: {required: true, message: '请输入用户名', trigger: 'blur'},
        // password: {required: true, message: '请输入密码', trigger: 'blur'},
        anChannelType: {required: true, message: '请选择通道类型', trigger: 'blur'},
        useStatus: {required: true, message: '请选择使用状态', trigger: 'blur'}
      },
      title:'',//弹框标题文本
    }
  },

  mounted() {
    this.getList()
    // this.getTypes()
  },
  computed: {
    ...mapGetters(['permissions']),
    ...mapGetters(['dataAuths']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.da_tunnel_add, false),
        delBtn: this.vaildData(this.permissions.da_tunnel_del, false),
        editBtn: this.vaildData(this.permissions.da_tunnel_edit, false)
      };
    }
  },
  methods: {
    permissionBtn(bt) {
      if (bt == 'add') {
        return this.permissionList.addBtn
      }
      if (bt == 'edit') {
        return this.permissionList.editBtn
      }
      if (bt == 'del') {
        return this.permissionList.delBtn
      }
    },
    getList() {
      var param;
      this.tableLoading = true
      fetchList(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, param)).then(response => {

        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch((e) => {
        console.log('获取ftp通道信息异常'+e)
        this.tableLoading = false
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.currentPage = 1
      this.getList();
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList();
    },
    handleAdd() {
      this.form = {}
      this.dialogType = "add"
      this.title = "新增&保存"
      this.dialogVisible = true
    },
    handleEdit(index, row) {
      this.form = row
      this.dialogType = "edit"
      this.title = '编辑&保存'
      this.dialogVisible = true

    },
    handleDelete(index, row) {

      var tunnelInfoText = ""
      var stateText = ""
      var confim = '该通道将删除 是否继续?'
      //1.查看通道对象下是否有通道信息
      // findByTunnelId(row.tunnelId).then(response => {

      // var tunnelInfos = response.data.data
      // if(tunnelInfos!=null && tunnelInfos.length>0){tunnelInfoText="该通道下存在通道信息"}
      //2.查看是否处于链接状态
      // tunnelState(row).then(response => {
      //   var state = response.data.data
      //   if(state!=null){stateText="该通道处于通信中"}
      //   if(tunnelInfoText!="" || stateText!=""){
      //
      //     confim = tunnelInfoText+' '+stateText+', 是否删除?（删除后将停止通信和删除相关联通道信息!!!）'
      //   }
      //
      //   this.$confirm(confim, '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      this.onDel(row)
      //   }).catch(() => {
      //     return false
      //   });
      //
      // }).catch(() => {
      // })

      // }).catch(() => {
      // })
    },

    handleInfo(index, row) {
      this.dialogInfoVisible = true
      this.channelInfo = row
      this.$nextTick(() => {
        this.passvalueChannelId = row.id
      })

    },
    handleClose(done) {
      this.form = {}

      this.$nextTick(() => {
        this.$refs.elform.resetFields();
      })
      done()
    },
    handleCancel() {
      this.$nextTick(() => {
        this.$refs.elform.resetFields();
      })
      this.form = {}
      this.dialogVisible = false
    },
    handleReconnect(row, index) {
      // console.log(row)
    },
    onAdd() {
      this.$refs.elform.validate((valid) => {
        if (valid) {
          this.tableLoading = true
          addObj(this.form).then(response => {
            this.dialogVisible = false
            this.getList()
            this.tableLoading = false
            this.$message.success('添加成功')
          }).catch(() => {
            this.tableLoading = false
            this.$message.error('添加失败')
          })
        } else {
          return false;
        }
      })

    },
    onEdit() {
      this.tableLoading = true
      putObj(this.form).then(response => {
        this.dialogVisible = false
        this.getList()
        this.tableLoading = false
        this.$message.success('修改成功')
      }).catch(() => {
        this.tableLoading = false
        this.$message.error('修改失败')
      })
    },
    onDel(row) {

      delObj(row.id).then(response => {
        this.dialogVisible = false
        this.getList()
        this.tableLoading = false
        this.$message.success('通道名为'+row.channelName+'删除成功')
      }).catch(() => {
        this.tableLoading = false
        this.$message.error('通道名为'+row.channelName+'删除失败')
      })
    },
    formatStatus(row) {
      const status = this.useStatuss.find(w => w.value === row.useStatus)
      return status !== undefined ? status.label : row.useStatus
    },
    formatAnChannelType(row) {
      const anChannelType = this.anChannelTypes.find(w => w.value === row.anChannelType)
      return anChannelType !== undefined ? anChannelType.label : row.anChannelType
    },

  }
}
</script>
<style scoped>
.box {
  display: flex;
  flex-direction: row;
  justify-content: flex-start
}

</style>
