<script>
import { mapMutations } from 'vuex'
export default {
  props: ['question', 'index'],
  methods: {
    ...mapMutations(['setQuestion']),
    save: function () {
      this.$emit('saveEdit', {
        index: this.index
      })
      if(this.beforeSave && !this.beforeSave()) {
        return false
      }
    },
    // 验证 选项数量范围是否有效
    verifyCountLimt () {
      const choices = this.question.choices || []
      const choicesLen = choices.length
      const minNum = this.minCount || 0
      const maxNum = this.maxCount || choicesLen
      const reg = /^([0]|[1-9][0-9]*)$/
      if (!reg.test(minNum) || !reg.test(maxNum)) {
        this.$message.error(this.$t('editor.questOptionTip3'))
        return false
      } else if (minNum > maxNum) {
        this.$message.error(`${this.$t('editor.questOptionTip2')} ${maxNum}`)
        return false
      } else if (maxNum > choicesLen) {
        this.$message.error(`${this.$t('editor.questOptionTip1')} ${choicesLen}`)
        return false
      }
      this.question.validators = [
        {
          type: 'answercount',
          minCount: minNum,
          maxCount: maxNum
        }
      ]
      return true
    },
    validateData: function (arr, valueKey, textKey, validateTextFlag) {
      const hashData = {}
      for (const index in arr) {
        const item = arr[index]
        let itemValue = null
        let itemText = null
        // 对象判断
        if (typeof item === 'object') {
          if (Object.prototype.hasOwnProperty.call(item, valueKey)) {
            itemValue = (item[valueKey] + '').trim()
          }
          if (Object.prototype.hasOwnProperty.call(item, textKey)) {
            itemText = (item[textKey] + '').trim()
          }
        } else {
          itemValue = (item + '').trim()
        }

        if (hashData[itemValue]) {
          this.$message.error(this.$t('general.errRepeatValue', { 0: itemValue }))
          return false
        }

        if (validateTextFlag) {
          // 直接取反的话  null会通过此验证
          if (itemText) {
          } else {
            this.$message.error(this.$t('general.errNoneText', { 0: itemValue }))
            return false
          }
        }
        if (itemValue) {
          hashData[itemValue] = true
        }
      }

      return true
    },
    showTitle: function () {
      return this.isShowTitle ? this.isShowTitle() : true
    }
  }
}
</script>
