<template>
  <div>
    <el-row>
      <!-- <el-col :span="8"> -->
        <el-toolbar>
          <el-button @click="addCatalogResourceClickHandler" :priv="'com.zving.cms.Catalog.ResourceAdmin.'+catalogId">
            <i class="fa fa-plus-square"></i>新建
          </el-button>
          <!-- <el-button @click="delResourceClickHandler" :disabled="selectedRows.length===0">
            <i class="fa fa-minus-square-o"></i>删除
          </el-button> -->
          <!-- <el-dropdown @command="handleCommand">
            <el-button>
              <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="reuploadResourceClickHandler" :disabled="selectedRows.length!=1">
                <i class="fa fa-plus-square"></i>重新上传
              </el-dropdown-item>
              <el-dropdown-item command="copyResourceClickHandler" :disabled="selectedRows.length===0">
                <i class="fa fa-plus-square" ></i>复制
              </el-dropdown-item>
              <el-dropdown-item command="cutResourceClickHandler" :disabled="selectedRows.length!=1">
                <i class="fa fa-scissors" ></i>裁剪
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <el-col :span="10" class="dropdown-search-box-r">
            <el-input v-model="search.content" placeholder="请输入文件名称" class="search-bar-algin-toolbar" @keyup.enter.native="searchResourceClickHandler">
              <el-select placeholder="请选择资源类型" clearable slot="prepend" v-model="search.resourceType" @change="searchResourceClickHandler">
                <el-option v-for="item in resourceType" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-input>
            <span class="search-icon"><i class="fa fa-search" @click="searchResourceClickHandler" title="查询"></i></span>
          </el-col>
        </el-toolbar>
      <!-- </el-col> -->
    </el-row>
    <el-list-view
      class="catalog-resource-list"
      :data-read-url="getData"
      ref="multipleTable"
      :auto-get-data="false"
      @selection-change="onResourceSelectionChange"
      :page-size="10">
      <template slot-scope="row">
        <div class="panel-card">
          <el-row>
            <el-col :span="5">
              <img :title="row.name" :src="row.logoFile?prefix+row.logoFile:'assets/images/nopicture.png'" class="logo-file" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';"/>
            </el-col>
            <el-col :span="19">
              <el-row>
                <img :src="row.icon"/><a class="list-card-title" href="javascript:void(0)" > {{row.oldName}}</a>
              </el-row>
              <el-row>
                <el-col :span="12"><span>大小：</span> <em>{{row.fileSize || '0kb'}}</em> </el-col>
                <el-col :span="12"><span>所属栏目：</span> <em>{{row.catalogName || '无'}}</em> </el-col>
              </el-row>
              <el-row>
                <el-col :span="12"><span>资源类型：</span> <em>{{row.type || '无'}}</em> </el-col>
                <el-col :span="12"><span>最后修改时间：</span> <em>{{row.lastModified || '无'}}</em> </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="tar">
              <el-button @click.stop="reuploadResourceClickHandler(row)" type="text" title="重新上传" :priv="'com.zving.cms.Catalog.ResourceAdmin.'+catalogId">
                <i class="fa fa-plus-square"></i>重新上传</el-button>
              <el-button @click.stop="copyResourceClickHandler(row)" type="text" title="复制" :priv="'com.zving.cms.Catalog.ResourceAdmin.'+catalogId">
                <i class="fa fa-plus-square"></i>复制</el-button>
              <el-button @click.stop="cutResourceClickHandler(row)" type="text" title="裁剪" :priv="'com.zving.cms.Catalog.ResourceAdmin.'+catalogId">
                <i class="fa fa-scissors"></i>裁剪</el-button>
              <el-button @click.stop="delResourceClickHandler(row)" type="text" title="删除" :priv="'com.zving.cms.Catalog.ResourceAdmin.'+catalogId">
                <i class="fa fa-remove"></i>删除</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </el-list-view>
    <el-dialog title="资源上传" :visible.sync="uploadResourceMode" @close="uploadDialogClose" class="catalog-resources-upload-dlg">
      <el-form :model="tmpResource" ref="tmpResource" label-width="20%">
        <el-form-item label="文件：" props="file">
          <el-input disabled v-model="allowType" type="primary"
          style="width:200px;float: left;margin-right: 6px;"></el-input>
          <el-upload
            class="upload-Image"
            ref="resourceUpload"
            action=""
            :multiple="false"
            :auto-upload="false"
            :limit="1"
            :on-change="selectResourceChangeHandler"
            :before-upload="beforeUploadHandler"
            :http-request="fileUploadHandler"
            :on-remove="removeFileHandler"
            :accept="allowType">
            <el-button type="primary">选择文件</el-button>
             <div slot="tip" v-show="uploadShow" :title="'只能上传的文件格式：'+ allowType" class="el-upload__tip upload-allow-hint">{{'只能上传的文件格式：'+allowType}}</div>
          </el-upload>
        </el-form-item>
        <div v-if="(tmpResource.resourceType==='image'||tmpResource.resourceType==='video')&&isReuploadModal">
          <el-form-item label="宽度：" props="width">
            <el-input-number :style="{width:'75%'}" v-model="tmpResource.width" :min="0"></el-input-number>
          </el-form-item>
          <el-form-item label="高度：" props="height">
            <el-input-number :style="{width:'75%'}" v-model="tmpResource.height" :min="0"></el-input-number>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="uploadClose">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="doUploadResourceClickHandler">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 栏目资源复制  -->
    <copy-dialog
      :title="copyResource.title"
      :show.sync="copyResource.isShowModal"
      :select-ids="copyResource.selectIDs"
      @dialog="dialog"
      :show-check-box="copyResource.showCheckBox"
      @callback="copyResourcesBack">
    </copy-dialog>
    <!-- 图片处理 -->
    <image-cutting-dialog
      :siteID="imageCuttingDlg.siteID"
      :show.sync="imageCuttingDlg.isShowModal"
      :image-path.sync="imageCuttingDlg.filePath"
      @callback="imageCuttingCallback">
    </image-cutting-dialog>
  </div>
</template>
<script>
import util from '@src/common/util.js'
import CopyResourceDialog from './components/CopyResourceDialog.vue'
import ImageCuttingDialog from './commonImageCuttingDialog.vue'
export default {
  components: {
    'copy-dialog': CopyResourceDialog,
    'image-cutting-dialog': ImageCuttingDialog
  },
  props: { catalogId: [Number, String], type: String, tabName: String },
  data() {
    return {
      uploadShow: false,
      submitLoading: false,
      catalogResource: [], //   栏目资源数组
      selectedRows: [], //   选择行
      resourceType: [], //  栏目资源类型
      uploadResourceMode: false,
      tmpResource: {}, //  临时栏目资源上传对象
      fileList: [], //  上传文件对象
      isReuploadModal: false, //  栏目资源上传或重新上传
      allowType: '', //  上传文件类型
      copyResource: {
        title: '',
        isShowModal: false,
        showCheckBox: false,
        selectIDs: []
      },
      search: { allResourcesChecked: false, resourceType: '' },
      copyTree: [], //  复制内容的栏目树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      imageCuttingDlg: {
        isShowModal: false,
        filePath: '',
        siteID: 0
      },
      prefix: this.$root.prefix,
      tmpCatalogResource: {}
    }
  },
  watch: {
    catalogId: function(val) {
      if (this.tabName === 'resources') {
        this.loadCatalogResources()
      } else {
        this.catalogResource = []
      }
    },
    tabName: function(val) {
      if (val === 'resources') {
        this.initCondition()
        this.loadCatalogResources()
      } else {
        this.catalogResource = []
      }
    }
  },
  created() {
    this.loadResourceType()
  },
  methods: {
    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    uploadDialogClose() {
      this.$refs.resourceUpload.clearFiles()
      this.$refs['tmpResource'].resetFields()
      this.fileList = []
    },
    getFileIconBySuffix(row) {
      if (!row.name) {
        return 'assets/images/framework/filetype/unknown.gif'
      }
      return util.getFileIconByName(row.name)
    },
    imageCuttingCallback (prePath, path) {
      this.loadCatalogResources()
      // this.updateCatalogResources(path)
    },
    async updateCatalogResources(path) {
      try {
        let obj = {
          siteID: this.tmpCatalogResource.siteID,
          catalogID: this.tmpCatalogResource.catalogID,
          src: this.tmpCatalogResource.path,
          path: path
        }
        let res = await axios.put(`/ui/catalogresources/${this.tmpCatalogResource.ID}/cutresource`, obj)
        if (res.data.status === 1) {
          this.loadCatalogResources()
        }
        util.showResponseMessage(res.data)
      } catch (e) {
        util.showErrorNotification(e)
      }
    },
    // 裁剪
    cutResourceClickHandler(row) {
      this.tmpCatalogResource = row
      if (!row || !row.ID) {
        this.$alert('请先选择一条记录！', '提示', {
          type: 'warning'
        })
        return
      }
      if (!row.resourceType || row.resourceType !== 'image') {
        this.dialog('非图片文件不能裁剪文件')
        return
      }
      this.imageCuttingDlg.isShowModal = true
      this.imageCuttingDlg.filePath = row.logoFile
      this.imageCuttingDlg.siteID = row.siteID
    },
    // 提交复制栏目
    copyResourcesBack() {
      this.selectedRows = []
      this.$refs.multipleTable.clearSelection()
      this.loadCatalogResources()
    },
    //  复制栏目点击事件
    copyResourceClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        this.$alert('请先选择一条记录！', '提示', {
          type: 'warning'
        })
        return
      }
      this.copyResource.title = '选择需要复制到的栏目'
      this.copyResource.isShowModal = true
      this.copyResource.showCheckBox = true
      this.copyResource.selectIDs = ids
    },
    // 删除栏目资源
    async delResourceClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        this.$alert('请先选择一条记录！', '提示', {
          type: 'warning'
        })
        return
      }
      try {
        await this.$confirm('确认删除？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/catalogresources/${this.catalogId}`, {
          params: {
            resourcesID: ids.join(','),
            force: 'N'
          }
        })
        if (res.data.status === 2) {
          await this.$confirm(res.data.message, '系统提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          })
        } else {
          util.showMessage(res)
          if (res.data.status === 1) {
            this.selectedRows = []
            this.loadCatalogResources()
          }
        }
      } catch (e) {

      }
    },
    // 重新上传资源文件
    reuploadResourceClickHandler(row) {
      if (!row || !row.ID) {
        return
      }
      this.tmpResource = {
        ID: row.ID,
        oldName: row.oldName,
        resourceType: row.resourceType
      }
      this.allowType = '.' + row.suffix
      this.isReuploadModal = true
      this.uploadResourceMode = true
    },
    selectResourceChangeHandler(file, files) {
      this.fileList = JSON.parse(JSON.stringify(files.slice(-1)))
      this.beforeUploadHandler(file)
    },
    // 文件列表移除文件
    removeFileHandler(file, files) {
      this.fileList = JSON.parse(JSON.stringify(files))
      this.uploadShow = false
    },
    beforeUploadHandler(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      const extensions = this.allowType.split(',')
      for (var i = 0; i < extensions.length; i++) {
        let tmp = extensions[i]
        if (extension.toLowerCase() === tmp.toLowerCase()) {
          return true
        }
      }
      this.uploadShow = true
      return false
    },

    uploadClose() {
      this.$refs.resourceUpload.clearFiles()
      this.fileList = []
      this.uploadShow = false
      this.uploadResourceMode = false
    },
    // 文件上传确定事件
    async fileUploadHandler(event) {
      if (!this.fileList || this.fileList.length === 0) {
        this.dialog('请选择要上传的文件')
        return
      }
      const { file, onProgress } = event
      const formData = new FormData()
      formData.append('file', file)
      for (let i in this.tmpResource) {
        formData.append(i.toLowerCase(), this.tmpResource[i])
      }
      this.submitLoading = true
      if (this.isReuploadModal) {
        try {
          let res = await axios.post(
            `/ui/catalogresources/${this.tmpResource.ID}/uploadedit`,
            formData,
            event => {
              onProgress(event, file)
            },
            { headers: { 'Content-Type': 'multipart/form-data' } }
          )
          this.submitLoading = false
          if (res.data.status === 1) {
            this.uploadResourceMode = false
            this.loadCatalogResources()
          }
          util.showMessage(res)
        } catch (e) {
          this.submitLoading = false
          // util.showErrorNotification(e)
        }
      } else {
        try {
          let res = await axios.post(
            `/ui/catalogresources/${this.catalogId}/upload`,
            formData,
            event => {
              onProgress(event, file)
            },
            { headers: { 'Content-Type': 'multipart/form-data' } }
          )
          this.submitLoading = false
          if (res.data.status === 1) {
            this.$refs['tmpResource'].resetFields()
            if (this.catalogId === 0) {
              this.$refs.resourceUpload.clearFiles()
              this.fileList = []
              this.uploadResourceMode = false
              this.loadCatalogResources()
            } else {
              this.uploadResourceMode = false
              this.loadCatalogResources()
              if (res.data.saveRelaFlag) {
                this.saveRela(res.data.resourceID, res.data.delFlag, res.data.dataType)
              }
            }
          }
          util.showMessage(res)
        } catch (e) {
          this.submitLoading = false
          // util.showErrorNotification(e)
        }
      }
    },
    async saveRela(resourceID, delflag, dataType) {
      let obj = {
        dataType: dataType,
        dataID: this.catalogId,
        delflag: delflag
      }
      try {
        let res = await axios.put(`/ui/catalogresources/${resourceID}/saverela`, obj)
        if (res.data.status === 1) {
          this.$refs.resourceUpload.clearFiles()
          this.fileList = []
          // this.uploadResourceMode = false
          // this.loadCatalogResources()
        }
      } catch (e) {
        // util.showErrorNotification(e)

      }
    },
    //  提交新建资源
    doUploadResourceClickHandler() {
      if (!this.fileList || this.fileList.length === 0) {
        this.dialog('请选择要上传的文件')
        return
      }
      if (this.fileList) {
        let extension = this.fileList[0].name.substring(this.fileList[0].name.lastIndexOf('.'), this.fileList[0].name.length)
        let flag = false
        const extensions = this.allowType.split(',')
        for (let i = 0; i < extensions.length; i++) {
          let tmp = extensions[i]
          if (extension.toLowerCase() === tmp.toLowerCase()) {
            flag = true
            break
          }
        }
        if (!flag) {
          this.uploadShow = true
          this.dialog('请上传指定格式的文件')
          return
        }
      }
      this.$refs.resourceUpload.submit()
    },
    //  栏目资源查询
    searchResourceClickHandler() {
      this.loadCatalogResources()
    },
    //  新建资源点击事件
    addCatalogResourceClickHandler() {
      this.uploadResourceMode = true
      this.tmpResource = {}
      this.isReuploadModal = false
      this.loadResourceUploadInit()
    },
    // 资源上传初始化
    async loadResourceUploadInit() {
      let res = await axios.get('/ui/catalogresources/resourceuploadinit', {
        params: { catalogID: this.catalogId }
      })
      if (res.data.status === 1) {
        this.allowType = '.' + res.data.data.allowType.replace(/,/g, ',.')
      } else {
        this.allowType = '.*'
      }
    },
    // 资源列表选中事件
    onResourceSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 加载栏目资源
    async loadCatalogResources() {
      this.$refs.multipleTable.getData()
    },
    getData() {
      return ['/ui/catalogresources',
        {
          params: {
            catalogID: this.catalogId,
            resourceType: this.search.resourceType,
            oldName: this.search.content
          }
        }
      ]
    },
    // 初始化栏目资源条件搜索
    initCondition() {
      this.search.content = ''
      this.search.resourceType = ''
    },
    //  加载资源类型
    async loadResourceType() {
      let codeid = 'CatalogResourceType'
      let res = await axios.get(`/ui/platform/codes/${codeid}`)
      this.resourceType = res.data.data
    },
    // 消息Dialog封装
    dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    }
  }
}
</script>
<style scoped>
.upload-allow-hint {
  display: -webkit-box;
  display: -moz-box;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

.el-pagination__rightwrapper {
    float: right;
}
.catalog-resource-list .logo-file {
  max-width: 124px;
  max-height: 108px;
  vertical-align: middle;
}
</style>
<style>
.catalog-resources-upload-dlg .el-dialog {
  width: 400px;
}
@media (max-width: 480px) {
  .catalog-resources-upload-dlg .el-dialog {
    width: 96%;
  }
}
</style>
