<template>
  <div class="layout-row-main" style="display:block" v-loading="deleting">
    <el-toolbar align="right">
      <el-row style="width:100%">
        <el-col :span="6" class="detail-toobar-back">
          <el-button @click="back" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回{{isEdit=='Y'?'列表页':'上页'}}</el-button>
        </el-col>
        <el-col :span="18" class="tar">
          <el-button :loading="saveLoading[0]" class="btn-item-txt-link" @click="doSave(0)"><i class="fa fa-save"></i>保存并返回列表</el-button>
          <el-button :loading="saveLoading[1]" class="btn-item-txt-link" @click="doSave(1)"><i class="fa fa-save"></i>{{isEdit=='Y'?'保存并返回编辑器':'保存并进入编辑器'}}</el-button>
          <template v-if="showOprateBtns">
            <el-button class="btn-item-txt-link" @click="publish('pub')">
              <i class="fa fa-send-o"></i>发布</el-button>
            <el-button @click="preview">
              <i class="fa fa-search"></i>预览</el-button>
            <el-dropdown>
              <span>
                <el-button size="small" class="btn-item-oprate" title="更多">
                  <i class="fa fa-ellipsis-h f16" style="padding-right:0;"></i>
                </el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native.stop="del">
                  <i class="fa fa-remove"></i>删除</el-dropdown-item>
                <el-dropdown-item @click.native.stop="publish('topub')">
                  <i class="fa fa-circle-o-notch"></i>待发布</el-dropdown-item>
                <el-dropdown-item @click.native.stop="publish('offline')">
                  <i class="fa fa-refresh"></i>下线</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-col>
      </el-row>
    </el-toolbar>

    <div class="editor-content detail-content-box" v-if="invalidIDFlag === false">
      <el-form ref="specialForm" :model="special" label-width="110px" label-suffix=":" class="content-form">
        <div class="step2">
          <el-row :gutter="20">
          <el-col :lg="17" :xl="17" class="special-main">
            <div class="panel-card">
              <el-form-item prop="title" label="专题名称" :verify="['NotNull','Length<150']">
                <el-row>
                  <el-col :span="22">
                    <el-input :maxlength="titleMaxLength" @blur="specialTitleBlur" v-model="special.title"></el-input>
                  </el-col>
                  <el-col :span="2">
                    <span style="margin: 6px;" v-text="titleCounter"></span>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
            <div class="panel-card">
              <el-form-item prop="fileName" label="生成文件名" :verify="['NotNull','Length<150','Regex=^[a-zA-Z0-9_-]+$|文件名只能包含英文字母、数字、横线或下划线']">
                <el-row>
                  <el-col :span="22">
                    <el-input v-model="special.fileName"></el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </div>
            <div class="panel-card" v-if="/^\d+$/.test(id) === false">
              <template-selector :template-id.sync="templateId" :selected-id="fromSourceId" @templateTypeChanged="templateTypeChangeHandle"></template-selector>
            </div>
          </el-col>
          <el-col :lg="7" :xl="7">
            <div class="sidebar">
              <el-collapse v-model="activeNames">
                <el-collapse-item title="基本属性" name="1" class="sidebar-item-box">
                  <el-form label-width="80px" label-suffix=":">
                    <el-form-item prop="author" label="作者" :verify="['Length<50']">
                      <el-input v-model="special.author"></el-input>
                    </el-form-item>
                    <el-form-item prop="editor" label="编辑" :verify="['Length<50']">
                      <el-input v-model="special.editor"></el-input>
                    </el-form-item>
                    <el-form-item  label="所属栏目">
                       <el-input disabled v-model="special.catalogName"></el-input>
                         <content-move-button :content-ids="!special.ID?'new':special.ID" :isEditContent="true" :button-name='"切换"' :content-type="special.contentTypeID" :catalog-ids="special.catalogID" @refresh-content="catalogSelection" :size='"mini"' :button-type='"primary"'></content-move-button>
                    </el-form-item>
                    <div class="sidebar-item-box-logo">
                      <logo-path :path.sync="special.logoFile" :preview-path.sync="special.fullLogoFile" :resource-dialog-props="resourceDialogProps" :logo-style.sync="logoStyle" editPosition="right"></logo-path>
                    </div>
                  </el-form>
                </el-collapse-item>
                <el-collapse-item title="扩展属性" name="2" class="sidebar-item-box">
                  <el-form label-width="80px" label-suffix=":">
                    <el-form-item prop="tags" label="Tag词" class="content-attriute">
                      <el-tag
                        v-for="tag in special.tag"
                        :key="tag"
                        closable
                        :disable-transitions="false"
                        @close="handleTagClose(tag)"
                      >
                        <span :title="tag">{{tag | charWidth(10)}}</span>
                      </el-tag>
                      <select-tags :tags.sync="special.tag" :content-type="special.contentTypeID" :show.sync="tagInfo.addTag"></select-tags>
                      <el-button v-show="!tagInfo.addTag" class="button-new-tag tag-select" size="small" @click="tagBrowseClick"><i class="fa fa-plus"></i></el-button>
                    </el-form-item>
                    <el-form-item prop="keyword" label="关键字" class="content-attriute">
                      <el-tag
                        v-for="word in keywords"
                        :key="word"
                        closable
                        :disable-transitions="false"
                        @close="handleWordClose(word)"
                      >
                        <span :title="word">{{word | charWidth(10)}}</span>
                      </el-tag>
                      <el-input
                        class="input-new-tag"
                        v-if="wordInfo.addWord"
                        v-model="wordInfo.inputWord"
                        ref="wordRefs"
                        size="small"
                        @keyup.enter.native="handleWordConfirm"
                        @blur="handleWordConfirm"
                      >
                      </el-input>
                      <el-button v-else class="button-new-tag tag-select" size="small" @click="showWord"><i class="fa fa-plus"></i></el-button><br/>
                    </el-form-item>
                    <el-form-item prop="textarea" label-width="0px">
                      <el-row style="position:relative;">
                        <el-col>
                          <el-input type="textarea" v-model="special.summary" class="form-item" placeholder="摘要" :autosize="{ minRows: 4, maxRows: 8}"></el-input>
                          <span style="position:absolute;bottom:40px;right:6px;color:#999;">{{summaryCounter}}</span>
                        </el-col>
                      </el-row>
                    </el-form-item>
                    <el-form-item label="发布时间" prop="publishDate" class="time_picker_css">
                      <el-date-picker id="publishDatepicker" v-model="special.publishDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择发布时间">{{special.publishDate}}</el-date-picker>
                    </el-form-item>
                    <el-form-item label="下线时间" prop="downlineDate" class="time_picker_css" >
                      <el-date-picker id="downlineDatepicker" v-model="special.downlineDate" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择下线时间">{{special.downlineDate}}}</el-date-picker>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
                <el-collapse-item title="其他属性" name="3" class="sidebar-item-box">
                  <el-form label-width="100px" label-suffix=":">
                    <div>
                      <el-form-item prop="source" label="来源" :verify="['Length<80']" class="source-box">
                        <el-input v-model="special.source">
                          <el-button @click="sourceBrowseClick" slot="append"><i class="fa fa-plus"></i></el-button>
                        </el-input>
                      </el-form-item>
                      <el-form-item prop="sourceURL" label="来源地址" :verify="['Length<150']">
                        <el-input v-model="special.sourceURL" placeholder="http://"></el-input>
                      </el-form-item>
                    </div>

                    <el-form-item prop="weight" label="权重" class="custom-weight editor-slider">
                      <el-slider v-model="special.weight" show-input class="weight-slider"></el-slider>
                    </el-form-item>
                  </el-form>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-col>
        </el-row>
        </div>
      </el-form>
    </div>
    <select-sources-dialog :word-flag.sync="sourceFlag" :content-type="special.contentTypeID" type="source" title="选择来源" @wordCallBack="sourceCallBack"></select-sources-dialog>
  </div>
</template>
<script>

import util from '@src/common/util.js'
import _ from 'lodash'
import TemplateSelector from './components/templateSelector.vue'
import LogoPath from '../contentcore/components/LogoPath.vue'
import TreeSelect from '@src/components/TreeSelect.vue'
import selectTags from '@src/components/contentComponent/selectTags.vue'
import selectWordsDialog from '../wordmanage/components/WordPicker.vue'
import contentMoveButton from '../contentcore/components/ContentMoveButton.vue'
import './special.css'
export default {
  components: {
    'logo-path': LogoPath,
    TemplateSelector,
    TreeSelect,
    'select-tags': selectTags,
    'select-sources-dialog': selectWordsDialog,
    'content-move-button': contentMoveButton
  },
  props: {
    catalogid: {
      require: true,
      type: [Number, String]
    },
    id: {
      require: true,
      type: [Number, String]
    }
  },
  data() {
    let url = location.href
    let catalogID = this.catalogid
    return {
      platformAttributes: this.$root.platformAttributes,
      showOprateBtns: /^\d+$/.test(this.id),
      invalidIDFlag: this.id !== 'new' && /^\d+$/.test(this.id) === false,
      titleMaxLength: 50,
      summaryMaxLength: 250,
      activeNames: ['1', '2', '3'],
      baseInfo: false,
      tagInfo: {
        addTag: false,
        inputTag: '',
        hasSelect: false
      },
      wordInfo: {
        addWord: false,
        inputWord: ''
      },
      logoStyle: '',
      selectCatalogFlag: false,
      templateType: 'Y', // 模板类型 Y为根据模板创建，N为根据空白模板创建
      templateId: '', // 最终用户选择并提交到后端的模板ID
      fromSourceId: util.url.getQueryValue(url, 'sourceID'), // 从模板预览界面过来的选中的模板ID
      isEdit: util.url.getQueryValue(url, 'isEdit'), // 从模板预览界面过来的选中的模板ID
      special: {
        contentTypeID: 'Special',
        publishUrl: '',
        platformAttribute: [],
        keyword: '',
        fileName: '',
        catalogID: catalogID,
        catalogName: '',
        author: localStorage.realName || localStorage.userName,
        editor: localStorage.realName || localStorage.userName,
        title: '',
        source: '',
        sourceURL: '',
        weight: 10,
        summary: '',
        downlineDate: '',
        publishDate: '',
        logoFile: '',
        sourceID: '',
        templateId: '',
        tag: [],
        ID: null
      },
      customLayout: {},
      keywords: [],
      deleting: false,
      resourceDialogProps: {},
      saveLoading: [false, false],
      sourceFlag: false
    }
  },
  computed: {
    specialID() {
      if (/^\d+$/.test(this.id)) {
        return Number(this.id)
      } else {
        return null
      }
    },
    catalogID() {
      if (/^\d+$/.test(this.catalogid)) {
        return Number(this.catalogid)
      } else {
        return null
      }
    },
    summaryCounter() {
      return this.special.summary ? this.special.summary.length : 0
    },
    titleCounter() {
      return (this.special.title ? this.special.title.length : 0) + '/' + this.titleMaxLength
    },
    tags: {
      set (val) {
        this.special.tag = val
        this.special = Object.assign({}, this.special, { tag: val ? val.split(',') : [] })
      },
      get () {
        let initContent = Object.assign({}, this.special, { tags: this.special.tag ? this.special.tag.join(',') : '' })
        return initContent.tag ? initContent.tag.join(',') : ''
      }
    }
  },
  created() {
    this.init()
    this.resourceDialogProps = {
      selectorURL: 'imageResources',
      resourceType: 'image',
      allowType: '.jpg,.jpeg,.png,gif,.bmp',
      imageHeight: 260,
      imageWidth: 260,
      catalogID: this.catalogid,
      url: ''
    }
  },
  methods: {
    preview() {
      window.open(`./ui/special/preview/${this.id}/content`)
    },
    async init() {
      if (this.invalidIDFlag) {
        util.showError('参数不正确!')
        return
      }

      if (this.specialID !== null) {
        // 编辑专题逻辑
        let ajaxData = await axios.get(`/ui/contentcore/contents/${this.specialID}`)
        let data = ajaxData.data
        if (data.status === 1) {
          this.special = data.data
          this.keywords = this.special.keyword ? this.special.keyword.split(',') : []
        }
      } else {
        // 新建专题逻辑
        let catalogAjaxData = await axios.get(`/ui/catalogs/${this.catalogID}`)
        if (catalogAjaxData.data.status === 1) {
          this.special.catalogName = catalogAjaxData.data.data.name
        }
        // 新建专题时默认选中pc发布平台
        if (
          _.filter(this.$root.platformAttributes, function(item) {
            return _.includes(item, 'pc')
          }).length > 0
        ) {
          this.special.platformAttribute = ['pc']
        }
        this.special.catalogID = this.catalogID
      }

      let dimInfo = Object.assign(
        {},
        {
          enable: true,
          catalogId: this.special.catalogID,
          contentId: this.special.ID,
          contentType: this.special.contentTypeID,
          dimensonID: this.special.dimensionID
        }
      )
      Vue.set(this.special, 'dimInfo', dimInfo)
    },
    templateTypeChangeHandle(val) {
      this.templateType = val
    },
    catalogSelection (catalog) {
      if (catalog['contentType'] !== 'Special' && catalog['contentType'] !== '') {
        this.special.catalogID = this.catalogID
        util.showErrorMessageBox('只能选择内容类型为专题或为空的栏目')
      } else {
        this.special.catalogID = catalog.ID
        this.special.catalogName = catalog.name
        let path = `/special/${catalog.ID}/${this.special.ID ? this.special.ID : 'new'}`
        if (!$.isEmptyObject(this.$route.query)) {
          path = util.url.addParams(path, this.$route.query)
        }
        this.$router.replace(path)
      }
    },
    async publish(type) {
      let resp = await axios.put(`/ui/contentcore/contentpublish/${this.id}/${type}`)
      util.showResponseMessage(resp.data)
    },
    async doSave(method) {
      // method:0->保存并返回上一页;1->保存并进入编辑器
      this.saveLoading[method] = true
      try {
        await util.validateForm(this.$refs.specialForm)
        let fileName = this.special.fileName
        if (fileName.startsWith('index') || fileName.startsWith('list')) {
          this.saveLoading[method] = false
          return util.showErrorNotification('生成文件名不能以index或list开头')
        }
        if (this.id === 'new' && this.templateId === '' && this.templateType === 'Y') {
          return util.showErrorNotification('请选择专题模板或使用空白模板')
        }
        const pickObj = {}
        for (let field in this.special) {
          let val = this.special[field]
          if (
            (_.isNumber(val) || !_.isEmpty(val)) &&
            _.includes(
              [
                'ID',
                'title',
                'fileName',
                'author',
                'catalogID',
                'catalogInnerCode',
                'contentTypeID',
                'downlineDate',
                'editor',
                'keyword',
                'logoFile',
                'orderFlag',
                'platformAttribute',
                'priority',
                'publishDate',
                'source',
                'sourceTitle',
                'sourceURL',
                'staticFileName',
                'summary',
                'tag',
                'titleStyle',
                'topDate',
                'topCatalog',
                'topFlag',
                'weight',
                'version'
              ],
              field
            )
          ) {
            pickObj[field] = val
          }
        }
        this.special = pickObj
        if (!this.special.catalogID) {
          this.special.catalogID = this.catalogid
        }
        this.special.contentTypeID = 'Special'
        this.special.version = 3
        if (this.specialID === null && !_.isEmpty(this.templateId)) {
          this.special.sourceID = this.templateId
        }
        const resp = this.specialID
          ? await axios.put(`/ui/specialv3/${this.specialID}`, this.special)
          : await axios.post('/ui/specialv3', this.special)
        const resData = resp.data
        if (resData.status === 1) {
          if (method === 1) {
            util.showSuccess(`保存成功，即将为您跳转到专题编辑界面`)
            let specialID = this.specialID === null ? resData.pageID : this.specialID
            setTimeout(() => {
              let fromStr = this.id === 'new' ? '&from=new' : ''
              window.open(`specialDesigner.html?ID=${specialID}${fromStr}`)
              this.back()
            }, 2000)
          } else if (method === 0) {
            util.showSuccess(`保存成功，即将返回列表页`)
            setTimeout(() => {
              this.back()
            }, 1000)
          } else {
            util.showSuccess(`保存成功`)
          }
        } else {
          this.saveLoading = [false, false]
          util.showErrorMessageBox(resData.message)
        }
      } catch (e) {
        util.showErrorMessageBox(e)
        this.saveLoading = [false, false]
      }
    },
    specialTitleBlur() {
      if (_.isEmpty(this.special.fileName) && this.special.title !== '') {
        this.special.fileName = window.util.getSpell(this.special.title, true)
      }
    },
    back() {
      if (this.isEdit === 'Y') {
        this.$router.replace('/editorWorkspace/Default')
      } else {
        this.$router.back()
      }
    },
    async del() {
      try {
        await this.$confirm('确定要删除该专题吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.deleting = true
        let resp = await axios.delete(`/ui/contentcore/contents/${this.id}?catalogID=${this.catalogID}`)
        util.showResponseMessage(resp.data)
        this.deleting = false
        if (resp.data.status === 1) {
          // this.$router.back()
          this.$router.replace({path: '/editorWorkspace/'})
        }
      } catch (e) {
        return null
      }
    },
    tagBrowseClick () {
      this.tagInfo.addTag = true
    },
    contentAttributeChange (val) {
      this.special.contentAttribute = this.attributes.join()
    },
    handleTagClose (tag) {
      this.special.tag.splice(this.special.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.special.tag.includes(inputTag)) {
        this.special.tag.push(inputTag)
      }
      this.tagInfo.addTag = false
      this.tagInfo.inputTag = ''
    },

    handleWordClose (value) {
      this.keywords.splice(this.keywords.indexOf(value), 1)
      this.special.keyword = this.keywords.join(',')
    },
    showWord () {
      this.wordInfo.addWord = true
      this.$nextTick(_ => {
        this.$refs.wordRefs.$refs.input.focus()
      })
    },
    handleWordConfirm () {
      let inputWord = this.wordInfo.inputWord
      if (inputWord) {
        this.keywords.push(inputWord)
        this.special.keyword = this.keywords.join(',')
      }
      this.wordInfo.addWord = false
      this.wordInfo.inputWord = ''
    },
    sourceBrowseClick () {
      this.sourceFlag = true
    },
    sourceCallBack (val) {
      this.special.source = val
      this.sourceFlag = false
    }
  }
}
</script>
<style scoped>
.el-tag {
  margin-right: 10px;
}
.tag-select{
  margin-left: 0;
}
.detail-toobar-back {
  line-height: 40px;
}
.layout-row-main {
  min-height: calc(100vh - 152px);
}
</style>
<style>
.custom-weight .el-slider__runway.show-input {
  margin-right: 120px;
}

.custom-weight .el-input-number.el-slider__input.el-input-number--small {
  width: 105px;
}

.content-platform-attribute .el-checkbox + .el-checkbox {
  margin-left: 3px;
}
.special-main .el-form-item {
  margin-bottom: 0;
}

.el-input-number--small .el-input-number__decrease,
.el-input-number--small .el-input-number__increase {
  line-height: 30px;
}
</style>
