<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="$router.back()" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" class="el-button el-button--default save" :priv="ID === 'new' ? 'Search.WeightsConfig.AddQueryPositionConfig':'Search.WeightsConfig.EditQueryPositionConfig'" :loading="btnLoading" @click="saveData"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
    <div class="detail-panel form-panel" v-loading="dataLoading">
      <el-form :model="currentFormData" ref="editCustomWeightsForm" label-width="128px">
        <input type="hidden" id="ID" name="ID" v-model="currentFormData.ID" />
        <input type="hidden" id="dataDBID" name="dataDBID" v-model="currentFormData.dataDBID" />
        <el-form-item label="检索词：" prop="query" :verify="['NotNull','Length<60']">
          <el-input v-model="currentFormData.query"></el-input>
        </el-form-item>
        <el-form-item label="内容类型" v-show="false">
          <el-input v-model="currentFormData.contentType"></el-input>
        </el-form-item>
        <el-form-item label="标题：" prop="title" :verify="['NotNull']">
          <el-row type="flex" class="row-bg" justify="space-between" :gutter="10">
            <el-col :span="21">
              <el-popover placement="bottom-start" :disabled="!currentFormData.title" title="" trigger="hover" @show="loadArticleData">
                <div v-loading="popoverLoading">
                  <div class="content-tip">
                    <span>ID: </span>{{chooseContentData.ID}}
                  </div>
                  <div class="content-tip">
                    <span>文章标题: </span>{{chooseContentData.title}}
                  </div>
                  <div class="content-tip">
                    <span>内容类型: </span>{{chooseContentData.contentTypeName}}
                  </div>
                  <div class="content-tip">
                    <span>所属栏目: </span>{{chooseContentData.catalogName}}
                  </div>
                </div>
                <el-input slot="reference" v-model="currentFormData.title" disabled></el-input>
              </el-popover>
            </el-col>
            <el-col :span="3" class="right">
              <el-button-group class="group">
                <el-button type="primary" icon="edit" @click='editArticle' :disabled="!currentFormData.dataDBID" title="编辑文章"></el-button>
                <el-button class="through-btn" @click="contentSelectorModal = true">选择</el-button>
              </el-button-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="位置下标：" prop="position" :verify="['NotNull','Int']">
          <el-input v-model="currentFormData.position" placeholder="0或负数将不影响检索结果"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!--选择内容Dialog组件-->
    <content-selector :show.sync="contentSelectorModal" @callback="setChooseContent"></content-selector>

  </div>
</template>

<script>
import util from '@src/common/util.js'
import contentSelector from '@src/components/contentComponent/ContentSelector.vue'

export default {
  components: {
    contentSelector
  },
  props: {
    ID: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      inputParams: {
        type: '',
        formData: {}
      },
      dataLoading: false,
      popoverLoading: false,
      btnLoading: false,
      currentFormData: {
        ID: null,
        dataDBID: null,
        query: '',
        contentType: '',
        title: '',
        position: ''
      }, // 当前Docs检索位置配置临时数据
      emptyFormData: {},
      chooseContentData: {},
      contentSelectorModal: false
    }
  },
  watch: {
    ID: 'init'
  },
  methods: {
    async loadArticleData() {
      if (!!this.chooseContentData.ID && this.chooseContentData.ID === this.currentFormData.dataDBID) {
        return
      }
      this.popoverLoading = true
      let params = {
        ID: this.currentFormData.dataDBID,
        contentType: this.currentFormData.contentType
      }
      let res = await axios.get('/ui/article/datas', { params })
      res = res.data
      if (res.status === 1) {
        Object.assign(this.chooseContentData, res.data)
        this.popoverLoading = false
      }
    },
    async editArticle() {
      if (this.chooseContentData.ID !== this.currentFormData.dataDBID) {
        await this.loadArticleData()
      }

      let path = ''
      if (this.chooseContentData.contentTypeID === 'Special') {
        path = `/special/${this.chooseContentData.catalogID}/${this.chooseContentData.ID}`
        this.$router.push(path)
      } else {
        path = `/contentEditor/${this.chooseContentData.ID}?type=${this.chooseContentData.contentTypeID}&cid=${
          this.chooseContentData.catalogID
        }`
        window.open('contentEditor.html#' + path)
      }
    },

    init() {
      if (!this.ID || this.ID === 'new') {
        this.clearFormData()
      } else {
        this.loadData()
      }
    },

    async loadData() {
      this.dataLoading = true
      try {
        let res = await axios.get(`/ui/docsquerypositionconfig/${this.ID}`)
        res = res.data
        res.status === 1 && Object.assign(this.currentFormData, res.data)
        this.loadArticleData()
      } catch (e) {}
      this.dataLoading = false
    },

    clearFormData() {
      Object.assign(this.currentFormData, this.emptyFormData)
    },

    setChooseContent(data) {
      if (!util.isEmptyObject(data)) {
        this.currentFormData['dataDBID'] = data.ID
        this.currentFormData['contentType'] = data.contentTypeID
        this.currentFormData['title'] = data.title

        this.chooseContentData.contentTypeName = data.contentTypeIDName
        this.chooseContentData.catalogName = data.name
        Object.assign(this.chooseContentData, data)
      }
    },

    validatePosition() {
      let position = this.currentFormData.position
      if (!position) {
        this.$alert('请输入位置下标 ！')
        return false
      }
      if (!/^-?\d+$/.test(position)) {
        this.$alert('位置下标必须为整数 ！')
        return false
      }

      position = position - 0
      if (!Number.isSafeInteger(position)) {
        this.Dialog(`位置下标范围超出安全数值范围(${Number.MIN_SAFE_INTEGER} - ${Number.MAX_SAFE_INTEGER}) ！`)
        return false
      }
      return true
    },

    // 保存Docs检索位置配置事件
    async saveData() {
      try {
        await util.validateForm(this.$refs['editCustomWeightsForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }

      if (this.validatePosition() === false) {
        return
      }

      this.confirmLoading = true
      let res
      if (!this.ID || this.ID === 'new') {
        res = await axios.post('/ui/docsquerypositionconfig', this.currentFormData)
      } else {
        if (!this.currentFormData.ID) {
          this.MsgPop('传入id错误 ！', 'error')
          this.confirmLoading = false
          return
        }
        res = await axios.put(`/ui/docsquerypositionconfig/${this.currentFormData.ID}`, this.currentFormData)
      }

      this.confirmLoading = false
      if (!res) {
        this.MsgPop('请求错误', 'error')
        return
      }
      let data = res.data
      if (data.status === 1) {
        util.showResponseMessage(data)
        this.$emit('success')
      } else {
        this.Dialog(data.message)
      }
    },

    // 消息Dialog封装
    Dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },

    // 消息显示封装
    MsgPop(msg, type) {
      if (!type) {
        this.$message(msg)
        return
      }
      this.$message({
        message: msg,
        type: type
      })
    }
  },
  created() {
    Object.assign(this.emptyFormData, this.currentFormData)
    this.init()
  }
}
</script>
