<template>
  <div class="resource-content">
    <!-- 资源选择弹框内容 -->
    <el-tabs class="tabs-wrap" v-model="tabActiveName" @tab-click="onResourceTabsClick">
      <!-- 视频编辑编辑面板 -->
      <el-tab-pane name="videoEdit" v-if="this.resourceDialogProps.isEdit">
        <span slot="label">视频编辑</span>
        <div style="padding: 20px 0 0">
          <el-form ref="videoEditForm" :model="videoEdit" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="视频地址">
                  <el-input v-model="videoEdit.url"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="宽度">
                  <el-input-number v-model="videoEdit.width" :min="0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="高度">
                  <el-input-number v-model="videoEdit.height" :min="0"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="呈现风格">
                  <el-radio-group v-model="videoEdit.display">
                    <el-radio label="simple">简单</el-radio>
                    <el-radio label="fold">折叠</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="预览">
                  <video-player :src="videoEdit.url" :poster="videoEdit.poster" :auto-play="false" width="420px" height="260px"></video-player>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-tab-pane>
      <!-- 资源上传面板选择栏 -->
      <el-tab-pane name="uploader">
        <span slot="label">资源上传</span>
        <el-form label-position="right" label-width="200px" :model="tmpResourceProps">
          <div v-if="tmpResourceProps.supportNetSource !== 'false'">
            <el-form-item label="来源：">
              <el-radio-group v-model="tmpResourceProps.sourceType">
                <el-radio label="upload">本地上传</el-radio>
                <el-radio label="internet">网络</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <!-- 根据不同来源加载不同表单样式 -->
          <div v-if="tmpResourceProps.sourceType === 'upload'">
            <el-form-item label="文件：">
              <el-upload ref="upload" action="" :multiple="tmpResourceProps.multiUpload === 'Y'" :file-list="tmpFileList" :auto-upload="false" :on-change="selectFileChangeHandler" :on-remove="selectFileRemoveHandler" :accept="tmpResourceProps.allowType" style="width:330px;">
                <el-row :gutter="3">
                  <el-col :span="18">
                    <el-input disabled v-model="tmpResourceProps._allowType"></el-input>
                  </el-col>
                  <el-col :span="6">
                    <el-button type="primary">选择文件</el-button>
                  </el-col>
                </el-row>
                <div slot="tip" class="el-upload__tip">只能上传 {{tmpResourceProps.allowType | formatSymbol}} 文件</div>
              </el-upload>
              <el-progress :percentage="progressInfo.percent" v-show="progressInfo.visible"></el-progress>
            </el-form-item>
            <!-- <el-form-item label="是否转换：" v-if="tmpResourceProps.resourceType === 'video'">
              <el-switch v-model="tmpResourceProps.convert" active-value="Y" inactive-value="N">
            </el-switch>
            </el-form-item> -->
          </div>
          <div v-else>
            <el-form-item label="URL地址：" prop="URL">
              <el-input auto-complete="on" style="width:300px;" v-model="tmpResourceProps.URL" @input="autoFillOldName(`${tmpResourceProps.URL}`)"></el-input>
            </el-form-item>
            <el-form-item label="名称：" prop="oldName" :rules="[{required:true,message:'不能为空',trigger:'blur'}]">
              <el-input style="width:300px;" v-model="tmpResourceProps.oldName"></el-input>
            </el-form-item>
          </div>
          <div v-if="tmpResourceProps.resourceType === 'image' || tmpResourceProps.resourceType === 'video'">
            <el-form-item label="宽度：">
              <el-input-number v-model="tmpResourceProps.width" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="高度：">
              <el-input-number v-model="tmpResourceProps.height" :min="0"></el-input-number>
            </el-form-item>
          </div>
        </el-form>
        <el-form label-position="right" label-width="200px" :model="tmpParams">
          <div v-if="tmpResourceProps.resourceType === 'image'">
            <el-form-item label="添加水印：">
              <el-radio-group v-model="tmpParams.addWaterImage">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="logo图缩放模式：">
              <el-select v-model="tmpParams.logoThumbMode">
                <el-option v-for="item in logoThumbModeOptions" :key="item.key" :value="item.key" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="裁剪保留区域：" v-if="tmpParams.logoThumbMode === 'fill'">
              <water-position-picker :position.sync="tmpParams.logoCutSavePart"></water-position-picker>
            </el-form-item>
          </div>
          <!-- <el-form-item prop="tag" label="标签"> -->
            <resource-tags :tags.sync="tmpResourceProps.tag"></resource-tags>
          <!-- </el-form-item> -->
        </el-form>
      </el-tab-pane>
      <!-- 资源库面板选择栏 -->
      <el-tab-pane name="selector">
        <span slot="label">资源库</span>
        <el-row v-if="resourceTabLoaded" id="resources-row">
          <el-col :span="7" id="resources-col">
            <!-- <dim-select :dim-info="{'enable':true}" @callback="callback"></dim-select>
            <el-tree
              :render-content="renderContent"
              :data="catalogTree"
              @node-click="catalogTreeNodeClick"
              default-expand-all highlight-current
              :node-key="treeOptions.key"
              :props="treeOptions"
              :expand-on-click-node="false"
              class="catalog-tree">
            </el-tree> -->
            <resource-select-menu @callback="catalogTreeNodeClick"></resource-select-menu>

          </el-col>
          <el-col :span="17">
            <el-toolbar style="position:relative" v-if="tmpResourceProps.selectorURL === 'imageResources'">
              <span >
                <el-button @click="cutImage">
                  <i class="fa fa-cut"></i>裁剪</el-button>
              </span>
            </el-toolbar>
            <div id="resources-search-div">
               <resource-tag-search :tags.sync="tags" ref="tagRef" @callback="loadingResourcesData" style="width:200px"></resource-tag-search>
              <el-input v-model="keyword" @keyup.enter.native="loadingResourcesData" style="width:270px" placeholder="请选择标题">
                <el-button slot="append" @click="loadingResourcesData">查询</el-button>
              </el-input>
            </div>
            <div v-if="tmpResourceProps.selectorURL === 'imageResources'">
              <el-row class="resource-icon">
                <component :is="tmpResourceProps.multiUpload==='Y'?'el-checkbox-group':'el-radio-group'" v-model="selectedData" style="width: 100%;" @change="selectionChange">
                  <el-col :span="6" v-for="item in resourcesData" v-bind:key="item.ID" :offset="1">
                  <el-card :body-style="{ padding: '0px' }">
                    <div @click.stop="updateCheckedData(item)">
                      <div class="image"><img :imageid="item.ID" :title="item.name" :src="tmpResourceProps.prefix+item.logoFile" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';"/></div>
                      <div class="resource-title">
                        <component :is="tmpResourceProps.multiUpload==='Y'?'el-checkbox':'el-radio'" :label="item" :title="item.oldName">{{item.oldName}}</component>
                      </div>
                    </div>
                  </el-card>
                  </el-col>
                </component>
              </el-row>
            </div>
            <div v-if="tmpResourceProps.selectorURL === 'fileResources'">
              <el-table :data="resourcesData" height="320" class="resources-table" v-loading="resourcesDataLoading" highlight-current-row @selection-change="updateCheckedData">
                <el-table-column type="index" label=" " width="60" align="center"></el-table-column>
                <el-table-column type="selection" width="40" align="center"></el-table-column>
                <el-table-column label="名称" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{scope.row.oldName}}
                  </template>
                </el-table-column>
                <el-table-column width="60" label="类型" align="center">
                  <template slot-scope="scope">
                    <img :src="scope.row.icon">
                  </template>
                </el-table-column>
                <el-table-column prop="fileSize" width="100" label="大小" align="center"></el-table-column>
              </el-table>
            </div>
            <div v-if="tmpResourceProps.selectorURL === 'videoResources'">
              <div class="floatVideoWrap" v-if="videoWrapModal">
                <video-player :src="videoFilePath" :poster="videoFilePath" :auto-play="true" width="450px" height="300px"></video-player>
              </div>
              <el-table :data="resourcesData" height="320" class="resources-table" v-loading="resourcesDataLoading" highlight-current-row @selection-change="updateCheckedData">
                <el-table-column type="index" label=" " width="60" align="center"></el-table-column>
                <el-table-column type="selection" width="40" align="center"></el-table-column>
                <el-table-column label="名称" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <div  class="floatPicCell">
                      {{scope.row.oldName}}.{{scope.row.suffix}}
                      <div class="floatPicWrap" v-show="!!scope.row.logFile">
                          <img :src="tmpResourceProps.prefix+scope.row.logoFile" style="max-height:120px;max-width:120px" onerror="this.src='assets/images/picture404-'+((row.ID||row.$index) % 4)+'.png';"/>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="60" label="类型" align="center">
                  <template slot-scope="scope">
                    <img :src="scope.row.icon">
                  </template>
                </el-table-column>
                <el-table-column prop="fileSize" width="100" label="大小" align="center"></el-table-column>
                <el-table-column width="90" label=" ">
                  <template slot-scope="scope">
                    <span class="video-preview" @mouseover="videoPreview(scope.row)" @mouseout="videoWrapModal = false">
                      <el-button type="text">视频预览</el-button>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-if="tmpResourceProps.selectorURL === 'audioResources'">
              <el-table :data="resourcesData" height="320" class="resources-table" v-loading="resourcesDataLoading" highlight-current-row @selection-change="updateCheckedData">
                <el-table-column type="index" label=" " width="60" align="center"></el-table-column>
                <el-table-column type="selection" width="40" align="center"></el-table-column>
                <el-table-column label="名称" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{scope.row.oldName}}.{{scope.row.suffix}}
                  </template>
                </el-table-column>
                <el-table-column width="60" label="类型" align="center">
                  <template slot-scope="scope">
                    <img :src="scope.row.icon">
                  </template>
                </el-table-column>
                <el-table-column prop="fileSize" width="100" label="大小" align="center"></el-table-column>
                <el-table-column width="100" label=" ">
                  <template slot-scope="scope">
                    <audio :ref="'audioPlayer'+scope.row.ID" :id="'audioPlayer'+scope.row.ID" :src="tmpResourceProps.prefix + scope.row.path">您的浏览器不支持 audio 标签。</audio>
                    <span class="audio-player">
                      <i title="播放" @click.stop="audioStart('audioPlayer'+scope.row.ID)" class="fa fa-play fa-fw"></i>
                      <i title="暂停" @click.stop="audioPause('audioPlayer'+scope.row.ID)" class="fa fa-pause fa-fw"></i>
                      <i title="停止" @click.stop="audioStop('audioPlayer'+scope.row.ID)" class="fa fa-stop fa-fw"></i>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!--分页-->
            <div class="resources-page-bar">
              <el-pagination @size-change="sizeChangeHandler" @current-change="currentChangeHandler" :current-page.sync="pageIndex" :page-sizes="pageSizes" :page-size="pageSize" :total="total" layout="total,->, prev, pager, next, jumper">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <!-- 栏目选择框 -->
    <catalog-selector inputType="checkbox" :show.sync="catalogSelectorModal" title="选择需要复制到的栏目" @callback="catalogSelectorCallback"></catalog-selector>
    <imagecutting-dialog :show.sync="imageCuttingModal" :imagePath="currentImagePath" :siteID="resourceDialogProps.siteID" @callback="imageCuttingCallback"></imagecutting-dialog>
  </div>
</template>

<script>
/* global _, Vue */
import util from '@src/common/util.js'
import catalogSelector from './CatalogSelector.vue'
import commonImageCuttingDialog from '../commonImageCuttingDialog.vue'
import WaterPositionPicker from './WaterPositionPicker.vue'
import videoPlayer from '@src/components/VideoPlayer.vue'
import DimSelect from '@src/components/DimSelect.vue'

import ResourceSelectMenu from './ResourceSelectMenu.vue'
import resourceTag from '../../workspace/components/ResourceTags.vue'
import ResourceTagSearch from '../../workspace/ResourceTagSearch.vue'
export default {
  data() {
    return {
      videoFilePath: '',
      videoWrapModal: false,
      imageCuttingModal: false,
      resourceTabLoaded: false, // 是否加载过资源标签，默认不加载
      tmpFileList: [], // 文件待上传列表
      resourcesIDs: [], // 资源id
      catalogSelectorModal: false, // 控制栏目选择框
      resourcesDataLoading: false, // 资源数据加载动画
      currentImagePath: '',
      selectedData: [],
      resourcesData: [], // 资源数据
      pageSizes: [10, 20, 30, 50], // 分页大小控制
      pageSize: 30, // 分页当前页大小
      pageIndex: 1, // 分页当前页索引
      total: 0, // 分页中数据总量
      keyword: '', // 搜索关键词
      tags: '',
      catalogTree: [], // 栏目树数据
      tmpParams: {}, // 图片上传参数
      tabActiveName: 'uploader', // 面板选择控制
      logoThumbModeOptions: [{ key: 'fit', label: '原比例缩放' }, { key: 'fill', label: '裁剪缩放' }], // logo图缩放模式数据
      tmpResourceProps: {},
      selectDatas: [], // 对接
      videoEdit: {
        url: '',
        width: 0,
        height: 0,
        display: '',
        poster: ''
      },
      progressInfo: {
        visible: false,
        percent: 0
      }
    }
  },
  methods: {
    callback(val) {
      this.catalogTree = val
    },
    videoPreview(row) {
      this.videoFilePath = row.prefix + row.path
      this.videoWrapModal = true
    },
    cutImage() {
      if (!this.currentImagePath) {
        this.$alert('请先选择一条记录', '提示', {
          type: 'info'
        })
        return
      }
      this.imageCuttingModal = true
    },
    imageCuttingCallback(sPath, path) {
      this.selectDatas[0].path = path
    },
    audioStart(refName) {
      let audio = this.$refs[refName]
      audio.play()
    },
    audioPause(refName) {
      let audio = this.$refs[refName]
      audio.pause()
    },
    audioStop(refName) {
      let audio = this.$refs[refName]
      audio.currentTime = 0
      audio.pause()
    },
    reset() {
      this.pageSize = 30
      this.pageIndex = 1
      this.selectDatas = []
      this.currentImagePath = ''
      this.tmpFileList = []
      this.resourceIDs = ''
      this.resourcesData = []
      this.tabActiveName = this.resourceDialogProps.isEdit ? 'videoEdit' : 'uploader'
      this.tmpResourceProps = {}
    },
    // 自动填写名称
    autoFillOldName(pathURL) {
      if (
        pathURL &&
        pathURL.lastIndexOf('/') > -1 &&
        pathURL.lastIndexOf('.') > -1 &&
        pathURL.lastIndexOf('.') > pathURL.lastIndexOf('/')
      ) {
        let name = pathURL.substring(pathURL.lastIndexOf('/') + 1, pathURL.lastIndexOf('.'))
        if (!this.tmpResourceProps.oldName) {
          this.tmpResourceProps.oldName = name
        }
      }
    },
    // 面板选择
    onResourceTabsClick(val) {
      if (val.name === 'selector') {
        if (!this.resourceTabLoaded) {
          this.resourceTabLoaded = true
        }
        this.loadingResourcesData()
      }
    },
    // 栏目树点击节点触发事件
    catalogTreeNodeClick(val) {
      this.tmpResourceProps.branchInnerCode = val
      this.loadingResourcesData()
    },
    // 加载资源数据
    async loadingResourcesData() {
      this.tmpResourceProps.branchInnerCode = this.tmpResourceProps.branchInnerCode ? this.tmpResourceProps.branchInnerCode : 'Y'
      this.selectedData = []
      this.selectDatas = []
      let obj = {
        branchInnerCode: this.tmpResourceProps.branchInnerCode,
        siteID: this.tmpResourceProps.siteID,
        resourceType: this.tmpResourceProps.resourceType,
        keyword: encodeURIComponent(this.keyword),
        tags: encodeURIComponent(this.tags),
        suffix: this.tmpResourceProps.suffix,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex - 1
      }
      let res = await axios.get('/ui/resourcesselector/resourcesdatagrid', {
        params: obj
      })
      this.resourcesData = res.data.data
      this.total = res.data.total
    },
    // 资源库页面大小改变事件
    sizeChangeHandler(val) {
      this.pageSize = val
      this.loadingResourcesData()
    },
    // 资源库页面索引改变事件
    currentChangeHandler(val) {
      this.pageIndex = val
      this.loadingResourcesData()
    },
    // 资源复制
    copy() {
      if (!this.currentImagePath) {
        this.$alert('请选择需要复制的资源文件', '提示', {
          confirmButtom: '确定',
          type: 'info'
        })
        return
      }
      this.catalogSelectorModal = true
    },
    // 资源复制选中栏目后回调
    async catalogSelectorCallback(val) {
      if (val.ids.length === 0) {
        this.$alert('请选择需要复制到的栏目', '提示', {
          type: 'info'
        })
        return
      }
      let ids = this.resourcesIDs.join()
      let res = await axios.put(`/ui/catalogresources/${ids}/copy`, {
        catalogIDs: val.ids,
        siteID: this.siteID
      })
      util.showResponseMessage(res.data)
    },

    // 资源选择弹框打开回调
    async init() {
      this.tmpResourceProps = Object.assign({}, this.resourceDialogProps)
      let initResourceDialog = await axios.get('/ui/catalogresources/initresourcedialog', {
        params: {
          resourceType: this.tmpResourceProps.resourceType,
          inputType: this.tmpResourceProps.inputType
        }
      })
      Vue.set(this.tmpResourceProps, 'selectorURL', initResourceDialog.data.data.selectorURL)
      let resourceUploadInit = await axios.get('/ui/catalogresources/resourceuploadinit', {
        params: {
          manualAllowType: this.tmpResourceProps.manualAllowType,
          resourceType: this.tmpResourceProps.resourceType,
          siteID: this.tmpResourceProps.siteID,
          catalogID: this.tmpResourceProps.catalogID
        }
      })
      Vue.set(this.tmpResourceProps, 'sourceType', 'upload')
      Vue.set(this.tmpResourceProps, 'URL', '')
      Vue.set(this.tmpResourceProps, 'oldName', '')
      Vue.set(this.tmpResourceProps, 'width', this.tmpResourceProps.logoWidth ? this.tmpResourceProps.logoWidth : this.tmpResourceProps.imageWidth)
      Vue.set(this.tmpResourceProps, 'height', this.tmpResourceProps.logoHeight ? this.tmpResourceProps.logoHeight : this.tmpResourceProps.imageHeight)
      if (this.tmpResourceProps.resourceType === 'image') {
        Vue.set(this.tmpParams, 'addWaterImage', 'Y')
        Vue.set(this.tmpParams, 'logoThumbMode', 'fit')
        Vue.set(this.tmpParams, 'logoCutSavePart', 5)
      }
      Vue.set(this.tmpResourceProps, 'convert', this.tmpResourceProps.resourceType === 'video' ? 'Y' : 'N')
      Vue.set(this.tmpResourceProps, 'allowType', '.' + resourceUploadInit.data.data.allowType.replace(/,/g, ',.'))
      Vue.set(this.tmpResourceProps, '_allowType', '.' + resourceUploadInit.data.data.allowType.replace(/,/g, '、.'))
      Vue.set(this.tmpResourceProps, 'prefix', resourceUploadInit.data.data.prefix)
      this.selectedData = this.tmpResourceProps.multiUpload === 'Y' ? [] : {}
    },
    // 改变选中文件触发事件
    selectFileChangeHandler(file, files) {
      let suffix = file.name.substring(file.name.lastIndexOf('.')).toLocaleLowerCase()
      let allowType = this.tmpResourceProps.allowType
      let isAllowType = allowType.split(',').some(type => type === suffix)
      if (!isAllowType) {
        files.splice(files.length - 1, 1)
        this.$message.info('请选择指定的文件格式')
        return
      }
      if (this.tmpResourceProps.multiUpload !== 'Y' && files.length > 1) {
        this.tmpFileList = _.slice(files, 0, 1)
        this.$message.info('文件总数量限制为1')
      } else {
        this.tmpFileList = files
      }
    },

    updateCheckedData(item) {
      if (_.isArray(item)) {
        this.selectDatas = item
        this.resourcesIDs = []
        for (var v of item) {
          this.resourcesIDs.push(v.ID)
        }
        this.currentImagePath = this.selectDatas.length > 0 ? this.selectDatas[0].path : ''
      } else {
        this.resourcesIDs = [item.ID]
        this.currentImagePath = item.path || ''
        if (this.tmpResourceProps.multiUpload === 'Y') {
          if (this.selectDatas.includes(item)) {
            this.selectDatas = this.selectDatas.filter(val => val.ID !== item.ID)
          } else {
            this.selectDatas.push(item)
          }
          this.selectedData = [...this.selectDatas]
        } else {
          this.selectedData = item
          this.selectDatas = [item]
        }
      }
    },
    selectionChange(val) {
      if (this.tmpResourceProps.multiUpload === 'Y') {
        this.selectDatas = [...val]
      }
    },
    selectFileRemoveHandler(file, files) {
      this.tmpFileList = files
    },

    // 文件上传确定事件
    async uploadFile() {
      if (this.tmpFileList.length === 0) {
        this.$alert('请选择要上传的文件', '提示', {
          type: 'warning'
        })
        return
      }
      const formData = new FormData()
      for (var file of this.tmpFileList) {
        formData.append('file', file.raw)
      }

      if (!this.tmpResourceProps.tag) {
        this.tmpResourceProps.tag = ''
      }

      for (let i in this.tmpResourceProps) {
        formData.append(i, this.tmpResourceProps[i])
      }
      for (let i in this.tmpParams) {
        formData.append(i, this.tmpParams[i])
      }
      let progressInfo = this.progressInfo
      progressInfo.visible = true
      let upload = await axios.post(`/ui/catalogresources/${this.tmpResourceProps.catalogID || 0}/upload`, formData, {
        timeout: 0,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: function(e, file) {
          let total = e.total - 0
          let loaded = e.loaded - 0
          progressInfo.percent = total === loaded ? 100 : (loaded / total * 100).toFixed() - 0
        }
      }).catch(e => {
        console.error(e)
        util.showErrorMessageBox('上传失败！')
      })
      if (!upload){
        return
      }

      util.showResponseMessage(upload.data)
      if (upload.data.status === 1) {
        Object.assign(this.progressInfo, {visible: false, percent: 0})
        if (this.tmpResourceProps.multiUpload === 'Y') {
          this.selectDatas = upload.data.dt
        } else {
          this.selectDatas = []
          let resourceData = upload.data
          Vue.set(resourceData, 'width', this.tmpResourceProps.width)
          Vue.set(resourceData, 'height', this.tmpResourceProps.height)
          this.selectDatas.push(resourceData)
        }
        if (this.resourceDialogProps.dataType && this.resourceDialogProps.dataID) {
          let resourceIDs = this.selectDatas.map(item => item.resourceID)
          this.saveRela(resourceIDs.join(), true)
        }
        if (this.tmpResourceProps.selectorURL === 'videoResources') {
          let displayStyle = await this.videoResourceTypeBox()
          for (var item of this.selectDatas) {
            item.displayStyle = displayStyle
          }
        }

        this.$emit(
          'callback',
          this.selectDatas
        )
        return [upload.data.previewPrefix + upload.data.path, upload.data.path, upload.data.resourceID]
      }
    },
    //  确定资源选中事件返回callback回调函数，附带文件预览路径、文件路径、资源id参数
    async resourceConfirm() {
      if (this.tabActiveName === 'uploader') {
        if (this.tmpResourceProps.sourceType === 'upload') {
          return this.uploadFile()
        }
        if (this.tmpResourceProps.sourceType === 'internet') {
          return [this.tmpResourceProps.URL, this.tmpResourceProps.URL]
        }
      }
      if (this.tabActiveName === 'selector') {
        if (this.tmpResourceProps.selectorURL === 'imageResources') {
          await this.loadThumbImages()
        }
        let path = this.selectDatas[0].resourcePath || this.selectDatas[0].path
        return [this.tmpResourceProps.prefix + path, path, this.resourcesIDs[0], true]
      }
    },
    async confirm() {
      if (this.tabActiveName === 'videoEdit') {
        this.$emit('callback', [
          {
            path: this.videoEdit.url,
            width: this.videoEdit.width,
            height: this.videoEdit.height,
            displayStyle: this.videoEdit.display,
            poster: this.videoEdit.poster
          }
        ])
      }
      if (this.tabActiveName === 'uploader') {
        if (this.tmpResourceProps.sourceType === 'upload') {
          this.uploadFile()
          return
        }
        if (this.tmpResourceProps.sourceType === 'internet') {
          this.selectDatas.push({
            type: 'net',
            path: this.tmpResourceProps.URL,
            url: this.tmpResourceProps.URL,
            oldName: this.tmpResourceProps.oldName
          })
          this.$emit(
            'callback',
            this.selectDatas
          )
        }
      }
      if (this.tabActiveName === 'selector') {
        if (this.selectDatas.length === 0) {
          this.$alert('请选择一个资源文件', '提示', {
            type: 'warning'
          })
          return
        }

        for (let item of this.selectDatas) {
          item.previewPrefix = this.tmpResourceProps.prefix
          item.resourceID = item.ID
        }

        // 视频资源，设置displayStyle
        if (this.tmpResourceProps.selectorURL === 'videoResources') {
          let displayStyle = await this.videoResourceTypeBox()
          for (let item of this.selectDatas) {
            item.displayStyle = displayStyle
          }
        }

        // 图片资源，获取指定尺寸的图
        if (this.tmpResourceProps.selectorURL === 'imageResources') {
          await this.loadThumbImages()
        }
        this.$emit('callback', this.selectDatas)
      }
      this.reset()
    },

    async loadThumbImages() {
      let imagePaths = this.selectDatas.map(item => item.path)
      let res = await axios.get('/ui/article/getthumbimage', {
        params: {
          imagePaths: imagePaths.join(),
          imageWidth: this.tmpResourceProps.imageWidth,
          imageHeight: this.tmpResourceProps.imageHeight
        }
      })
      let result = res.data.imageLinks
      for (var i in result) {
        this.selectDatas[i].resourcePath = result[i]
      }
    },

    videoResourceTypeBox () {
      const h = this.$createElement
      let value = 'simple'
      return this.$msgbox({
        title: '插入视频',
        message: h('div', null, [
          h('span', null, '选择呈现视频风格：'),
          h('input', {
            attrs: {
              id: 'simpleRadio',
              type: 'radio',
              value: 'simple',
              name: 'videoStyle',
              checked: 'checked' }
          }, '简单'),
          h('span', null, '简单  '),
          h('input', {
            attrs: {
              id: 'foldRadio',
              type: 'radio',
              value: 'fold',
              name: 'videoStyle' }
          }, '折叠'),
          h('span', null, '折叠')
        ]),
        confirmButtonText: '确定',
        showClose: true,
        beforeClose: (action, instance, done) => {
          const $foldRadio = instance.$el.querySelector('#foldRadio')
          value = $foldRadio.checked ? 'fold' : 'simple'
          done()
        }
      }).then(() => {
        return value
      })
    },
    /**
     * dataType和dataID不为空时记录资源引用关系
     * delFlag: 是否先删除原有引用记录
     */
    async saveRela(resourceID, delFlag) {
      let obj = {
        resourceIDs: resourceID,
        dataType: this.resourceDialogProps.dataType,
        dataID: this.resourceDialogProps.dataID,
        delFlag: delFlag ? 'Y' : 'N'
      }
      await axios.put(`/ui/catalogresources/${resourceID}/saverela`, obj)
    }
  },
  async created () {
    await this.init()
    this.tabActiveName = this.resourceDialogProps.isEdit ? 'videoEdit' : 'uploader'

    if (this.resourceDialogProps.isEdit) {
      let editor = window.editor

      var range = editor.selection.getRange()

      var img = range.getClosedNode()

      Object.assign(this.videoEdit, {
        url: img.getAttribute('_url'),
        width: parseInt(img.getAttribute('width')),
        height: parseInt(img.getAttribute('height')),
        display: img.getAttribute('_display'),
        poster: img.getAttribute('_poster')
      })
    }
  },
  props: {
    resourceDialogProps: {
      type: Object,
      required: true
    }// 传递过来的对象，可包含manualAllowType,dataType,dataID,resourceType,siteID
    //  catalogIDlogoWidth,logoHeight,resourceID,inputType,suffix等多个属性
  },
  watch: {
    resourceDialogProps: {
      handler: function (val, oldVal) {
        this.init()
      },
      deep: true
    }
  },
  components: {
    'catalog-selector': catalogSelector,
    'imagecutting-dialog': commonImageCuttingDialog,
    'water-position-picker': WaterPositionPicker,
    'video-player': videoPlayer,
    'dim-select': DimSelect,
    'resource-select-menu': ResourceSelectMenu,
    'resource-tags': resourceTag,
    'resource-tag-search': ResourceTagSearch
  },
  filters: {
    formatSymbol(val) {
      console.log(val)
      if (!val) {
        return ''
      }
      return val.replace(/,/g, '、')
    }
  }
}
</script>

<style>
#resources-col .node-content {
  position: relative;
}
.resource-content .el-toolbar,.resource-content .el-toolbar-body {
  height: 50px;
}
.resource-content .el-tabs__content {
  height: 460px;
  overflow: auto;
}
.resource-content .el-tabs__header.is-top{
  padding-top: 0;
  height: 50px;
}
.resource-content .resource-icon {
  width: 100%;
  height: 320px;
  overflow: auto;
  background-color: #f9f9f9;
  margin: 0 auto;
}
.resource-content .resource-icon .el-col-offset-1 {
  margin-left: 3.33333%;
}
.resource-content .resource-icon .image {
  display: table-cell;
  height: 120px;
  vertical-align: middle;
}
.resource-content .resource-icon .el-card {
  border: 0;
  border-radius: 0;
  background: rgba(0, 0, 0, 0);
  box-shadow: 0 0 0 0;
  overflow: hidden;
  height: 150px;
  margin: 5px;
}
.resource-content .resource-icon .el-card img {
  max-width: 100%;
  max-height: 100%;
  margin: 0 auto;
}
.resource-content .resource-icon .el-card img:hover {
  background: #fff68f;
}
.resource-content .resource-icon .resource-title {
  margin-top: 5px;
}
.resource-content .resource-icon .resource-title .el-radio {
  text-overflow: ellipsis;
  overflow: hidden;
}
.resource-content .resource-icon .resource-title .el-checkbox .el-radio__label {
  font-weight: 100 !important;
  font-size: 13px;
  padding-left: 2px;
}
.resource-content .resource-icon .el-col-6 {
  width: 21%;
}
.resource-content .el-table {
  margin: 0;
}
</style>

<style scoped>
.tabs-wrap {
  height: 510px;
}

#resources-row {
  height: 460px;
  background-color: #f5f5f5;
}

#resources-col {
  overflow: auto;
  height: 99%;
}

.catalog-tree {
  color: black;
}

#resources-search-div {
  padding: 5px;
  text-align: right;
  border: 1px solid #eee;
  border-width: 1px 0;
}

.resources-page-bar {
  width: 100%;
  position: relative;
  bottom: 0px;
}

.resources-table {
  width: 100%;
}

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

.el-upload__tip {
  word-break: break-all;
  word-wrap: break-word;
  line-height: 24px;
}

.floatPicWrap {
  display: none !important;
}

.floatPicCell:hover .floatPicWrap {
  display: block !important;
  position: absolute;
  left: 0;
  top: 0;
  float: left;
  z-index: 2200;
}

.audio-player {
  padding: 2px 0 2px 5px;
}

.audio-player:hover {
  border: 1px solid #ccc;
}

.video-preview:hover {
  padding: 5px 0;
  border: 1px solid #ccc;
}

.floatVideoWrap{
  position: absolute;
  float: left;
  z-index: 2200;
}
</style>
