<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 './special.css'
export default {
  components: {
    LogoPath,
    TemplateSelector,
    TreeSelect
  },
  props: {
    id: {
      require: true,
      type: [Number, String]
    }
  },
  data() {
    let url = location.href
    return {
      dataLoading: false,
      exporting: false,
      styleDatas: [],
      subjectDatas: [],
      platformAttributes: this.$root.platformAttributes,
      invalidIDFlag: this.id !== 'new' && /^\d+$/.test(this.id) === false,
      stepActive: this.id === 'new' ? 0 : 1,
      titleMaxLength: 50,
      otherOptionsFlag: false,
      activeNames: ['basic', 'others'],
      selectCatalogFlag: false,
      templateType: 'Y', // 模板类型 Y为根据模板创建，N为根据空白模板创建
      selectTemplateId: '', // 最终用户选择并提交到后端的模板ID
      fromSourceId: util.url.getQueryValue(url, 'sourceID'), // 从模板预览界面过来的选中的模板ID
      resourceDialogProps: {
        selectorURL: 'imageResources',
        resourceType: 'image',
        allowType: '.jpg,.jpeg,.png,gif,.bmp',
        height: 200,
        width: 200,
        url: ''
      },
      template: {
        publishUrl: '',
        platformAttribute: [],
        keyword: '',
        fileName: '',
        author: '',
        editor: '',
        title: '',
        source: '',
        sourceURL: '',
        weight: 10,
        summary: '',
        downlineDate: '',
        publishDate: '',
        logoFile: '',
        sourceID: '',
        templateId: '',
        ID: null
      },
      keywords: '',
      saveLoading: [false, false]
    }
  },
  computed: {
    templateId() {
      if (/^\d+$/.test(this.id)) {
        return this.id
      } else {
        return null
      }
    },
    summaryCounter() {
      return this.template.summary ? this.template.summary.length : 0
    },
    titleCounter() {
      return (this.template.title ? this.template.title.length : 0) + '/' + this.titleMaxLength
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      if (this.invalidIDFlag) {
        util.showError('参数不正确!')
        return
      }
      this.dataLoading = true
      // 获取模板分类、模板风格数据
      let ajaxRes = await axios.get('/ui/pageweaver/forminit')
      if (ajaxRes.data.status === 1) {
        const ajaxData = ajaxRes.data.data
        this.styleDatas = ajaxData.styles
        this.subjectDatas = ajaxData.subjects
        this.resourceDialogProps.siteID = ajaxData.siteID
        this.resourceDialogProps.catalogID = ajaxData.catalogID
        this.template.siteID = ajaxData.siteID
        this.template.catalogID = ajaxData.catalogID
      }

      // 获取模板数据
      if (this.templateId !== null) {
        let ajaxData = await axios.get(`/ui/pageweaver/template/${this.templateId}`)
        let data = ajaxData.data
        if (data.status === 1) {
          this.template = data.data
          this.keywords = this.template.keywords
          this.template.styleID = '' + this.template.styleID
        }
      }
      this.dataLoading = false
    },
    templateTypeChangeHandle(val) {
      this.templateType = val
    },
    async doSave(method) {
      // method:0->保存并返回上一页;1->保存并进入编辑器
      this.saveLoading[method] = true
      this.$refs.specialForm.validate(async valid => {
        if (valid) {
          let includedFields = ['ID', 'title', 'styleID', 'subjectID', 'keywords', 'logoFile', 'summary']
          if (this.templateId === null) {
            includedFields.push('sourceID')
          }
          const pickObj = {}
          for (let field in this.template) {
            let val = this.template[field]
            if ((_.isNumber(val) || !_.isEmpty(val)) && _.includes(includedFields, field)) {
              pickObj[field] = val
            }
          }
          this.template = pickObj
          if (this.templateId === null && !_.isEmpty(this.selectTemplateId)) {
            this.template.sourceID = this.selectTemplateId
          }
          const resp = this.templateId
            ? await axios.put(`/ui/pageweaver/template/${this.templateId}`, this.template)
            : await axios.post('/ui/pageweaver/template', this.template)
          const resData = resp.data
          if (resData.status === 1) {
            this.stepActive++
            if (method === 1) {
              util.showSuccess(`保存成功，即将为您跳转到专题模板编辑界面`)
              let templateId = this.templateId === null ? resData.data : this.templateId
              setTimeout(() => {
                let fromStr = this.id === 'new' ? '&from=new' : ''
                window.open(`specialDesigner.html?ID=${templateId}${fromStr}`)
              }, 2000)
            } else if (method === 0) {
              util.showSuccess(`保存成功，即将返回上页`)
              setTimeout(() => {
                // this.$router.back()
                this.back()
              }, 1000)
            } else {
              util.showSuccess(`保存成功`)
            }
          } else {
            this.saveLoading = [false, false]
          }
        } else {
          this.saveLoading[method] = false
        }
      })
    },
    specialTitleBlur() {
      if (_.isEmpty(this.template.fileName) && this.template.title !== '') {
        this.template.fileName = window.util.getSpell(this.template.title, true)
      }
    },
    back() {
      // this.$router.replace({path: "/settings/specialTemplate" })
      this.$router.back()
    },
    keywordsChange(val) {
      this.template.keywords = val
    },
    async exportTemplate() {
      this.exporting = true
      let resp = await axios.get(`/ui/pageweaver/template/${this.templateId}/export`)
      this.exporting = false
      if (resp.data.data) {
        window.location.href = `./ui/pageweaver/template/${this.templateId}/download?fileName=${resp.data.data}`
      } else {
        util.showResponseMessage(resp.data)
      }
    }
  }
}
</script>
<template>
  <div class="layout-no-cols">
    <el-toolbar class="toolbar">
      <el-row class="toolbar-row">
        <el-col :span="4">
          <el-button @click="back" type="primary" size="medium" round class="shadow-primary">
            <i class="fa fa-chevron-left"></i> 返回上页</el-button>
        </el-col>
        <el-col :span="20" class="tar toolbar-btns">
          <template v-if="stepActive >= 1">
            <el-button type="text" :loading="saveLoading[0]" class="btn-item-txt-link" round @click="doSave(0)"><i class="fa fa-save"></i>保存并返回列表</el-button>
            <el-button type="text" :loading="saveLoading[1]" class="btn-item-txt-link" round @click="doSave(1)"><i class="fa fa-save"></i>保存并进入编辑器</el-button>
          </template>
          <template v-if="invalidIDFlag===false && id !== 'new'">
            <el-button type="text" :disabled="id==='new'" class="btn-item-txt-link">
              <a :href="`./ui/special/preview/${this.templateId}/content`" style="color:inherit" target="_blank"><i class="fa fa-search"></i> 预览</a></el-button>
            <el-button type="text" :loading="exporting" :disabled="id==='new'" @click="exportTemplate">
              <i class="fa fa-download"></i>导出</el-button>
          </template>
        </el-col>
      </el-row>
    </el-toolbar>
    <div class="layout-row-main-content" v-if="invalidIDFlag === false">
      <el-form ref="specialForm" :model="template" label-width="110px" label-suffix=":" v-loading="dataLoading" class="content-form">
        <el-steps :active="stepActive" simple finish-status="success" v-show="id === 'new'">
          <el-step title="选择模板" icon="el-icon-menu"></el-step>
          <el-step title="填写模板内容" icon="el-icon-edit"></el-step>
          <el-step title="完成" icon="el-icon-success"></el-step>
        </el-steps>
        <div class="step1" v-show="stepActive === 0 && id === 'new'">
          <div class="panel-card" v-if="/^\d+$/.test(id) === false">
            <template-selector :template-id.sync="selectTemplateId" :selected-id="fromSourceId" @templateTypeChanged="templateTypeChangeHandle"></template-selector>
          </div>
          <div class="bottom-buttons">
            <el-button type="primary" size="medium" :disabled="selectTemplateId === '' && templateType === 'Y'" round @click="stepActive++" class="shadow-primary">下一步</el-button>
          </div>
        </div>
        <div class="step2" v-show="stepActive !== 0">
          <el-row>
            <el-col :span="24" class="template-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="template.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-row>
                  <el-col :span="11">
                    <el-form-item prop="subjectID" label="模板分类" :verify="['NotNull|请选择模板分类']">
                      <tree-select class="subject-selector" width="100%" top :value.sync="template.subjectID" :items="subjectDatas" placeholder="请选择"></tree-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item prop="styleID" label="模板风格" :verify="['NotNull|请选择模板风格']">
                      <el-select style="width:100%" v-model="template.styleID" placeholder="请选择">
                        <el-option v-for="item in styleDatas" :key="item.ID" :label="item.name" :value="item.ID">{{item.name}}</el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
              <div class="panel-card">
                <el-form-item prop="keywords" label="关键词">
                  <el-row>
                    <el-col :span="22">
                      <el-input-tags :tags="keywords" @change="keywordsChange" :limit="10"></el-input-tags>
                    </el-col>
                  </el-row>
                </el-form-item>
              </div>
              <div class="panel-card">
                <el-form-item prop="summary" label="摘要">
                  <el-row>
                    <el-col :span="22">
                      <el-input v-model="template.summary" type="textarea"></el-input>
                    </el-col>
                  </el-row>
                </el-form-item>
              </div>
              <div class="panel-card">
                <el-form-item prop="logoFile" label="Logo图片">
                  <logo-path :path.sync="template.logoFile" :resource-dialog-props="resourceDialogProps"></logo-path>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </div>

      </el-form>
    </div>
  </div>
</template>
<style scoped>
.layout-row-main {
  min-height: calc(100vh - 152px);
}

.toolbar-row {
  width: 100%;
}

.toolbar-btns {
  font-size: 12px;
}

.time_picker_css {
  width: 100%;
}

.other-options-div {
  height: 36px;
  margin: 15px;
  position: relative;
  text-align: center;
}

.other-options-div:before {
  content: '';
  width: 100%;
  height: 1px;
  background: #d7d7d7;
  top: 17px;
  left: 0;
  position: absolute;
}

.other-options-div .btn-adv {
  height: 36px;
  width: 120px;
  text-align: center;
  left: 50%;
  margin-left: -60px;
  background: #f7f8fa;
  position: absolute;
}

.bottom-buttons {
  text-align: center;
  margin-bottom: 20px;
}
</style>
<style>
.content-platform-attribute .el-checkbox + .el-checkbox {
  margin-left: 3px;
}

.template-main .el-form-item {
  margin-bottom: 0;
}

.time_picker_css.el-input--prefix .el-input__inner {
  padding-left: 25px;
  padding-right: 20px;
  font-size: 12px;
  color: #28b06e;
}

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