<template>
  <div>
    <el-select v-model="uploadId" :filterable="true" placeholder="请选择FTP/SFTP通道" prop="uploadId" @change="uploadChannelURL">
      <el-option
        v-for="item in this.channelData"
        :key="item.id"
        :label="item.channelName"
        :value="item.id"/>
    </el-select>
    <el-select v-model="servicePath" :filterable="true" placeholder="请选择该通道对应的路径" prop="servicePath" style="width: 30%">
      <el-option
        v-for="item in this.uploadURL"
        :key="item.value"
        :label="item.label"
        :value="item.value"/>
    </el-select>
    <el-button icon="vxe-icon--check" :loading="tableLoading" style="width: 80px" @click="getConnect">连接</el-button>
    <el-button icon="vxe-icon--close" :loading="tableLoading" style="width: 80px" @click="closeContinue">断开</el-button>
    <el-button icon="vxe-icon--refresh roll" :loading="tableLoading" style="width: 80px" @click="flush">刷新</el-button>
    <el-header style="padding: 0px; height: 41px">
      <div style="display: inline;">
        <el-button
          :loading="tableLoading"
          style="width: 5%"
          icon="el-icon-caret-left"
          @click="back"/>
        <el-upload
          :http-request="dataUpload"
          :before-upload="beforeUpload"
          class="el-upload-button"
          show-file-list="false"
          action="/FTP/upload"
          ref="upload"
        >
          <el-button icon="el-icon-upload2">
            上传文件
          </el-button>
        </el-upload>
        <el-select v-model="servicePath" style="width: 82%"/>
      </div>
    </el-header>

    <el-main style="padding-left: 0px;padding-top: 0px">
      <div>
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          height="550"
          border
          stripe
          size="mini"
          style="width: 100%;">
          <el-table-column
            :show-overflow-tooltip="true"
            header-align="center"
            width="500"
            label="文件名">
            <template slot-scope="scope" >
              <el-button
                v-if="scope.row.directory === true"
                icon="el-icon-arrow-right"
                class="el-icon-folder-opened"
                type="warning"
                style="padding: 3px 4px 3px 4px;margin: 2px"
                size="mini"
                @click="open(scope.row)">{{ scope.row.name }}
              </el-button>
              <span v-else-if="scope.row.directory === false"  class="el-icon-tickets">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="fileSize"
            header-align="center"
            min-width="100"
            label="文件大小"/>
          <el-table-column
            sortable
            prop="lastModified"
            header-align="center"
            min-width="200"
            label="修改日期"/>
          <el-table-column
            prop="jurisdiction"
            header-align="center"
            min-width="100"
            label="权限"/>
          <el-table-column
            fixed="right"
            header-align="center"
            min-width="100"
            label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.directory === false"
                type="success"
                style="padding: 3px 4px 3px 4px;margin: 2px"
                size="mini"
                icon="el-icon-download"
                @click="download(scope.row)">下载
              </el-button>
              <el-button
                v-if="scope.row.directory === false"
                type="danger"
                style="padding: 3px 4px 3px 4px;margin: 2px"
                size="mini"
                icon="el-icon-delete"
                @click="deleteEmp(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </div>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      tableLoading:false,
      fullscreenLoading:false,
      tableData:[],
      uploadId:'',
      uploadList:[],
      channelData:[],
      uploadURL:[],
      servicePath:'',
      continueParam:[],
      level:0,
      connectStatus:false,
      directoryName:[],
      directoryStatus:false,
      serviceOpenPath:'',
      //0=FTP,1=SFTP
      agreementType:0
    }
  },
  created() {
    this.getAllChannel()
  },
  methods: {
    //返回上一级
    back(){
      if(this.connectStatus !== true){
        this.$message.error('未建立连接')
        return
      }
      let path =''
      if(this.level === 0 ){
        this.$message.error('已经是最底层目录了')
        return
      }else{
        if(this.level === 1 ){
          path = this.serviceOpenPath
        }else {
          const str = this.servicePath.split("/"+this.directoryName[this.directoryName.length-1])
          for(let i = 0 ; i < str.length-1 ; i++){
            path = path + str[i]
          }
          this.directoryName.splice(this.directoryName.length-1,1)

        }
      }
      this.servicePath = path
      const param = {
        servicePath:this.servicePath
      }
      this.tableLoading = true
      if(this.agreementType ===0){
        this.$axios.post("/FTP/openServicePath/",param).then(res => {
          this.tableData = res.data
          this.connectStatus = true;
          this.level = this.level-1
          this.tableLoading = false
        })
      }else{
        this.$axios.post("/SFTP/openServicePath/",param).then(res => {
          this.tableData = res.data
          this.connectStatus = true;
          this.level = this.level-1
          this.tableLoading = false
        })
      }
    },
    //获取选择通道下的路径
    uploadChannelURL() {
      this.uploadURL = []
      this.servicePath = ''
      for(let i = 0 ; i < this.channelData.length ; i++){
        if(this.channelData[i].id === this.uploadId){
          //如果backupC === "1" 则是多路径
          this.$axios.get("/uploadURL/"+this.channelData[i].id).then(res => {
            if(this.channelData[i].backupC === "1"){
              for(let j = 0 ; j < res.data.length ; j++){
                this.uploadURL.push({label:res.data[j].uploadURL,value:res.data[j].uploadURL})
              }
            }else{
              this.uploadURL.push({label:this.channelData[i].pathService,value:this.channelData[i].pathService})
            }
          })
        }
      }
    },
    //获取所有FTP/SFTP通道
    getAllChannel() {
      this.$axios.get("/uploadObject/getFtpSftpChannel").then(res => {
        for(let i = 0 ; i < res.data.length ; i++){
          this.channelData.push(res.data[i])
        }
        console.log(this.channelData)
      })

    },
    //与对方建立连接
    getConnect(){
      this.directoryName=[]
      if(this.uploadId === null || this.uploadId===""){
        this.$message.error('请选择通道')
        return
      }
      if(this.servicePath === null || this.servicePath === ""){
        this.$message.error('请选择通道对应的路径')
        return
      }

      for(let i = 0 ; i < this.channelData.length ; i++){
        if(this.channelData[i].id === this.uploadId){
          const param = {
            remoteIp: this.channelData[i].remoteIp,
            remotePort:this.channelData[i].remotePort,
            uploadUserName: this.channelData[i].uploadUserName,
            uploadPassword: this.channelData[i].uploadPassword,
            servicePath:this.servicePath,
          }
          this.tableLoading = true

          //根据uploadObjectId来判断是FTP还是SFTP
          this.$axios.get("/uploadObject/").then(res => {
            for(let k = 0 ; k< res.data.length; k++){
              if(res.data[k].id ===  this.channelData[i].uploadObjectId){
                //如果是FTP
                if(res.data[k].uploadProtocolEnum === "E4"){
                  this.agreementType = 0
                  this.$axios.post("/FTP/continueFTP/",param).then(res => {
                    this.tableData = res.data
                    this.connectStatus = true;
                    this.serviceOpenPath = this.servicePath
                    this.tableLoading = false
                  })
                }else{
                  this.agreementType = 1
                  this.$axios.post("/SFTP/continueSFTP/",param).then(res => {
                    this.tableData = res.data
                    this.connectStatus = true;
                    this.serviceOpenPath = this.servicePath
                    this.tableLoading = false
                  })
                }
              }
            }
          })
        }
      }
    },
    //进入文件夹
    open(row) {
      if(this.servicePath === "/"){
        this.servicePath = this.servicePath+row.name
        this.directoryStatus = true
      }else{
        this.servicePath = this.servicePath+"/"+row.name
      }
      const param = {
        servicePath:this.servicePath
      }
      this.tableLoading = true
      if(this.agreementType === 0){
        this.$axios.post("/FTP/openServicePath/",param).then(res => {
          this.tableData = res.data
          this.connectStatus = true;
          this.directoryName.push(row.name)
          this.level = this.level+1
          this.tableLoading = false
        })
      }else{
        this.$axios.post("/SFTP/openServicePath/",param).then(res => {
          this.tableData = res.data
          this.connectStatus = true;
          this.directoryName.push(row.name)
          this.level = this.level+1
          this.tableLoading = false
        })
      }

    },
    //下载
    download(row){
      this.tableLoading = true
      const formData = new FormData()
      formData.append('path', this.servicePath)
      formData.append('name', row.name)
      if(this.agreementType === 0){
        this.$axios({ // 用axios发送post请求
          method: 'post',
          url: '/FTP/downloadFile', // 请求地址
          data: formData, // 参数
          responseType: 'blob', // 表明返回服务器返回的数据类型
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => { // 处理返回的文件流
          this.tableLoading = false
          if (res && res.code === 0) {
            this.$message.error('下载失败！')
          }
        })
      }else{
        this.$axios({ // 用axios发送post请求
          method: 'post',
          url: '/SFTP/downloadFile', // 请求地址
          data: formData, // 参数
          responseType: 'blob', // 表明返回服务器返回的数据类型
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => { // 处理返回的文件流
          this.tableLoading = false
          if (res && res.code === 0) {
            this.$message.error('下载失败！')
          }
        })
      }

    },
    //刷新
    flush(){
      if(this.connectStatus === false){
        this.$message.error('未建立连接')
        return
      }
      this.tableLoading = true
      setTimeout(() =>{
        this.tableLoading = false
      },500);
    },
    //上传文件
    beforeUpload(file) {

      const isLt2M = file.size / 1024 / 1024 < 1024 // 这里做文件大小限制
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过1020M!',
          type: 'warning'
        })
      }
      return isLt2M
    },
    dataUpload(item) {
      if(this.connectStatus === false){
        this.$message.error('未建立连接')
        return
      }
      this.tableLoading = true
      const formData = new FormData()
      formData.append('path', this.servicePath)
      formData.append('file', item.file)
      if(this.agreementType === 0){
        this.$axios.post('/FTP/upload', formData).then((resx) => {
          this.$refs.upload.clearFiles()
          this.tableLoading = false
          this.tableData = resx.data
        })
      }else {
        this.$axios.post('/SFTP/upload', formData).then((resx) => {
          this.$refs.upload.clearFiles()
          this.tableLoading = false
          this.tableData = resx.data
        })
      }

    },
    closeContinue(){
      if(this.connectStatus === false){
        this.$message.error('未建立连接')
        return
      }
      this.tableLoading = true
      if(this.agreementType === 0){
        this.$axios.get('/FTP/closeContinue').then(res => {
          this.tableData = []
          this.connectStatus = false
          this.tableLoading = false
        }).catch(function (error){
          console.log(error)
        })
      }else{
        this.$axios.get('/SFTP/closeContinue').then(res => {
          this.tableData = []
          this.connectStatus = false
          this.tableLoading = false
        }).catch(function (error){
          console.log(error)
        })
      }

    },
    deleteEmp(row) {
      this.doDelete(row.name,this.servicePath)
    },
    doDelete(name, path) {
      this.tableLoading = true
      const formData = new FormData()
      formData.append('path', path)
      formData.append('name', name)
      if(this.agreementType === 0){
        this.$axios.post('/FTP/deleteFile',formData).then((resp) => {
          this.tableLoading = false
          if (resp && resp.code === 0) {
            this.tableData = resp.data
          }
        })
      }else {
        this.$axios.post('/SFTP/deleteFile',formData).then((resp) => {
          this.tableLoading = false
          if (resp && resp.code === 0) {
            this.tableData = resp.data
          }
        })
      }

    },
  }
}
</script>

<style scoped>
.el-upload-button {
  display: inline-block;
}
</style>
