<!-- 文件传输窗口 -->
<template>
  <el-dialog
    :title="comonentVar.modelTitle"
    :visible.sync="comonentVar.dialogVisible"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    width="65%"
    top="20px"
    @close="modelOnClose"
  >
    <div class="model-form">
      <!-- label-width 设置了：label 和 input 就不会换行 -->
      <el-form ref="modelYaoKongOpt" label-width="30px">
        <el-tabs v-model="fileGetTabname" type="border-card">
          <el-tab-pane label="文件读取" name="tab2" style="text-align: center;">
            <el-row style="text-align: left;margin-bottom: 10px;">
              <el-col>
                <span>文件目录：<el-input
                  v-model="getFileDir"
                  class=""
                  clearable
                  placeholder="请输入文件目录"
                  type="text"
                  style="width:380px;margin-right: 2rem;"
                /></span>
                <el-button
                  type="primary"
                  class="dark-button"
                  size="big"
                  icon="el-icon-download"
                  @click="getDeviceFileList()"
                >获取目录文件</el-button>
                <el-button class="light-button" icon="el-icon-refresh" size="big" @click="refreshFileList()">刷新</el-button>
                <el-button style="float: right;" class="light-button" icon="el-icon-add" size="big" @click="addFileRecord()">添加文件信息</el-button>
              </el-col>
            </el-row>
            <el-row>
              <div class="buttons" style="text-align: left;">
                <el-button
                  class="dark-button"
                  icon="el-icon-delete"
                  size="small"
                  :disabled="!showDel"
                  @click="multDelete()"
                >批量删除</el-button>
              </div>
            </el-row>
            <el-row type="flex" style="float:left;width: 100%;margin-top: 10px;">
              <el-col>
                <div class="left-report">
                  <!-- 表格 -->
                  <el-table v-loading="isLoading2" :data="dbFileList" :height="tableHeight" @selection-change="handleSelectionChange">
                    <el-table-column
                      type="selection"
                    />
                    <!-- id隐藏不显示，作为操作数据依据 -->
                    <el-table-column v-if="false" property="id" label="id" />
                    <el-table-column property="name" label="文件名" width="260px" />
                    <el-table-column property="size" label="大小(B)" width="100px" />
                    <el-table-column property="updateRc" label="状态" width="150px" />
                    <el-table-column property="percent" label="进度" width="80px" />
                    <el-table-column property="updateTime" label="最后更新时间" width="160px" />
                    <el-table-column
                      label="操作"
                    >
                      <template slot-scope="scope">
                        <el-upload
                          v-if="scope.row.upload==true"
                          :action="uploadFileUrl"
                          :show-file-list="false"
                          :auto-upload="true"
                          accept="*"
                          :data="{filename:uploadFileName}"
                          :disabled="isUploadFileIng"
                          :headers="uplaodHeader"
                          :before-upload="(file) => updateActionUrl2(file,scope.row.id)"
                          :on-success="uploadSuccess"
                          style="float: left;margin-right: 20px;"
                        >
                          <el-button
                            type="text"
                            class="light-button"
                            icon="el-icon-upload2"
                            :disabled="isUploadFileIng"
                            size="small"
                          >上传文件</el-button>
                        </el-upload>
                        <a v-if="scope.row.download==true" style="float: left;margin-right: 20px;" target="new" :href="`/test/file/${scope.row.id}/bytes`"><el-button class="table-act" type="text" icon="el-icon-download" size="small">下载文件</el-button></a>
                        <el-button v-if="scope.row.writeable==true" style="float: left;margin-right: 20px;" class="table-act" type="text" icon="el-icon-download" size="small" @click="sendFile(scope.row)">写文件</el-button>
                        <el-button v-if="scope.row.readable==true" style="float: left;margin-right: 20px;" class="table-act" type="text" icon="el-icon-download" size="small" @click="readFile(scope.row)">读文件</el-button>
                        <el-button v-if="scope.row.deletable==true" style="float: left;" class="table-act" type="text" icon="el-icon-delete" size="small" @click="deleteFile(scope.row)">删除</el-button>
                        <!--<el-button v-if="scope.row.pos==null || scope.row.size==null || scope.row.pos==scope.row.size" class="table-act" type="text" icon="el-icon-delete" size="small" @click="deleteFile(scope.row)">删除</el-button>-->
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <el-tabs v-model="fileSendTabname" type="border-card" style="margin-top: 20px;">
          <el-tab-pane label="文件直接下发" name="tab3" style="text-align: center;">
            <el-row>
              <el-col>
                <el-upload
                  ref="upload"
                  :action="uploadFileUrl"
                  :show-file-list="false"
                  :auto-upload="false"
                  accept="*"
                  :disabled="isUploadFileIng"
                  :on-change="changeUpload"
                  :headers="uplaodHeader"
                  :before-upload="updateActionUrl"
                  :on-success="uploadSuccess"
                  style="float: left;margin-right: 20px;"
                >
                  <el-button
                    type="primary"
                    class="dark-button"
                    icon="el-icon-upload2"
                    :disabled="isUploadFileIng"
                    size="big"
                  >选择本地文件</el-button>
                </el-upload>
                <el-button
                  type="primary"
                  class="dark-button"
                  size="big"
                  :disabled="isUploadFileIng || !isSelectedFile"
                  icon="el-icon-upload2"
                  style="float: left;"
                  @click="submitUpload"
                >上传文件</el-button>
              </el-col>
            </el-row>

            <el-row v-show="isSelectedFile" style="margin-top: 20px;">
              <el-col>
                <span class="sendFileName">文件名称：{{ selectFileName }}</span><span class="sendFileProcess"><span ref="sendFileProcess2" class="sendFileProcess2" /></span><span class="sendFileProcessNumber">{{ sendFileProcessNumber }}</span>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div class="buttons" style="margin-top:20px;text-align: right;">
        <div class="cancel">
          <el-button class="lightButton" icon="el-icon-circle-close" size="big" @click="cancelForm">取消</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import {
  putData,
  postData,
  httpGet,
  delRecord
} from '@/api/common-action'
import { getToken } from '@/utils/auth'
export default {
  name: 'ModelFormSample',
  // model-parames 模态框参数
  props: {
    modelParames: {
      type: Object,
      default: function() {
        return {}
      }
    },
    sampleData: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      comonentVar: {
        modelTitle: '加载中...',
        dialogVisible: true
      },
      isLoading: false,
      isLoading2: false,
      getFileDir: '/', // 拉取文件的目录名称
      uploadFileUrl: '', // 文件上传地址
      fid: '',
      uploadFileName: '', // 上传的文件名称
      uploadSize: 0, // 上传文件的大小
      isUploadFileIng: false, // 文件是否在上传中
      isSendFileId: 0, // 文件是不是正在下发中
      isReadFileId: 0, // 文件是不是正在读取中
      isSelectedFile: false,
      fileGetTabname: 'tab2',
      fileSendTabname: 'tab3',
      selectFileName: '请先选择本地文件',
      sendFileProcessNumber: '0 %',
      deviceFileList: [],
      dbFileList: [],
      uplaodHeader: { 'Authorization': 'Bearer ' + getToken() },
      tableHeight: window.innerHeight * 0.5,
      fileUrl: '',
      multipleSelection: '',
      // 批量删除显示控制
      showDel: false
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  created() {
  },
  mounted() {
    // 初始化
    this.$nextTick(() => {
      this.initFunctions()
    })
  },
  methods: {
    // 初始化
    async initFunctions() {
      this.comonentVar.modelTitle = '文件传输'
      // this.fileUrl = window.STATIC_CONFIG.proxyUrl
      this.getList()
    },
    // 多选按钮状态改变 handleSelectionChange
    handleSelectionChange(val) {
      // 选中行存入临时变量中
      this.multipleSelection = val
      console.log('handleSelectionChange val', val)
      // 批量删除按钮激活
      if (val.length > 0) this.showDel = true
      else this.showDel = false
    },
    // 关闭model时执行
    modelOnClose() {
      this.$emit('toggleModel', 'ModelFormFileTransferOpt104', false)
    },
    // 拉取设备文件列表
    getDeviceFileList() {
      if (this.isLoading) {
        return
      }
      this.isLoading = true
      const url = `/equip/file/${this.modelParames.curPlanId}/list`
      postData(url, 'name=' + this.getFileDir).then(res => {
        this.isLoading = false
        // 请求结果
        if (res == null || res.data == null || res.data === '') {
          return
        }
        this.getList()
      }).catch(rees => {
        this.isLoading = false
      })
    },
    getList() {
      if (this.isLoading2) {
        return
      }
      this.isLoading2 = true
      httpGet('/test/file/search?runnerId=' + this.modelParames.curPlanId).then(res => {
        this.isLoading2 = false
        const resLst = res.content
        if (resLst != null && resLst.length > 0) {
          for (let i = 0; i < resLst.length; i++) {
            resLst[i]['size'] = resLst[i]['size'] || 0
            if (resLst[i]['size'] === 0) {
              resLst[i]['pro'] = 0
              continue
            }
            resLst[i]['pro'] = Math.round((resLst[i]['pos'] || 0) * 1 / (resLst[i]['size'] || 0) * 1)
          }
        }
        this.dbFileList = resLst
      }).catch(res => {
        this.isLoading2 = false
        this.$message({
          message: res.message,
          type: 'error',
          offset: window.screen.height / 3
        })
      })
    },
    refreshFileList() {
      this.getList()
    },
    changeUpload(e) {
      this.isUploadFileIng = false
      this.isSelectedFile = true
      this.selectFileName = e.name
      this.uploadSize = e.size
      this.sendFileProcessNumber = '0 %'
      this.$refs.sendFileProcess2.style.width = 0 * (300 / 100) + 'px'
    },
    addFileRecord() {
      this.$prompt('文件名称', '文件信息', {
        inputAttrs: {
          maxlength: 50,
          placeholder: '请输入50个字符以内的文件名'
        }
      }).then((obj) => {
        // 确认
        const v = obj.value == null ? '' : obj.value.replace(/ /gi, '')
        if (v === '') {
          this.$message('文件名称不能为空')
          return
        }
        if (v.length > 50) {
          this.$message('文件名称不能超过50字符')
          return
        }
        // 先创建文件记录
        putData('/test/file', { 'runnerId': this.modelParames.curPlanId, 'name': v, 'size': 0 }).then(res => {
          this.$message('文件信息创添加成功')
          this.getList()
        }).catch(res => {
          this.$message({
            message: '文件信息添加失败：' + res.message,
            type: 'error',
            offset: window.screen.height / 3
          })
        })
      }).catch({
        // 取消
      })
    },
    submitUpload() {
      // 上传文件
      this.isUploadFileIng = true
      // 先创建文件记录
      putData('/test/file', { 'runnerId': this.modelParames.curPlanId, 'name': this.selectFileName, 'size': this.uploadSize }).then(res => {
        this.fid = res.id
        // /test/file/{id}/bytes
        // this.uploadFileUrl = window.STATIC_CONFIG.proxyUrl + '/test/file/' + fid + '/bytes' // 文件上传地址
        this.$refs.upload.submit()
        this.isUploadFileIng = false
        this.isSelectedFile = false
      }).catch(res => {
        this.isUploadFileIng = false
        this.isSelectedFile = false
      })
    },
    updateActionUrl() {
      return new Promise((r) => {
        this.$nextTick(() => {
          this.uploadFileUrl = '/test/file/' + this.fid + '/bytes' // 文件上传地址
          r()
        })
      })
    },
    updateActionUrl2(obj, id) {
      return new Promise((r) => {
        this.$nextTick(() => {
          this.uploadFileName = obj.name
          this.uploadFileUrl = '/test/file/' + id + '/bytes' // 文件上传地址
          r()
        })
      })
    },
    uploadSuccess() {
      this.$message({
        message: '文件上传成功',
        type: 'success',
        offset: window.screen.height / 3
      })
      this.getList()
    },
    async multDelete() {
      // 批量删除
      for (let i = 0; i < this.multipleSelection.length; i++) {
        const row = this.multipleSelection[i]
        let isOk = true
        await delRecord('/test/file/', row.id).then(res => {
        }).catch(res => {
          this.$message({
            message: res.message,
            type: 'error',
            offset: window.screen.height / 3
          })
          isOk = false
        })
        if (!isOk) {
          break
        }
      }
      this.getList()
    },
    deleteFile(row) {
      delRecord('/test/file/', row.id).then(res => {
        this.$message({
          message: '文件删除成功',
          type: 'success',
          offset: window.screen.height / 3
        })
        this.getList()
      }).catch(res => {
        this.$message({
          message: res.message,
          type: 'error',
          offset: window.screen.height / 3
        })
      })
    },
    downloadFile(row) {
      const url = `/test/file/${row.id}/bytes`
      httpGet(url).then(res => {
        console.log(res)
      }).catch(res => {
      })
    },
    readFile(row) {
      // 从设备上读取文件
      this.isReadFileId = row.id
      const url = `/equip/file/${this.modelParames.curPlanId}/get`
      postData(url, 'fileId=' + row.id).then(res => {
        this.$message({
          message: '文件' + row.name + '正在读取中，请等待读取完成',
          type: 'info',
          offset: window.screen.height / 3
        })
        const that = this
        setTimeout(() => {
          that.getList()
        }, 3000)
      }).catch(res => {
        this.isReadFileId = 0
        this.$message({
          message: res.message,
          type: 'error',
          offset: window.screen.height / 3
        })
      })
    },
    sendFile(row) {
      // 下发文件到设备
      this.isSendFileId = row.id
      const url = `/equip/file/${this.modelParames.curPlanId}/put`
      postData(url, 'fileId=' + row.id).then(res => {
        this.$message({
          message: '文件' + row.name + '正在下发中，请等待下发完成',
          type: 'info',
          offset: window.screen.height / 3
        })
        const that = this
        setTimeout(() => {
          that.getList()
        }, 3000)
      }).catch(res => {
        this.isSendFileId = 0
        this.$message({
          message: res.message,
          type: 'error',
          offset: window.screen.height / 3
        })
      })
    },
    // 表单取消按钮
    cancelForm() {
      if (this.isUploadFileIng) {
        this.$message({
          message: '文件正在下发中',
          type: 'info',
          offset: window.screen.height / 3
        })
        return
      }
      this.comonentVar.dialogVisible = false
    }
  }
}
</script>
<style lang="scss">
.sendFileName{
  float: left;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 310px;
  white-space: nowrap;
  cursor: default;
}
.sendFileProcess {
  float: left;
  width: 300px;
  margin-top: 3px;
  background-color: #ccc;
  position: relative;
  border-radius: 5px;
  height: 10px;
  line-height: 10px;
  margin-left: 20px;
  .sendFileProcess2 {
    position: absolute;
    left: 0;
    top: 0;
    padding: 0;
    width: 0px;
    border-radius: 5px;
    height: 10px;
    line-height: 10px;
    background-color: blue;
  }
}
.sendFileProcessNumber{
  float: left;
  margin-left: 30px;
  font-weight: bold;
}
</style>
