<template>
  <el-container class="editor-box" >
    <div class="paper-editor" v-show="currentEditor==='questionEditor'">
       <el-header>
        <h1 class="paper-title">
          {{surveyData.title || ''}}
          <span class="paper-version">{{surveyData.version || ''}}</span>
        </h1>
        </el-header>
        <el-main class="paper-main">
            <el-tabs type="card"
            id="pages-tabs-id"
            v-model="activePageName"
            :addable="isEdit"
            @tab-add="addPage"
            @tab-remove="removePage"
            >
              <el-tab-pane v-for="(pageItem, pIndex) in pages"
              :name="`${pageItem.name}_${pIndex}`"
              :key="pageItem.name" :closable="closable">
                  <span slot="label">{{$t('editor.selectPage', {'0': pIndex+1, '1': pageTitle(pageItem)})}}</span>
                  <template v-if="pIndex===pageIndex">
                        <PageBasic :pIndex="pIndex" :pageItem="pageItem"></PageBasic>
                        <div class="page-body">
                            <p v-if="currentList.length === 0" class="operate-prompt">{{ $t('editor.operatePrompt') }}</p>
                            <draggable class="editor-draggable" v-model="currentList" :options="dragOptions" @end="dragEnd" @add="addQuestion">
                              <div v-for="(item, qIndex) in currentList" :class="[`quetion-item-${qIndex}`]"  :key="item.name" class="question-item">
                                <QuestionRouter v-if=" !isEdit || questionIndex!==qIndex" @edit="startEdit"  :index="qIndex" :pIndex="pIndex" :question="item" ></QuestionRouter>
                                <EditorRouter  v-else ref="editorRouter"  :oldQuestion="item"  />
                              </div>
                            </draggable>
                        </div>
                  </template>
              </el-tab-pane>
            </el-tabs>
        </el-main>
    </div>
    <div class="template-editor" v-show="currentEditor==='homePage'">
      <PageTemplateEditor pageType="homePage" :show="otherSetting.showHome" :pageContent="otherSetting.homePage"  @change="changeContent"></PageTemplateEditor>
    </div>
    <div class="template-editor" v-show="currentEditor==='endPage'">
      <PageTemplateEditor pageType="endPage" :show="otherSetting.showEnd" :pageContent="otherSetting.endPage" @change="changeContent"></PageTemplateEditor>
    </div>
  </el-container>
</template>

<script>
import draggable from 'vuedraggable'
import QuestionRouter from '../question/QuestionRouter'
import EditorRouter from '../editor/EditorRouter'
import PageBasic from './PageBasic'
import { mapGetters, mapMutations, mapActions } from 'vuex'
import Sortable from 'sortablejs'
import { setGotos, resetVisibleIfFromTriggers, removeTriggers } from '../../utils/utils'
import PageTemplateEditor from '../PageTemplateEditor'

export default {
  name: 'EditorBox',
  props: ['surveyModel', 'surveyConfig', 'disabled', 'showQuestionNumbers'],
  beforeMount: function () {
    this.$store.commit('setCurrentEditor', 'questionEditor')
    this.updateSurveyData()
  },
  components: {
    draggable,
    QuestionRouter,
    EditorRouter,
    PageBasic,
    PageTemplateEditor
  },
  data () {
    return {
      questionList: []
    }
  },
  computed: {
    ...mapGetters(['questionIndex', 'surveyData', 'pageLastIndex', 'pageIndex',
      'isEdit', 'currentEditor', 'otherSetting']),
    pages: function () {
      return this.surveyData.pages || []
    },
    closable: function () {
      return this.pages.length > 1 && this.isEdit
    },
    currentPage: function () {
      return this.pages[this.pageIndex] || {}
    },
    activePageName: {
      get: function () {
        return `${this.currentPage.name}_${this.pageIndex}`
      },
      set: function (val) {
        const nameArr = val.split('_')
        this.setPageIndex(+nameArr[1])
      }
    },
    currentList: {
      get: function () {
        return this.currentPage.elements || []
      },
      set: function (value) {
        this.updateDraggableList(value)
      }
    },
    dragOptions: function () {
      let disabled = true

      if (this.isEdit) {
        disabled = false
      }
      // 如果有题目在编辑状态 禁止拖拽
      if(this.questionIndex !== null){
        disabled = true
      }
      return {
        disabled: disabled,
        animation: 100,
        group: 'creator',
        ghostClass: 'ghost'
      }
    }
  },
  methods: {
    ...mapMutations(['updateDraggableList',
      'addPage', 'setPageIndex', 'saveSurvey','setShowQuestionNumbers',
      'setQuestionIndex', 'setQuestion', 'setPageHome', 'setSurveyEdit']),
    ...mapActions(['movePage']),
    dragEnd (event) {
      resetVisibleIfFromTriggers(this)
      this.saveSurvey()
    },
    updateSurveyData () {
      if(this.surveyModel){
          this.$store.commit('setSurvey', this.surveyModel)
      }
      if (this.surveyConfig) {
        this.$store.commit('setConfig', this.surveyConfig)
      }
    },
    changeContent ({ type, content }) {
      this.setPageHome({ type, content })
    },
    //  当添加新问题，复制上一个问题的 skip visible 属性
    addQuestion ({ newIndex }) {
      const elements = this.pages[this.pageIndex].elements || []
      const question = elements[newIndex]
      let gotoVisibleIfArr = []
      let prevQuestion = {}
      if (newIndex > 0) {
        prevQuestion = elements[newIndex - 1]
        gotoVisibleIfArr = prevQuestion.gotoVisibleIfArr || []
        question.gotoVisibleIfArr = gotoVisibleIfArr
      } else if (this.pageIndex > 0) {
        const prevPage = this.pages[this.pageIndex - 1]
        const prevElements = prevPage.elements || []
        prevQuestion = prevElements[prevElements.length - 1] || {}
        gotoVisibleIfArr = prevQuestion.gotoVisibleIfArr || []
      }
      const prevGotos = prevQuestion.gotos || []
      if (gotoVisibleIfArr.length > 0) {
        question.visibleIf = gotoVisibleIfArr.join(' and ')
        question.gotoVisibleIfArr = gotoVisibleIfArr
        this.setQuestion(question)
        // 如果前一个问题没有可复制，检测是否有gotos
      } else if (prevGotos.length > 0) {
        setGotos(prevQuestion, this)
      }
      this.setQuestionIndex({index: newIndex})
    },
    startEdit (data) {
      const { index, startActive } = data
      this.questionIndex = index
    },
    // 获取页面title
    pageTitle (pageItem) {
      let title = (pageItem.title || '').trim()
      title = title.length < 5 ? title : `${title.substring(0, 4)}...`
      return title ? `: ${title}` : ''
    },
    initPgaeSort () {
      const sortableEle = document.querySelector('#pages-tabs-id .el-tabs__nav')
      this.sortable = Sortable.create(sortableEle, {
        disabled: !this.isEdit,
        onEnd: event => {
          const { oldDraggableIndex, newDraggableIndex } = event
          if (oldDraggableIndex !== newDraggableIndex && this.isEdit) {
            this.movePage({
              sourcePageIndex: oldDraggableIndex,
              targetPageIndex: newDraggableIndex
            })
            resetVisibleIfFromTriggers(this)
          }
        }
      })
    },
    removePage: function (tabName) {
      this.$confirm(this.$t('general.cfmDeletePage'), this.$t('general.cfmUsual'), {
        confirmButtonText: this.$t('general.btnSure'),
        cancelButtonText: this.$t('general.btnCancel'),
        type: 'warning'
      }).then(() => {
        if (this.pages.length > 1) {
          const tabIndex = +tabName.split('_')[1]
          const page = this.pages[tabIndex]
          const elements = page.elements || []
          if (this.pageIndex > 0 && tabIndex <= this.pageIndex) {
            this.setPageIndex(this.pageIndex - 1)
          }
          elements.forEach(question => {
            removeTriggers(question, this)
          })
          this.$store.commit('removePage', tabIndex)
        }
      })
    }
  },
  mounted () {
    this.initPgaeSort()
  },
  created () {
     this.setSurveyEdit(!this.disabled)
     this.setPageIndex(0)
  },
  filters: {
  },
  watch: {
    disabled: function(newVal, oldVal) {
      this.setSurveyEdit(!newVal)
    },
    surveyModel () {
      this.updateSurveyData()
    },
    showQuestionNumbers: function(newVal, oldVal) {
      this.setShowQuestionNumbers(newVal)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "./style.scss";
</style>
