<template>
  <el-card class="question" @click.native="eventCapture($event)" @mouseover.native="hover = true" @mouseleave.native="hover = false" shadow="never">
    <div :class="['question-control', {'z-index-9': $parent.question.type != 'imagepicker'}]" v-show="!disabled && hover">
      <slot name="control"></slot>
      <el-button type="warning" @click="startEdit('logic')" size="mini" class="event-bubbling">{{ $t('general.btnLogic') }}</el-button>
      <el-button type="info" @click="startEdit('copy')" size="mini" class="event-bubbling">{{ $t('general.btnCopy') }}</el-button>
      <el-button type="info" @click="deleteQuestion()" size="mini">{{ $t('general.btnDelete') }}</el-button>
      <el-button type="info" plain @click="startEdit('move')" size="mini" class="event-bubbling">{{ $t('general.btnMove') }}</el-button>
      <el-button type="info" v-if="isFirstQuestion == false" @click="moveQuestion('up')" size="mini" class="event-bubbling">{{ $t('general.btnMoveUp') }}</el-button>
      <el-button type="info" v-if="isLastQuestion == false" @click="moveQuestion('down')" size="mini" class="event-bubbling">{{ $t('general.btnMoveDown') }}</el-button>
      <el-button type="info" @click="startEdit('test')" size="mini" class="event-bubbling" v-if="testFlag">{{ $t('general.btnTest') }}</el-button>
    </div>
    <div class="question-main">
      <div class="question-title" v-if="isShowTitle">
        <span v-if="isRequired" class="required-sign">*</span>
        {{questionIdx}} {{title == null || title.trim() == ''? name : title}}
      </div>
      <div class="question-description" v-if="!(description == null || description.trim() == '')">{{description}}</div>
      <div class="question-body">
        <slot>{{ $t('editor.questionBody') }}</slot>
      </div>
    </div>
  </el-card>
</template>

<script>
/**
 * [1] BasicQuestion 必须配合 Question 使用
 * [2] BasicQuestion 的父组件必须 minix - Question
 */
import { setVisibleIf, setGotos } from '../../utils/utils.js'

export default {
  data: function () {
    return {
      hover: false
    }
  },
  props: ['surveyModel', 'disabled'],
  methods: {
    eventCapture (event) {
      const classList = event.target.className || event.target.parentNode.className
      if (classList.indexOf('event-bubbling') > -1) {
        const rightPosition = (document.getElementById(this.scrollPrentNodeId) && document.getElementById(this.scrollPrentNodeId).scrollTop) || document.documentElement.scrollTop || document.body.scrollTop
        this.$store.commit('setRightPosition', rightPosition) // TODO 编辑状态下校验不通过时，不需要执行
      }
    },
    startEdit: function (code) {
      if (this.$parent.startEdit) {
        this.$parent.startEdit(code)
      }
    },
    deleteQuestion: function () {
      const question = this.$parent.question
      let confirmInfo = ''
      if (question.create_source === 'report') {
        confirmInfo = this.$t('general.cfmDelQuest')
      }
      this.$confirm(confirmInfo || this.$t('general.cfmDelQuest2'), this.$t('general.cfmUsual'), {
        confirmButtonText: this.$t('general.btnSure'),
        cancelButtonText: this.$t('general.btnCancel'),
        type: 'warning'
      }).then(() => {
        const questionName = question.name
        try {
          /**
           * 更新跳转逻辑：先检测此题是否是跳转逻辑的目标题；再检测此题是否存在gotos；最后更新triggers
           */
          const paper = this.$store.state.survey.model

          // 此题是“某个跳转逻辑”的目标题
          const triggers = paper.triggers || []
          triggers.forEach(item => {
            if (item.gotoName === questionName) {
              const sourceQuestion = this.$store.getters.getQuestionByName(item.sourceQuestionName)
              sourceQuestion.gotos = sourceQuestion.gotos.filter(gotoItem => gotoItem.targetQuestionName !== questionName)
              setGotos(sourceQuestion, this)
            }
          })

          // 此题如果存在gotos，删除所有题的与此题相关的visibleIf
          // 查询当前题之后的所有题
          const afterCurrentQuestions = this.$store.getters.getQuestionsAfterCurrentByName(question.name)
          for (const i in afterCurrentQuestions) {
            if (afterCurrentQuestions[i].visibleIfsFromGotos && Array.isArray(afterCurrentQuestions[i].visibleIfsFromGotos)) {
              // 删除中间题的与此题相关的visibleIfsFromGotos
              afterCurrentQuestions[i].visibleIfsFromGotos = afterCurrentQuestions[i].visibleIfsFromGotos.filter(visibleIfFromGotos => {
                return visibleIfFromGotos.sourceQuestionName !== question.name
              })
              // 设置题的visibleIf
              setVisibleIf(afterCurrentQuestions[i])
            }
          }

          // 删除与此题相关的triggers
          if (paper.triggers && Array.isArray(paper.triggers)) {
            paper.triggers = paper.triggers.filter(item => {
              return item.sourceQuestionName !== question.name
            })
          }
        } catch (e) {
          console.error(this.$t('general.cfmDelQuest3') + e)
        } finally {
          // 删除问题
          const questionIndex = this.$store.getters.getQuestionIndexByName(questionName)
          this.$store.commit('removeQuestion', questionIndex)
        }
      })
    },
    moveQuestion: function (mode) {
      const sourceQuestionIndex = this.$parent.index
      const sourcePageIndex = this.$parent.pageIndex
      let targetQuestionIndex = sourceQuestionIndex
      let targetPageIndex = sourcePageIndex

      if (mode === 'up') {
        targetQuestionIndex--
        if (targetQuestionIndex < 0) {
          if (targetPageIndex > 0) {
            targetPageIndex--
            targetQuestionIndex = this.survey.pages[targetPageIndex].elements.length
          } else {
            targetQuestionIndex = 0
          }
        }
      } else {
        targetQuestionIndex++
        if (targetQuestionIndex > this.survey.pages[targetPageIndex].elements.length - 1) {
          if (targetPageIndex < this.survey.pages.length - 1) {
            targetPageIndex = this.survey.pages.length - 1
            targetQuestionIndex = 0
          } else {
            targetQuestionIndex = this.survey.pages[targetPageIndex].elements.length
          }
        }
      }
      this.$store.dispatch('swapQuestion',
        { targetPageIndex: targetPageIndex, targetQuestionIndex: targetQuestionIndex, sourcePageIndex: sourcePageIndex, sourceQuestionIndex: sourceQuestionIndex }
      )
    }
  },
  computed: {
    title: function () {
      return this.$parent.question.title
    },
    description: function () {
      return this.$parent.question.description
    },
    questionIdx: function () {
      const beforePagesQuestionCount = this.$store.getters.getQuestionsBeforeCurPage(this.$parent.pageIndex)
      return `${beforePagesQuestionCount + this.$parent.index + 1}.`
    },
    name: function () {
      return this.$parent.question.name
    },
    isRequired () {
      return this.$parent.question.isRequired
    },
    isShowTitle () {
      return this.$parent.isShowTitle ? this.$parent.isShowTitle() : true
    },
    scrollPrentNodeId () {
      return this.$store.state.survey.scrollPrentNodeId
    },
    testFlag () {
      if (this.surveyModel.currentUser && this.surveyModel.currentUser.authorities) {
        return Array.isArray(this.surveyModel.currentUser.authorities) && this.surveyModel.currentUser.authorities.some(item => {
          return item === 'paper.design.edit.tab'
        })
      } else {
        return false
      }
    },
    survey () {
      return JSON.parse(this.$store.getters.getData())
    },
    isFirstQuestion () {
      return this.$parent.pageIndex === 0 && this.$parent.index === 0
    },
    isLastQuestion () {
      if (this.$parent.pageIndex === this.survey.pages.length - 1) {
        if (this.$parent.index === this.survey.pages[this.$parent.pageIndex].elements.length - 1) {
          return true
        }
      }
      return false
    }
  }
}
</script>

<style scoped>
.question {
  border: none;
  position: relative;
  min-width: 300px;
}
.question /deep/ .el-card__body {
  /* padding-left: 0;
  padding-right: 0; */
  padding: 20px 0;
}
.question .question-control {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: right;
  padding-top: 14px;
  padding-right: 12px;
  box-sizing: border-box;
}
.question .question-control.z-index-9 {
  z-index: 9;
}
/* .question:hover .question-control {
  background: rgba(84, 163, 138, 0.15);
} */
.question:hover .question-control {
  background: rgba(0, 154, 68, 0.1);
}
.question .question-control /deep/ .el-button--info {
  border-color: #999;
  background-color: #fff;
  color: #333;
}

.question .question-main {
  padding: 0 12px;
}
.question .question-main .question-title {
  font-size: 20px;
  color: #333;
}
.question .question-main .question-description{
  color: #333e48;
  font-weight: 300;
  font-size: 18px;
  line-height: 18px;
  padding-left: 1.8em;
  margin-top: 24px;
}
.question .question-main .question-body{
  margin-top: 22px;
  padding-left: 2em;
}
/* 联动下拉题 嵌套basicQuestion时，不显示内部题目编辑 */
.question /deep/ .question .question-control{
  display: none;
}
</style>
