<template>
  <div class="common-dialogs-wrap">
    <resource-dialog :title="resourcePickerDlg.dialogTitle" :resourceDialogProps.sync="resourcePickerDlg.resourceDialogProps" :show.sync="resourcePickerDlg.show" @callback="resourceCallback"></resource-dialog>
  </div>
</template>
<script>
// import _ from 'lodash'
import resourceDialog from '@src/pages/contentcore/resourceDialog.vue'
var zcmsCommon = {}
var exchangeFn = null
export default {
  components: {
    'resource-dialog': resourceDialog
  },
  data () {
    return {
      resourceDialogProps: {
        resourceType: 'image',
        imageWidth: 500,
        imageHeight: 500
      },
      resourcePickerDlg: {
        show: false,
        dialogTitle: '选择资源',
        resourceDialogProps: {}
      }
    }
  },
  props: {

  },
  created () {
    window.zcmsCommon = zcmsCommon
    this.init()
  },
  methods: {
    init () {
      this.initUpload()
      // 后续可继续扩展其他CMS公共组件如站点、栏目、文章选择器
    },
    initUpload() {
      // 上传图片
      zcmsCommon.uploadImage = (title, props, callback) => {
        if (arguments.length === 2 && typeof arguments[1] === 'object' && typeof arguments[1] === 'function') {
          title = '图片上传'
          props = arguments[0]
          callback = arguments[1]
        }
        upload('image', title, props, callback)
      }
      // 上传视频
      zcmsCommon.uploadVideo = (title, props, callback) => {
        if (arguments.length === 2 && typeof arguments[1] === 'object' && typeof arguments[1] === 'function') {
          title = '视频上传'
          props = arguments[0]
          callback = arguments[1]
        }
        upload('video', title, props, callback)
      }
      // 上传音频
      zcmsCommon.uploadAudio = (title, props, callback) => {
        if (arguments.length === 2 && typeof arguments[1] === 'object' && typeof arguments[1] === 'function') {
          title = '音频上传'
          props = arguments[0]
          callback = arguments[1]
        }
        upload('audio', title, props, callback)
      }
      let upload = (type, title, props, callback) => {
        this.resourcePickerDlg.dialogTitle = title
        const resourceDialogProps = Object.assign({}, this.resourceDialogProps, props)
        resourceDialogProps.resourceType = type
        this.resourcePickerDlg.resourceDialogProps = resourceDialogProps
        this.resourcePickerDlg.show = true
        if (callback) {
          exchangeFn = callback
        } else {
          exchangeFn = null
        }
      }
    },
    // 选择资源后的回调
    resourceCallback (previewPath, filePath, resourceID) {
      // 可以通过事件机制获取选择后的资源
      if (window.eventHub && typeof window.eventHub.$emit === 'function') {
        window.eventHub.$emit('resourceUploaded', {previewPath, filePath, resourceID})
      }
      if (typeof exchangeFn === 'function') {
        exchangeFn(previewPath, filePath, resourceID)
        exchangeFn = null
      }
    }
  }
}
</script>
