/* global Window localStorage axios $ Vue UE location ZPageBreak _ */
import './articleEditor.css'
import util from '@src/common/util.js'
import contentScript from '../contentcore/js/contentScript.js'
import ueditor from '@src/components/ueditor.vue'
import editormd from '@src/components/editormd.vue'
import selectWordsDialog from '../wordmanage/components/WordPicker.vue'
import setTopDialog from '../contentcore/components/SetTopDialog.vue'
import ContentSelector from '@src/components/contentComponent/ContentSelector.vue'
import catalogSelector from '../contentcore/components/CatalogSelector.vue'
import LogoPath from '../contentcore/components/LogoPath.vue'
import templateDialog from '../contentcore/components/TemplateDialog.vue'
import ContentExtend from '../contentcore/components/ContentEditorExtend.vue'
import MobileContentEditor from './mobileContentEditor.vue'
// import config from './articleEditorCommon.js'
import voteItem from '../vote/voteItem.vue'
import advertiseList from '../advertise/advertiseList.vue'
// import independentTemplate from '../contentcore/components/IndependentTemplate.vue'
// 按钮
import contentSaveButton from '../contentcore/components/ContentSaveButton.vue'
import contentPublishButton from '../contentcore/components/ContentPublishButton.vue'
import contentLockButton from '../contentcore/components/ContentLockButton.vue'
import contentViewButton from '../contentcore/components/ContentViewButton.vue'
import contentVersionButton from '../contentcore/components/ContentVersionButton.vue'
import contentSimilarButton from '../contentcore/components/ContentSimilarButton.vue'
import contentOperatlogButton from '../contentcore/components/ContentOperatLogButton.vue'
import contentRecBlockButton from '../contentcore/components/ContentRecBlockButton.vue'
import contentWeiboSendButton from '../contentcore/components/ContentWeiboSendButton.vue'
import contentDeployButton from '../contentcore/components/ContentDeployButton.vue'
import contentCopyButton from '../contentcore/components/ContentCopyButton.vue'
import selectTags from '@src/components/contentComponent/selectTags.vue'
import TemplatePicker from '../contentcore/TemplatePicker.vue'
// import TreeSelect from '@src/components/TreeSelect.vue'
import emitter from '@src/mixins/emitter.js'
import postil from './components/Postil.vue'
import commentFormItem from '../comment/components/ContentEditorExtendAction.vue'
import contentMoveButton from '../contentcore/components/ContentMoveButton.vue'
import nwCornerButton from '@src/components/nw-corner-button.vue'

import contentDetailToolbar from '../contentcore/components/ContentDetailToolbar.vue'

import Privilege from '@src/common/privilege.js'
import BackTop from '@src/components/back-top.vue'

const config = {
  // bodyFontFamily: '隶书, SimLi',
  sourceEditorFirst: false,
  // initialContent: contents[0], //初始化编辑器的内容
  wordCount: false, // 关闭字数统计
  minFrameHeight: 350, // 无内容时编辑器的原始高度
  // initialFrameWidth: 690, //初始化编辑器宽度,默认680
  initialFrameHeight: 1300, // 初始化编辑器高度,默认400
  frameBodyWidth: 770, // 编辑区域宽度
  initialStyle: '',
  elementPathEnabled: false, // 关闭elementPath
  autoFloatEnabled: false, // 是否保持toolbar的位置不动,默认true
  selfCatalog: 'Y',
  page: 1,
  toolbars: [
    [
      'undo',
      'redo',
      'fullscreen',
      '|',
      'source',
      'zcheckwords',
      'fontfamily',
      'fontsize',
      'bold',
      'italic',
      'underline',
      // 'strikethrough',
      'forecolor',
      'backcolor',
      'paragraph',
      '|',
      'justifyleft',
      'justifycenter',
      'justifyright',
      'justifyjustify',
      'autotypeset',
      'indent',
      'link',
      'unlink',

      'zmedia', // 'zimage', 'zvideo', 'zaudio', 'zfile',
      'zcomponent', // 'zvote', 'zatverdise', 'zimagegroup',
      'zlink', // 'zcontent', 'zcatalog',
      'zcomment',
      'zpagebreak',
      'zresourceurl',

      'insertorderedlist',
      'insertunorderedlist',
      '|',
      'rowspacingtop',
      'rowspacingbottom',
      'lineheight',
      'removeformat',
      'searchreplace',
      'zround', // 'imagenone', 'imageleft', 'imageright', 'imagecenter',
      // 'emotion',
      'horizontal',
      'inserttable',
      'ztable', // 'deletetable', '|', 'insertrow', 'deleterow', 'insertcol', 'deletecol'
      'zwxeditor', 'xiumi-connect', '135editor'
    ]
  ]
}
let autoSaveInterval = null
export default {
  mixins: [emitter],
  components: {
    contentDetailToolbar,
    commentFormItem,
    postil,
    ueditor,
    editormd,
    'select-tags-dialog': selectWordsDialog,
    'select-sources-dialog': selectWordsDialog,
    'catalog-selector-dialog': catalogSelector,
    'settop-dialog': setTopDialog,
    'template-dialog': templateDialog,
    'logo-path': LogoPath,
    'content-extend': ContentExtend,
    'mobile-content-editor': MobileContentEditor,
    'content-selector': ContentSelector,
    'vote-item': voteItem,
    'atverdise-list': advertiseList,
    'content-move-button': contentMoveButton,
    'nw-corner-button': nwCornerButton,
    // independentTemplate,
    contentVersionButton,
    contentSimilarButton,
    contentOperatlogButton,
    contentRecBlockButton,
    contentWeiboSendButton,
    contentPublishButton,
    contentLockButton,
    contentViewButton,
    contentSaveButton,
    contentDeployButton,
    contentCopyButton,
    'template-picker': TemplatePicker,
    'select-tags': selectTags,
    'BackTop': BackTop
  },
  props: {
    content: {
      type: Object,
      default: function () {
        return {
          titleStyle: { color: '' },
          shortTitleStyle: { color: '' },
          detailTemplate: [],
          templateFlag: 'N'
        }
      }
    },
    siteConfig: {
      type: Object,
      default: function () {
        return {}
      }
    },
    contentId: {
      type: [String, Number]
    },
    catalogId: {
      type: [String, Number]
    }
  },
  inject: ['loadContent'],
  data () {
    var validateTitle = (rule, value, callback) => {
      if (value) {
        if (util.getLengthEx(value, true) > 360) {
          callback(new Error('字数必须小于或等于120个汉字或360个字母'))
        } else {
          this.verifySameTitle()
          callback()
        }
      } else {
        callback(new Error('请输内容'))
      }
    }
    var validateShortTitle = (rule, value, callback) => {
      if (value) {
        if (util.getLengthEx(value, true) > 150) {
          callback(new Error('字数必须小于或等于50个汉字或150个字母'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateKeyword = (rule, value, callback) => {
      if (value) {
        if (util.getLengthEx(value, true) > 200) {
          callback(new Error('字数必须小于或等于80个汉字或200个字母'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateSubTitle = (rule, value, callback) => {
      if (value) {
        if (util.getLengthEx(value, true) > 200) {
          callback(new Error('字数必须小于或等于66个汉字或200个字母'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validateSourceTitle = (rule, value, callback) => {
      if (value) {
        if (util.getLengthEx(value, true) > 360) {
          callback(new Error('字数必须小于或等于120个汉字或360个字母'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var contentRules = (rule, value, callback) => {
      if (!this.isLinkContentFlag) {
        callback()
      } else if (value) {
        callback()
      } else {
        callback(new Error('请输内容'))
      }
    }
    var linkRules = (rule, value, callback) => {
      if (this.isLinkContentFlag) {
        callback()
      } else if (value) {
        callback()
      } else {
        callback(new Error('请输内容'))
      }
    }
    return {
      sameTitleShow: false, // 存在在相同标题提醒文字
      sameTitleNotice: '',
      customLayout: {},
      atverdiseID: '',
      atverdiseDialogShow: false,
      voteItemID: '',
      voteDialogShow: false,
      activeNames: ['1', '2', '3'], // 右侧折叠面板
      contentID: '',
      // 编辑器配置
      editorConfig: config,
      resourceDialogProps: {
        selectorURL: 'imageResources',
        resourceType: 'image',
        allowType: '.jpg,.jpeg,.png,gif,.bmp',
        height: 200,
        width: 200,
        imageWidth: 500, // 默认内容插入图片宽度和栏目配置项相同
        imageHeight: 500, // 默认内容插入图片高度和栏目配置项相同
        logoWidth: 120, // 默认LOGO图宽度和栏目配置项相同
        logoHeight: 120, // 默认LOGO图高度和栏目配置项相同
        url: ''
      },
      editor: {},
      PAGE_SPLIT: '<!--_ZVING_PAGE_BREAK_-->',
      TITLE_SPLIT: '|',
      // bodyText: '',
      mainHeight: '',
      showWxEditorFlag: false,
      contentType: 'Article',
      isLinkContentFlag: false,
      showShortTitleFlag: false,
      showSubTitleFlag: false,
      showSourceTitleFlag: false,
      contentAttributes: [],
      platformAttributes: window.app.platformAttributes,
      // channelAttributes: [],
      attributes: [],
      tagFlag: false,
      sourceFlag: false,
      isInputUrl: false,
      contentSelectorDialogModal: false,
      catalogSelectorDialogModal: false,
      selectTemplateDialogFlag: false,
      name: '',
      isRightCatalog: false,
      showSetTopFlag: false,
      // topTime: '',
      isShowModal: false,
      templateAttribute: false,
      platformID: 'pc',
      templateChoicePath: {
        /** 模板选择组件属性 */
        isShowModal: false,
        templateAttribute: {
          path: '' /** 模板路径 */,
          templateType: 'ArticleDetail' /** 模板类型 */
        }
      },
      articleFormRules: {
        title: [{ required: true, validator: validateTitle, trigger: 'blur' }],
        shortTitle: [{ required: false, validator: validateShortTitle, trigger: 'blur,change' }],
        subTitle: [{ required: false, validator: validateSubTitle, trigger: 'blur,change' }],
        sourceTitle: [{ required: false, validator: validateSourceTitle, trigger: 'blur,change' }],
        keyword: [{ required: false, validator: validateKeyword, trigger: 'change' }],
        bodyText: [
          {
            validator: contentRules,
            trigger: 'blur'
          }
        ],
        cName: [
          {
            validator: linkRules,
            trigger: 'blur'
          }
        ]
      },
      selectPlatAttributes: [],
      link: '',
      showEditorFlag: false,
      contentTypes: [],
      formatItem: ['props', 'extend', 'attributes', 'detailTemplate'],

      baseInfo: false,
      tagInfo: {
        addTag: false,
        inputTag: '',
        hasSelect: false
      },
      wordInfo: {
        addWord: false,
        inputWord: ''
      },
      keywords: [],
      catalogTree: [],
      rightMenuBar: false,
      logoStyle: '',
      badWordDialogShow: false, // 敏感词对话框
      badwordConfirmPromise: null, // 敏感词Promise
      badwordAction: '', // 敏感词处理方式
      badWords: '',
      article: {},
      oldArticle: {}, // 自动保存时用来判断是否更新
      showExtend: false,
      leftToolPanelRender: false, // 控制H5菜单是否已渲染，默认不渲染，只有单击箭头后才在dom中渲染
      leftToolPanelLoading: false, // 控制初始加载h5菜单loading效果
      userName: localStorage.userName,
      firstPageTitle: '',
      keywordValidate: { error: false, tips: '字数必须小于或等于80个汉字或200个字母' }
    }
  },
  computed: {
    publishContentID: {
      get () {
        return this.article.ID && this.article.status === 30 ? this.article.ID : ''
      },
      set (val) {
        this.article.ID = val
      }
    },
    tags: {
      set (val) {
        this.article.tag = val
        this.article = Object.assign({}, this.article, { tag: val ? val.split(',') : [] })
      },
      get () {
        let initContent = Object.assign({}, this.article, { tags: this.article.tag ? this.article.tag.join(',') : '' })
        return initContent.tag ? initContent.tag.join(',') : ''
      }
    },
    summaryCounter () {
      return this.article.summary ? this.article.summary.length : 0
    },
    showPanel () {
      if (this.showExtend) {
        return true
      }
      let isShow = false
      for (let i in this.customLayout) {
        if (i !== 'bodyWidth' && this.customLayout[i] === 'L') {
          isShow = true
          return isShow
        }
      }
      return isShow
    }
  },
  watch: {
    content: {
      handler: function (val) {
        let userPreferences = JSON.parse(localStorage.userPreferences)
        let showSubTitleAndShortTitle = userPreferences.showSubTitleAndShortTitle === 'Y'
        this.showShortTitleFlag = !!this.content.shortTitle || showSubTitleAndShortTitle
        this.showSubTitleFlag = !!this.content.subTitle || showSubTitleAndShortTitle
        this.showSourceTitleFlag = !!this.content.sourceTitle
        this.showEditorFlag = !!this.content.editor
        this.keywords = this.content.keyword ? this.content.keyword.split(',') : []
        let article = JSON.parse(JSON.stringify(this.content))
        // 敏感词突出显示
        if (localStorage.highlightBadword === 'true' && this.badWords) {
          let bodyText = article.bodyText
          var badWords = this.badWords.split(' ')
          for (var i = 0; i < badWords.length; i++) {
            if (badWords[i]) {
              var substr = '<span style="background-color:yellow;">' + badWords[i] + '</span>'
              bodyText = bodyText.split(badWords[i]).join(substr)
            }
          }
          article.bodyText = bodyText
        }
        this.article = article
        this.oldArticle = JSON.parse(JSON.stringify(this.article))
        /** 自动保存 */
        if (autoSaveInterval === null) {
          if (Privilege.hasPriv('com.zving.cms.Catalog.Content.Edit.' + this.article.catalogID)) {
            if (this.article.siteConfigProps && this.article.siteConfigProps.articleAutoSave === 'Y') {
              autoSaveInterval = setInterval(async () => {
                if ((this.article.isLock === 'Y' && this.article.lockUser !== this.userName) || !this.article.ID || this.notUpdateArticle()) {
                  return
                }
                Window.saveContentAction = 'autoSave'
                await this.saveContent()
                Window.saveContentAction = ''
              }, 1000 * 60) // 设置文章自动保存，每分钟执行一次
              this.$once('hook:beforeDestroy', () => {
                clearInterval(autoSaveInterval)
              })
            }
          }
        }
        this.$nextTick(() => {
          if (typeof UE !== 'undefined' && UE.instants) {
            let bodyText = this.article.bodyText || ''
            let bodyArr = bodyText.split(this.PAGE_SPLIT)
            if (bodyArr.length > 1) {
              for (let i = 0, length = bodyArr.length; i < length; i++) {
                let currentInstant = _.find(UE.instants, function (instant) {
                  return instant.options.page && instant.options.page === i + 1
                })
                if (currentInstant) {
                  currentInstant.setContent(bodyArr[i])
                }
              }
            }
            this.firstPageTitle = this.article.pageTitles ? this.article.pageTitles.split(this.TITLE_SPLIT)[0] : ''
          }
        })
        this.initContent()
      },
      deep: true
    },
    siteConfig: {
      handler: function (val) {
        this.customLayout = JSON.parse(this.siteConfig.articleCustomLayout)
        config.frameBodyWidth = this.customLayout.bodyWidth ? this.customLayout.bodyWidth : 770
        config.initialStyle = 'body{'
        if (this.siteConfig.articleFontFamily){
          config.initialStyle += 'font-family:' + this.siteConfig.articleFontFamily + ';'
        }
        if (this.siteConfig.articleFontSize){
          config.initialStyle += 'font-size:' + this.siteConfig.articleFontSize + ';'
        }
        if (this.siteConfig.articleLetterSpacing){
          config.initialStyle += 'letter-spacing:' + this.siteConfig.articleLetterSpacing + ';'
        }
        if (this.siteConfig.articleLineHeight){
          config.initialStyle += 'line-height:' + this.siteConfig.articleLineHeight + ';'
        }
        config.initialStyle += '}'
      },
      deep: true
    },
    'article.title' (val) {
      util.title(val)
    }
  },
  async created () {
    if (this.$route.query.type === 'Article') {
      this.initWXEditorListener()
    }
    localStorage.highlightBadword = 'false'
    this.article = JSON.parse(JSON.stringify(this.content))
    let getContentType = await axios.get('/ui/contentcore/contenttypes')
    if (getContentType.data.status === 1) {
      this.contentTypes = getContentType.data.data
    }
    /*
    // 暂时注释发布渠道管理（需求待讨论）
    let getChannelAttributes = await axios.get('/ui/mediaconfig')
    this.channelAttributes = getChannelAttributes.data.data
    */
    this.initContent()
    this.contentID = this.$route.params.id === 'new' ? 0 : this.$route.params.id
    /** 自动保存 */
    if (Privilege.hasPriv('com.zving.cms.Catalog.Content.Edit.' + this.article.catalogID)) {
      if (this.article.siteConfigProps && this.article.siteConfigProps.articleAutoSave === 'Y') {
        autoSaveInterval = setInterval(async () => {
          if ((this.article.isLock === 'Y' && this.article.lockUser !== this.userName) || !this.article.ID || this.notUpdateArticle()) {
            return
          }
          Window.saveContentAction = 'autoSave'
          await this.saveContent()
        }, 1000 * 60) // 设置文章自动保存，每分钟执行一次
        this.$once('hook:beforeDestroy', () => {
          clearInterval(autoSaveInterval)
        })
      }
    }
  },
  async mounted () {
    if (window.UE) {
      let ueInstantKeys = _.keys(UE.instants)
      if (ueInstantKeys.length) {
        for (let i = 0, length = ueInstantKeys.length; i < length; i++) {
          UE.delEditor(ueInstantKeys[i])
        }
      }
      UE.instants = {}
      this.$emit('loaded')
      this.$refs['editor'] && this.$refs['editor'].initEditor()
    }
    this.$nextTick(_ => {
      this.fixedContentDetailToolbar()
      this.quickSave()
    })
  },
  beforeDestroy () {
    this.destroyEditorConfig() // 重置编辑器的配置，删除LogoFile配置
    this.scrollHandler && window.removeEventListener('scroll', this.scrollHandler)
    this.quickSaveKeydown && window.removeEventListener('keydown', this.quickSaveKeydown)
  },
  methods: {
    notUpdateArticle() {
      let keys = Object.keys(this.oldArticle).filter(e => e !== 'extend')
      for (let key of keys) {
        let oldAttr = this.oldArticle[key]
        let attr = this.article[key]
        if (typeof attr === 'object') {
          oldAttr = JSON.stringify(oldAttr)
          attr = JSON.stringify(attr)
        }
        if (attr !== oldAttr) {
          return false
        }
      }
      return true
    },

    quickSave () {
      window.addEventListener('keydown', this.quickSaveKeydown, false)
    },
    // 快速保存（ctrl+s）
    quickSaveKeydown (_e) {
      let e = _e
      if (!_e) {
        e = window.event
      }
      if (e.ctrlKey && e.keyCode === 83){
        e.preventDefault()
        this.saveContent()
      }
    },
    fixedContentDetailToolbar () {
      let scrollWrap = window
      function offset (target) {
        var top = 0
        var left = 0
        while (target.offsetParent) {
          top += target.offsetTop
          left += target.offsetLeft
          target = target.offsetParent
        }
        return { top, left }
      }
      let _contentDetailToolbar = null
      this.scrollHandler = (e) => {
        let _offset = offset(this.$el)
        let _h = this.$el.offsetHeight
        let _top = scrollWrap.scrollY || scrollWrap.scrollTop
        let _diff = _top - _offset.top
        _contentDetailToolbar = _contentDetailToolbar || this.$refs.contentDetailToolbar.$el
        let width = _contentDetailToolbar.clientWidth
        if (_diff > 0 && _diff < _h) {
          _contentDetailToolbar.style.position = 'fixed'
          _contentDetailToolbar.style.top = '0'
          // _contentDetailToolbar.style.width = _contentDetailToolbar.parentElement.offsetWidth + 'px'
          _contentDetailToolbar.style.width = width + 'px'
          _contentDetailToolbar.style.zIndex = '100'
          _contentDetailToolbar.style.margin = '0'
        } else {
          _contentDetailToolbar.style.position = 'relative'
          _contentDetailToolbar.style.top = ''
          _contentDetailToolbar.style.width = ''
          _contentDetailToolbar.style.zIndex = ''
          _contentDetailToolbar.style.margin = ''
        }
      }
      scrollWrap.addEventListener('scroll', this.scrollHandler, false)
    },
    async verifySameTitle () {
      let res = await axios.get('/ui/contentcore/contents/verifysametitle', {
        params: {
          contentID: this.contentID,
          catalogID: this.article.catalogID,
          title: encodeURIComponent(this.article.title)
        }
      })
      if (res.data.status === 1 && res.data.count > 0) {
        this.sameTitleShow = true
        if (res.data.TitleCheckType === 'Catalog') {
          this.sameTitleNotice = '注意：当前栏目下已有相同标题记录'
        }
        if (res.data.TitleCheckType === 'Site') {
          this.sameTitleNotice = '注意：当前站点下已有相同标题记录'
        }
      } else {
        this.sameTitleShow = false
      }
    },
    catalogSelection (catalog) {
      this.article.mainCatalogID = catalog.ID
      this.article.catalogID = catalog.ID
      this.article.catalogName = catalog.name
      this.article.catalogAlias = catalog.alias
      this.$emit('catalog-change', catalog, this.article)
      this.$nextTick(() => {
        this.$refs.contentDetailToolbar.refreshWorkflowButton()
      })
      this.reflushList()
    },
    handleLoaded () {
      if (this.$route.query.format !== 'Markdown') {
        this.$refs['editor'].initEditor()
      }
      this.$emit('loaded')
    },
    changeOptions () {
      if (this.$refs.editor.instance) {
        let options = this.$refs.editor.instance.options
        this.article.logoFile = options.logoFile ? options.logoFile : this.article.logoFile
        this.article.title = options.title ? options.title : this.article.title
        this.article.subTitle = options.subTitle ? options.subTitle : this.article.subTitle
        this.article.shortTitle = options.shortTitle ? options.shortTitle : this.article.shortTitle
        this.article.summary = options.summary ? options.summary : this.article.summary
        this.article.source = options.source ? options.source : this.article.source
        if (options.keyword) {
          let keyword = options.keyword
          if (this.keywords.indexOf(keyword) === -1) {
            this.keywords.push(keyword)
            this.article.keyword = this.keywords.join()
          }
        }
        this.article.author = options.author ? options.author : this.article.author
      }
    },
    /**
     * 初始化内容
     */
    async initContent () {
      // this.$refs['articleForm'].resetFields()
      let attResp = await axios.get('/ui/platform/codes/ContentAttribute')
      if (attResp.data.status === 1) {
        this.contentAttributes = attResp.data.data
      }
      let getCatalogTree = await axios.get('/ui/catalog/admintree', { params: { contentType: this.$route.query.type } })
      this.catalogTree = getCatalogTree.data.data
      this.resourceDialogProps = Object.assign({}, this.resourceDialogProps, { catalogID: this.article.catalogID })
      let catalogConfig = this.article.catalogConfigProps
      if (catalogConfig) {
        if (catalogConfig.articleImageWidth) {
          this.resourceDialogProps.imageWidth = catalogConfig.articleImageWidth
        }
        if (catalogConfig.articleImageHeight) {
          this.resourceDialogProps.imageHeight = catalogConfig.articleImageHeight
        }
        if (catalogConfig.articleLogoWidth) {
          this.resourceDialogProps.logoWidth = catalogConfig.articleLogoWidth
        }
        if (catalogConfig.articleLogoHeight) {
          this.resourceDialogProps.logoHeight = catalogConfig.articleLogoHeight
        }
        if (catalogConfig.articleFileDownloadPath) {
          this.resourceDialogProps.articleFileDownloadPath = catalogConfig.articleFileDownloadPath
        }
      }
      this.initEditorConfig()
      Window.saveContent = this.saveContent
    },
    /**
     * 初始化分页编辑器,分页重构
     */
    initPages (editor) {
      let bodyTextArr = []
      let pageTitleArr = []
      if (this.article.bodyText) {
        bodyTextArr = this.article.bodyText.split(this.PAGE_SPLIT)
        this.article.bodyText = bodyTextArr[0] // 第一个编辑器实例的内容
      }
      if (this.article.pageTitles) {
        pageTitleArr = this.article.pageTitles.split(this.TITLE_SPLIT)
      }
      for (let i = 1; i < bodyTextArr.length; i++) {
        var number = parseInt(Math.random() * 10000)
        let e = ZPageBreak.addPageBlock(editor, number) // 得到分页的编辑器实例
        e.addListener(
          'ready',
          (function (content) {
            // 给编辑器设置分页内容
            return function (type, evt) {
              // reayPageAmount++
              e.setContent(content)
              // ZPageBreak.boolbarSwitch(e, content)
            }
          })(bodyTextArr[i])
        )
        $('#PageTitle_' + number).val(pageTitleArr[i]) // 得到分页的标题
      }
      this.firstPageTitle = pageTitleArr.length > 0 ? pageTitleArr[0] : ''
    },
    // 当侧边栏选中内容时，插入内容到当前UEditor编辑器
    onSideEditorSelected (html) {
      this.editor.undoManger.save()
      this.editor.execCommand('inserthtml', html)
    },
    onSideEditorRendered () {
      this.leftToolPanelLoading = false
    },
    handleReady (editor) {
      this.editor = editor
      this.initEditorData()
      this.sourceModeChangeHandler()
      this.initPages(editor) // 重构分页
      this.initWxEditorPanel() // 如果正文内容存在微信编辑器则初始显示微信编辑器工具栏
    },
    initWxEditorPanel () {
      // let me = this
      if (this.article.bodyText && $('<div>' + this.article.bodyText + '</div>').find('.pEditor').length > 0) {
        this.editor.ready(function () {
          window.setTimeout(function () {
            // me.toggleLeftToolPanel()
          }, 0)
        })
      }
    },
    // 切换源码模式处理
    sourceModeChangeHandler () {

    },
    initEditorConfig () {
      let configs = {
        dataType: this.article.contentType,
        ID: this.article.ID,
        catalogID: this.article.catalogID,
        siteID: this.article.siteID,
        resourceProps: this.resourceDialogProps,
        logoFile: this.article.logoFile,
        imageFieldName: 'file',
        imageUrlPrefix: this.$root.prefix,
        imageActionName: 'uploadimage', // 执行上传图片的action名称，UEditor里要求必须要这个配置
        serverUrl: 'ui/catalogresources/' + this.article.catalogID + '/upload?' + 'siteID=' + this.article.siteID
      }
      this.editorConfig = Object.assign(
        this.editorConfig,
        configs
      )
      if (this.$refs.editor && this.$refs.editor.instance) {
        this.$refs.editor.instance.options = Object.assign(
          this.$refs.editor.instance.options,
          configs
        )
      }
    },
    destroyEditorConfig () {
      let configs = {
        dataType: '',
        ID: '',
        catalogID: '',
        siteID: '',
        resourceProps: {},
        logoFile: ''
      }
      this.editorConfig = Object.assign(
        this.editorConfig,
        configs
      )
      if (this.$refs.editor && this.$refs.editor.instance) {
        this.$refs.editor.instance.options = Object.assign(
          this.$refs.editor.instance.options,
          configs
        )
      }
    },
    initEditorData () {
      // this.$refs.editor.instance.options.dataType = this.article.contentType
      // this.$refs.editor.instance.options.ID = this.article.ID || ''
      // this.$refs.editor.instance.options.catalogID = this.article.catalogID
      // this.$refs.editor.instance.options.siteID = this.article.siteID
      // this.$refs.editor.instance.options.resourceProps = this.resourceDialogProps
      // this.$refs.editor.instance.options.logoFile = this.article.logoFile || ''
    },

    async saveContent () {
      return new Promise(async (resolve, reject) => {
        try {
          await util.validateForm(this.$refs['articleForm'])
        } catch (e) {
          util.showErrorMessageBox(e)
          reject(new Error())
          return
        }
        if (this.isInputUrl && this.article.linkFlag === 'Y') {
          this.article.redirectURL = this.article.cName
        }
        if ((this.article.linkFlag !== 'Y' && !this.article.bodyText) || (this.article.linkFlag === 'Y' && !this.article.redirectURL)) {
          util.showErrorMessageBox('内容不能为空')
          reject(new Error())
          return
        }
        // if(!this.article.catalogID){
        //   util.showErrorMessageBox('所属栏目不能为空！')
        //   reject(new Error())
        //   return
        // }

        // 自动提取摘要
        if (!this.article.summary || this.article.summary.trim() === '') {
          await this.autoSummaryOrKeyword('summary')
        }

        if (this.article.summary) {
          let lengthEx = util.getLengthEx(this.article.summary, true)
          if (lengthEx > 1500) {
            util.showErrorMessageBox('摘要必须小于等于500个汉字或者1500个字母')
            reject(new Error())
            return
          }
        }
        let checkBadFlag = await this.checkBadWord()
        let badwordDealAction = ''
        if (!checkBadFlag) {
          badwordDealAction = await this.showBadwordConfirm()
          if (badwordDealAction === 'cancel') {
            reject(new Error('取消'))
            return
          }
        }
        let _bodyText
        if (this.$route.query.format === 'Markdown') {
          _bodyText = this.article.bodyText
        } else {
          _bodyText = await this.getPageData() // 获取所有分页编辑器内容合并值
        }
        if (localStorage.highlightBadword === 'true' && this.badWords) {
          const badwordsArr = typeof this.badWords === 'string' ? this.badWords.split(' ') : this.badWords
          for (var i = 0; i < badwordsArr.length; i++) {
            var substr = '<span style="background-color:yellow;">' + badwordsArr[i] + '</span>'
            _bodyText = _bodyText.split(substr).join(badwordsArr[i])
          }
        }
        this.article.pageTitles = await this.getPageTitles() // 获得分页标题合并值
        let formData = {}
        let article = JSON.parse(JSON.stringify(this.article))
        article.channelAttribute = article.channelAttribute ? article.channelAttribute.join(',') : ''
        for (let i in article) {
          Vue.set(formData, i, this.formatItem.includes(i) ? article[i] && JSON.stringify(article[i]) : article[i])
        }
        // formData.append('redirectURL', this.article.cName)

        formData = Object.assign(formData, {
          redirectURL: this.isInputUrl ? article.cName : article.redirectURL,
          bodyText: _bodyText
        })

        // 处理敏感词
        if (badwordDealAction === 'save') {
          localStorage.highlightBadword = 'true'
        } else if (badwordDealAction === 'replace') {
          formData.replaceBadWord = 'Y'
          localStorage.highlightBadword = 'false'
        }
        // 处理tag词
        formData.tag = formData.tag.join()
        // 保存格式，如：markdown
        // formData.format = this.$route.query.format
        Vue.set(formData, 'format', this.$route.query.format)
        try {
          // 相关内容单独处理
          delete formData.relativeContent
          // 新建文章时，避免重复保存内容
          if (this.content.addContentID) {
            formData.addContentID = this.content.addContentID
            formData.method = 'ADD'
          }
          formData.publishDate = (this.article.publishDate === 'null' || this.article.publishDate === null) ? '' : this.article.publishDate
          formData.downlineDate = (this.article.downlineDate === 'null' || this.article.downlineDate === null) ? '' : this.article.downlineDate
          let res = article.ID
            ? await axios.put(`/ui/contentcore/contents/${article.ID}`, formData)
            : await axios.post('/ui/contentcore/contents', formData)
          if (!Window.startPublishing) {
            if (Window.saveContentAction === 'autoSave') {
              this.$notify.info({
                title: '',
                message: '自动保存成功',
                position: 'bottom-left',
                showClose: false,
                duration: 1500
              })
            } else {
              util.showResponseMessage(res.data)
            }
          }
          // 刷新父页面
          if (res.data.status !== 1) {
            reject(new Error())
            return
          }
          if (article.channelAttribute.length > 0) {
            let vres = await axios.put(`/ui/mediaaccounts/0/verify/${article.ID ? article.ID : res.data.contentID}`, {
              PCodes: article.channelAttribute
            })
            if (vres.data.status !== 1) {
              util.showErrorMessageBox(vres.data.message)
              reject(new Error())
              return
            }
          }
          let flag = !!article.ID
          if (!flag) {
            Window.articleID = res.data.contentID
            await util.updatePriv()
            this.$router.replace(
              location.hash.replace('#', '').replace('new', res.data.contentID)
            )
            this.contentID = res.data.contentID
          }
          if (!Window.startPublishing) {
            await this.loadContent()
          }
          resolve('success')
        } catch (e) {
          reject(new Error())
        }
      })
    },
    showBadwordConfirm () {
      const badwordConfirmPromise =  new Promise((resolve, reject) => { // eslint-disable-line
        this.badWordDialogShow = true
        this.badwordConfirmPromise = {
          resolve,
          reject
        }
      })
      return badwordConfirmPromise
    },
    badwordConfirmAction (action) {
      this.badWordDialogShow = false
      if (this.badwordConfirmPromise !== null) {
        this.badwordAction = action
        this.badwordConfirmPromise.resolve(action)
      }
    },
    /**
     * 获取所有分页编辑器内容合并值
     */
    getPageData () {
      let c = ''
      try {
        let arr = $('.divPageTitle')
        for (let i = 0; arr.length && i < arr.length; i++) {
          if (i === 0) {
            c = this.article.bodyText
            continue
          }

          let index = arr[i].id.split('_')[1] // 截取分页标题的序号：分页标题的id（divPageTitle_1、divPageTitle_2...）
          let e = UE.getEditor('editor_' + index)
          if (c.length > 0) {
            c += this.PAGE_SPLIT
          }
          if (e) {
            c += e.getContent()
          } else {
            c += 'null'
          }
        }
      } catch (ex) {
        c = this.article.bodyText
      }
      return c
    },
    updateResourceID (val) {
      this.article.resourceID = val
    },
    /**
     * 获得分页标题合并值
     */
    getPageTitles () {
      let c = ''
      try {
        let arr = $('[name=PageTitle]')
        for (let i = 0; arr.length && i < arr.length; i++) {
          if (i > 0) {
            c += this.TITLE_SPLIT
          }
          c += arr[i].value
        }
      } catch (ex) {}
      return c
    },
    contentChange (val) {
      return this.article.bodyText
    },
    closeArticle () {
      window.close()
    },
    tagBrowseClick () {
      this.tagInfo.addTag = true
    },
    sourceCallBack (val) {
      this.article.source = val
      this.sourceFlag = false
    },
    contentAttributeChange (val) {
      this.article.contentAttribute = this.attributes.join()
    },
    contentPlatChange (val) {
      this.article.platformAttribute = this.selectPlatAttributes.join(',')
    },
    setTitleStyle (color) {
      if (typeof this.article.titleStyle === 'object') {
        let val = ''
        for (let i in this.article.titleStyle) {
          val += i + ':' + this.article.titleStyle[i] + ';'
        }
        this.article.titleStyle = val
      }
      if (this.article.titleStyle.indexOf('{"color":"rgba(0, 0, 0, 1)"}') > -1) {
        this.article.titleStyle = ''
      }
      if (color === 'bold') {
        let index = this.article.titleStyle.indexOf('font-weight')
        if (index > -1) {
          this.article.titleStyle = this.article.titleStyle.replace('font-weight:bold;', '')
          return
        }
        this.article.titleStyle += 'font-weight:bold;'
      } else {
        let colorStyle = 'color:' + color + ';'
        let colorIndex = this.article.titleStyle.indexOf(colorStyle)
        if (colorIndex > -1) {
          let part1 = this.article.titleStyle.substring(0, colorIndex)
          let part2 = this.article.titleStyle.substring(colorIndex + colorStyle.length)
          this.article.titleStyle = part1 + part2
        } else {
          let index = this.article.titleStyle.indexOf('color:')
          if (index > -1) {
            let part1 = this.article.titleStyle.substring(0, index)
            let part2 = this.article.titleStyle.substring(index + this.article.titleStyle.substring(index).indexOf(';') + 1)
            this.article.titleStyle = part1 + part2
          }
          this.article.titleStyle += 'color:' + color + ';'
        }
      }
    },
    selectContent () {
      this.isInputUrl = false
      this.contentSelectorDialogModal = true
    },
    selectCatalog (val) {
      this.isInputUrl = false
      this.catalogSelectorDialogModal = true
      if (val) {
        this.isRightCatalog = true
      }
    },
    inputUrl () {
      this.article.cName = 'http://'
      this.isInputUrl = true
    },
    tagCallBack (val) {
      this.article.tag = contentScript.handleTags([], this.article.tag, val)
    },
    contentSelectorCallback (row) {
      if (!row.ID) {
        return
      }
      let typeName = this.contentTypes.find(val => val.value === row.contentTypeID).label
      this.article.cName = (typeName || row.contentTypeID) + '：' + row.title
      this.article.redirectURL = row.link
    },
    catalogSelectorCallback (row) {
      // this.tmpImage.oldname = row.name
      if (this.isRightCatalog) {
        this.isRightCatalog = false
        this.article.catalogID = row.ID
        this.article.catalogName = row.name
        return
      }
      this.article.cName = '栏目：' + row.name
      this.article.redirectURL = row.link
    },
    sourceBrowseClick () {
      this.sourceFlag = true
    },
    contentTypeChange (e) {
      this.isLinkContentFlag = this.article.linkFlag === 'Y'
    },
    changeCopyImage (e) {
      if (e) {
        this.article.copyImageFlag = 'Y'
      } else {
        this.article.copyImageFlag = 'N'
      }
    },
    async setTop (e) {
      if (!e) {
        return
      }
      if (!this.article.ID) {
        let resp = await axios.put(`/ui/contentcore/contents${this.article}`)
        if (resp.data.status !== 1) {
          this.$alert(resp.data.message || '保存失败')
        }
      }
      this.showSetTopFlag = true
    },
    browseTemplate (val) {
      this.selectTemplateDialogFlag = true
      this.platformID = val
      this.templateChoicePath.isShowModal = true
    },
    getTemplatePath (e) {
      this.article.template_pc = e.path
    },
    async autoSummaryOrKeyword (type) {
      if ((this.article.linkFlag !== 'Y' && !this.article.bodyText) || (this.article.linkFlag === 'Y' && !this.article.redirectURL)) {
        util.showError('内容不能为空')
        return
      }
      let resp = await axios.post(`/ui/article/auto/${type}`, {
        format: this.$route.query.format,
        title: this.article.title,
        content: this.article.bodyText,
        linkFlag: this.article.linkFlag
      })
      if (resp.data.status === 1) {
        if (type === 'summary') {
          this.article.summary = resp.data.data
        } else if (type === 'keyword') {
          this.keywords = (resp.data.data ? resp.data.data.split(' ') : []).filter(i => i && i.trim())
          this.article.keyword = this.keywords.join(',')
        }
      }
    },
    async checkBadWord () {
      let resp = await axios.post('/ui/article/checkword', {
        title: this.article.title,
        content: this.article.bodyText,
        shortTitle: this.article.shortTitle,
        subTitle: this.article.subTitle,
        summary: this.article.summary,
        sourceTitle: this.article.sourceTitle
      })
      if (resp.data.status === 0) {
        this.badWords = resp.data.message.split('\t')[1]
      }
      return resp.data.status === 1
    },
    updateBrowsePrivGroups (val) {
      this.article.browsePrivGroups = val
    },
    handleTagClose (tag) {
      this.article.tag.splice(this.article.tag.indexOf(tag), 1)
    },
    showTag () {
      this.tagInfo.addTag = true
      this.$nextTick(_ => {
        this.$refs.tagRefs.$refs.input.focus()
      })
    },
    handleTagConfirm () {
      let inputTag = this.tagInfo.inputTag
      if (inputTag && !this.article.tag.includes(inputTag)) {
        this.article.tag.push(inputTag)
      }
      this.tagInfo.addTag = false
      this.tagInfo.inputTag = ''
    },

    handleWordClose (value) {
      this.keywords.splice(this.keywords.indexOf(value), 1)
      if (this.verifyWord('')) {
        return
      }
      this.article.keyword = this.keywords.join(',')
    },
    showWord () {
      if (this.verifyWord('')) {
        return
      }
      this.wordInfo.addWord = true
      this.$nextTick(_ => {
        this.$refs.wordRefs.$refs.input.focus()
      })
    },
    handleWordConfirm () {
      let inputWord = this.wordInfo.inputWord
      if (this.verifyWord(inputWord)) {
        return
      }
      if (inputWord) {
        this.keywords.push(inputWord)
        this.article.keyword = this.keywords.join(',')
      }
      this.wordInfo.addWord = false
      this.wordInfo.inputWord = ''
    },
    verifyWord (input) {
      let value = this.keywords.join() + input
      this.keywordValidate.error = (util.getLengthEx(value, true) > 200)
      return this.keywordValidate.error
    },
    initWXEditorListener () {
      if (!window.eventHub) {
        window.eventHub = new window.Vue()
      }
      // 定义事件监听
      window.eventHub.$on('wxeditorToggle', (state) => {
        this.showWxEditorFlag = state
        if (state && this.leftToolPanelRender === false) {
          this.leftToolPanelLoading = true
          window.setTimeout(() => {
            this.leftToolPanelRender = true
          }, 450)
        }
      })
    },
    articleLinkFlag(val) {
      this.article.bodyText = ''
    },

    reflushList() {
      window.refreshOpenerContentList && window.refreshOpenerContentList()
    }
  }
}
