<template>
  <div>
    <!--选择源目录弹框-->
    <el-dialog :title="title" :visible.sync="isShow" @open="beforeDialogOpen" append-to-body class="filePath-select-dialog">
      <!-- 工具栏 -->
      <el-toolbar style="position:relative;">
        <el-button @click="refreshData">
          <i class="fa fa-refresh"></i>刷新</el-button>
        <el-button @click="goParent">
          <i class="fa fa-reply"></i>上级目录</el-button>
        <span v-if="selectType === 'File'">
          <el-button @click="addFile('File')">
            <i class="fa fa-plus"></i>新建文件</el-button>
        </span>
        <span v-else>
          <el-button @click="addFile('Dir')">
            <i class="fa fa-plus"></i>新建目录</el-button>
        </span>&nbsp;
        <el-button @click="rename">
          <i class="fa fa-pencil"></i>重命名</el-button>
        <!-- <el-button @click="pageBrowse">
          <i class="fa fa-search-plus"></i>分页浏览</el-button> -->
      </el-toolbar>
      <el-row>
        <!-- 路径选择框 -->
        <el-col :span="16" class="source-dialog-row">
          <div id="address-div">
            <el-row>
              <el-col :span="2">
                <el-button id="address-button" type="text" @click="returnRootDir">
                  <img src="assets/images/framework/filetype/folder.gif"/> / </el-button>
              </el-col>
              <el-col :span="22">
                <ul id="urlLocationUL">
                  <li v-for="(URL,index) in urlLocationList" v-bind:key="URL.ID" v-bind:title="URL.ID">
                    &nbsp;
                    <i class="fa fa-caret-down"></i>
                    <a href="javascript:void(0)" @click="reLocate(index)">{{URL.ID}}</a>
                  </li>
                </ul>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <!-- 搜索框 -->
        <el-col :span="8" class="source-dialog-row">
          <el-input v-model="searchName" @keyup.enter.native="loadingFileData" placeholder="请输入名称">
            <el-button slot="append" @click="loadingFileData" icon="search" title="查询"></el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- 路径展示表格 -->
      <el-table :data="fileData" ref="singleTable" v-loading="fileDataLoading" highlight-current-row @row-dblclick="openFile" @row-click="selecteRow">
        <el-table-column type="index" width="60" align="center" label="序号" show-overflow-tooltip></el-table-column>
        <el-table-column min-width="38%" label="名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.row.name" class="table-radio">
                <img v-if="scope.row.dirFlag === 'Y'" src="assets/images/framework/filetype/folder.gif"/>
                <img v-else :src="getFileIconBySuffix(scope.row)"/>
              &nbsp;{{scope.row.name}}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="size" min-width="14%" label="大小" show-overflow-tooltipshow-overflow-tooltip></el-table-column>
        <el-table-column prop="type" min-width="18%" label="类型" ></el-table-column>
        <el-table-column prop="lastModified" min-width="24%" label="最后修改时间" show-overflow-tooltip></el-table-column>
      </el-table>
      <!-- 底部确认按钮 -->
      <div slot="footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmDirectoryData">确 定</el-button>
      </div>
    </el-dialog>
    <!--新建目录/重命名-->
    <el-dialog :title="createDirectoryTitle" :visible.sync="createDirectoryModal" append-to-body class="create-filePath-dialog">
      <!-- 新建/重命名表单 -->
      <el-form :model="tmpCreateDirectoryData" :rules="createDirectoryDataRules" ref="createfileDataForm" label-width="100px">
        <el-form-item label="上级目录：" prop="URL">
          <el-input class="e-input" v-model="tmpCreateDirectoryData.path" :disabled="true"></el-input>
        </el-form-item>
        <span v-if="tmpCreateDirectoryData.type === 'File'">
          <el-form-item label="文件名称：" prop="name">
            <el-input class="e-input" v-model="tmpCreateDirectoryData.name"></el-input>
          </el-form-item>
        </span>
        <span v-else>
          <el-form-item label="目录名：" prop="name">
            <el-input class="e-input" v-model="tmpCreateDirectoryData.name"></el-input>
          </el-form-item>
        </span>
      </el-form>
      <!-- 底部确认按钮 -->
      <div slot="footer">
        <el-button @click="createDirectoryModal = false">取 消</el-button>
        <el-button type="primary" @click="confirmName">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  data() {
    return {
      dirFlag: '',
      filePath: '',
      fileData: [],
      radio: '', // 单选框绑定
      oldName: '', // 用于判断是否有重命名改动
      isAdd: false, // 用于判断是新建还是重命名
      fileDataLoading: false, // 源目录数据加载动画
      createDirectoryModal: false, // 新建（重命名）目录对话框
      createDirectoryTitle: '', // 新建（重命名）目录对话框标题
      tmpCreateDirectoryData: {}, // 新建目录表单数据
      urlLocationList: [], // 导航栏路径选择列表
      createDirectoryDataRules: {
        name: [
          { required: true, message: '目录名不能为空', trigger: 'blur' },
          {
            pattern: /^[-\w._]+$/,
            message: '名称只能包含数字/字母/下划线/破折线和圆点',
            trigger: 'blur,change'
          }
        ]
      }, // 新建源目录表单数据匹配规则
      searchName: '', // 通过源目录名称查找源目录
      selectedFile: '', // 当前选中的源目录名
      selectedRows: [] // 当前选中的行
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  methods: {
    getFileIconBySuffix(row) {
      if (!row.name) {
        return 'assets/images/framework/filetype/unknown.gif'
      }
      return util.getFileIconByName(row.name)
    },
    // 加载数据
    async loadingFileData() {
      this.fileDataLoading = true
      try {
        let res = await axios.get('/ui/core/file/bindgrid', {
          params: {
            pageIndex: 0,
            pageSize: 99999,
            siteID: this.siteID,
            path: this.filePath,
            selectType: this.selectType,
            platformID: this.platformID,
            extension: this.extension,
            name: this.searchName
          }
        })
        // this.fileData = res.data.data
        let tableData = res.data.data
        tableData.forEach(item => {
          if (item.lastModified.length > 16) {
            item.lastModified = item.lastModified.substring(0, 16)
          }
        })
        this.fileData = tableData
        this.radio = ''
        this.selectedFile = ''
        this.dirFlag = ''
      } catch (e) {}
      this.fileDataLoading = false
    },
    // 弹框打开回调
    beforeDialogOpen() {
      this.urlLocationList = []
      this.searchName = ''
      this.filePath = this.path
      if (typeof this.filePath === 'undefined') {
        this.filePath = ''
      }
      if (this.filePath && this.filePath.length > 1) {
        if (this.selectType === 'File' && !this.parentPath) {
          this.filePath = this.filePath.substring(0, this.filePath.lastIndexOf('/') + 1)
        }
        let arr = this.filePath.split('/')
        if (arr[0] === '') {
          arr = arr.slice(1)
        }
        arr.pop()
        arr.forEach(o => {
          this.urlLocationList.push({
            ID: o
          })
        })
      } else {
        this.filePath = ''
      }
      this.loadingFileData()
    },
    refreshData() {
      this.loadingFileData()
    },
    // 返回上级目录
    goParent() {
      // 判断是否已经是顶级目录
      if (this.filePath === '') {
        return
      }
      this.urlLocationList.splice(-1, 1)
      this.filePath = ''
      // 判断是否已经是顶级目录
      if (this.urlLocationList.length > 0) {
        this.urlLocationList.forEach(o => {
          this.filePath = this.filePath + o.ID + '/'
        })
      }
      this.loadingFileData()
    },
    addFile(type) {
      this.isAdd = true
      this.createDirectoryTitle = '新建目录'
      this.tmpCreateDirectoryData = {
        path: this.filePath,
        name: '',
        type: type,
        siteID: this.siteID
      }
      this.createDirectoryModal = true
    },
    // 重命名确认
    async renameConfirm() {
      try {
        await util.validateForm(this.$refs['createfileDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      if (this.tmpCreateDirectoryData.oldName === this.tmpCreateDirectoryData.name) {
        this.$alert('名称未改变', '提示', {
          confirmButtonText: '确定',
          type: 'info'
        })
        return
      }
      let renameFile = await axios.patch(`/ui/core/file/${this.tmpCreateDirectoryData}/rename/${this.tmpCreateDirectoryData.name}`, this.tmpCreateDirectoryData)
      util.showResponseMessage(renameFile.data)
      if (renameFile.data.status === 1) {
        this.loadingFileData()
        this.createDirectoryModal = false
      }
    },
    // 添加确认
    async addFileConfirm(formName) {
      try {
        await util.validateForm(this.$refs['createfileDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      if (this.tmpCreateDirectoryData.type === 'File' && !this.checkSuffix(this.tmpCreateDirectoryData.name)) {
        this.$alert('不支持的文件后缀，请创建如下后缀的文件：' + this.extension, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
        return
      }
      let addFile = await axios.post('/ui/core/file', this.tmpCreateDirectoryData)
      util.showResponseMessage(addFile.data)
      if (addFile.data.status === 1) {
        this.loadingFileData()
        this.createDirectoryModal = false
      }
    },
    // 新建/重命名确认
    confirmName() {
      // 判断是新建还是重命名
      if (!this.isAdd) {
        this.renameConfirm()
      } else {
        this.addFileConfirm()
      }
    },
    async rename() {
      if (this.selectedFile === '') {
        this.$alert('请先选择一条记录！', '提示', {
          confirmButtonText: '确定',
          type: 'info'
        })
        return
      }
      try {
        await this.$confirm('重命名可能会影响到网站页面显示，确认要重命名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.isAdd = false
        this.createDirectoryTitle = '重命名'
        this.tmpCreateDirectoryData = {
          path: this.filePath,
          siteID: this.siteID,
          oldName: this.selectedFile,
          name: this.selectedFile
        }
        this.createDirectoryModal = true
      } catch (e) {

      }
    },
    //  双击表格行事件
    openFile(row) {
      if (!row) {
        return
      }
      let name = row.name
      if (row.dirFlag === 'Y') {
        this.selectedFile = ''
        this.filePath = this.filePath + name + '/'
        this.urlLocationList.push({
          ID: name
        })
        this.loadingFileData()
      } else {
        this.selectedFile = name
      }
    },
    // 单行点击事件
    selecteRow(row) {
      this.dirFlag = row.dirFlag
      this.radio = row.name
      this.selectedFile = row.name
      this.selectedRows = JSON.parse(JSON.stringify(row))
    },
    // 返回根目录
    returnRootDir() {
      this.filePath = ''
      this.urlLocationList = []
      this.loadingFileData()
    },
    // 点击路径名重定位
    reLocate(index) {
      this.urlLocationList = this.urlLocationList.slice(0, index + 1)
      this.filePath = ''
      this.urlLocationList.forEach(o => {
        this.filePath = this.filePath + o.ID + '/'
      })
      this.loadingFileData()
    },
    // 选择路径确认按钮点击事件
    confirmDirectoryData() {
      if (this.dirFlag === '' && this.selectType === 'File') {
        this.$alert('请从目录下选中一个文件！', '提示', {
          type: 'info'
        })
        return
      }
      if (this.dirFlag === 'Y' && this.selectType === 'File') {
        this.openFile(this.selectedRows)
        return
      }
      if (this.urlLocationList.length === 0 && this.selectedFile === '') {
        this.filePath = '/'
      }
      if (this.selectedFile !== '') {
        this.filePath = this.selectType === 'File' ? this.filePath + this.selectedFile : this.filePath + this.selectedFile + '/'
      }
      this.$emit('callback', this.filePath)
      this.$emit('update:show', false)
    },
    // 验证文件名后缀
    checkSuffix(name) {
      let extension = this.extension
      if (!name || !extension) {
        return true
      }
      extension = ',' + extension + ','
      var suffix = name.substring(name.lastIndexOf('.') + 1, name.length)
      if (extension.indexOf(',' + suffix + ',') >= 0) {
        return true
      } else {
        return false
      }
    }
  },
  props: ['title', 'show', 'selectType', 'path', 'extension', 'siteID', 'platformID', 'parentPath']
}
</script>

<style>
/* 在一般情况下dialog宽为680像素，在逻辑分辨率480像素以下dialog宽为96% */

.filePath-select-dialog .el-dialog {
  width: 700px;
}

@media (max-width: 480px) {
  .filePath-select-dialog .el-dialog {
    width: 96%;
  }
}
.create-filePath-dialog .el-dialog {
  width: 450px;
}

@media (max-width: 480px) {
  .create-filePath-dialog .el-dialog {
    width: 96%;
  }
}
</style>

<style scoped>
.source-dialog-row {
  height: 46px;
  background-color: #f3f3f3;
  padding: 5px;
}

#address-div {
  background-color: #fefefe;
  border: 1px solid #eee;
  height: 36px;
  width: 100%px;
}

#address-button {
  margin-left: 10px;
}

#urlLocationUL {
  padding-left: 4px;
  line-height: 33px;
}

#urlLocationUL li {
  float: left;
  list-style-type: none;
}

#urlLocationUL a:link {
  color: #333;
  text-decoration: none;
}

#urlLocationUL a:visited {
  color: #333;
  text-decoration: none;
}

#urlLocationUL a:hover {
  color: #333;
  text-decoration: none;
}

.dir-icon {
  color: #ffd700;
}

.table-radio {
  font-size: 13px;
  font-weight: normal;
}

.e-input {
  width: 240px;
}
</style>
