<template>
  <BasicEditor :question="question" >
    <el-tab-pane :label="$t('general.btnEdit')" name="edit">
      <el-form>
        <el-form-item :label="$t('editor.questName')" class="name-set-form-item">
          <el-input v-model="question.name" :disabled="true" />
        </el-form-item>
        <el-form-item :label="$t('editor.questTitle')" class="name-set-form-item">
          <el-input maxlength="200" v-model="question.title" />
          <div class="el-select-box">
            <el-select v-model="question.type">
              <el-option v-for="item in multiOpt" :key="item.value" :label="item.lable" :value="item.value"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item :label="$t('editor.questDesc')">
          <el-input maxlength="1000" type="textarea" v-model="question.description"></el-input>
        </el-form-item>
        <slot name="imgOptionSetting">
          <el-form-item :label="$t('editor.questImgOption')">
            <div class="row-display">
              <el-row :gutter="5" style="margin-bottom: 0;">
                <el-col :span="1"><span class="empty-placeholder"></span></el-col>
                <el-col :span="8" >{{ $t('editor.questOptValue') }}</el-col>
                <el-col :span="8">{{ $t('editor.matrixColChoose') }}</el-col>
                <el-col :span="2"><span class="empty-placeholder"></span></el-col>
              </el-row>
            </div>
            <draggable v-model="question.choices" :handle="'.drag-item'">
              <div class="row-display" v-for="(item, index) in question.choices" :key="index">
                <el-row :gutter="16">
                  <el-col :span="1"><i class="el-icon-s-operation drag-item"></i></el-col>
                  <el-col :span="8" ><el-input @change="handleChoiceValueChange(item, index)" v-model="item.value"></el-input></el-col>
                  <el-col :span="8"><el-input v-model="item.text"></el-input></el-col>
                  <el-col :span="7">
                    <el-button circle size="mini" icon="el-icon-plus" @click="handleAddChoice(index)"></el-button>
                    <el-button circle size="mini" icon="el-icon-minus" v-if="question.choices.length > minChoiecesNum" @click="handleDeleteChoice(question.choices, index)"></el-button>
                  </el-col>
                </el-row>
              </div>
            </draggable>
          </el-form-item>
        </slot>
        <el-form-item :label="$t('editor.questMinCountLimit')" class="uplimit" v-show="question.type == 'checkbox' || (question.type == 'imagepicker' && question.multiSelect)">
          <el-input-number :precision="0" v-model="minCount" :controls="false" />
        </el-form-item>
        <el-form-item :label="$t('editor.questMaxCountLimit')" class="uplimit" v-show="question.type == 'checkbox' || (question.type == 'imagepicker' && question.multiSelect)">
          <el-input-number :precision="0" v-model="maxCount" :controls="false"  />
        </el-form-item>
        <slot></slot>
      </el-form>
    </el-tab-pane>
    <el-tab-pane :label="$t('general.btnChoose')" name="options">
      <el-form>
        <el-form-item>
          <el-checkbox v-model="question.visible">{{ $t('editor.isVisible') }}</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="question.isRequired">{{ $t('editor.isMustAsked') }}</el-checkbox>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </BasicEditor>
</template>

<script>
import BasicEditor from './BasicEditor'
import Editor from './Editor'
import draggable from 'vuedraggable'
export default {
  mixins: [Editor],
  props: ['question'],
  components: {
    BasicEditor,
    draggable
  },
  data () {
    return {
      webChoice: 'Choose...',
      webChoicesList: [],
      maxCount: undefined,
      minCount: undefined
    }
  },
  computed: {
    multiOpt () {
      return [
        {
          value: 'radiogroup',
          lable: this.$t('question.radioTag')
        },
        {
          value: 'checkbox',
          lable: this.$t('question.checkboxTag')
        },
        {
          value: 'dropdown',
          lable: this.$t('question.dropdownTag')
        },
        {
          value: 'imagepicker',
          lable: this.$t('question.imageTag')
        }
      ]
    },
    minChoiecesNum () {
      return 1
    }
  },
  beforeMount () {

  },
  mounted () {
    if (this.question.validators) {
      this.maxCount = this.question.validators[0].maxCount
      this.minCount = this.question.validators[0].minCount
    }
    this.question.choices = this.question.choices.map(item => {
      if (typeof item === 'string') {
        item = { value: item, text: '' }
      }
      return Object.assign({}, item)
    })
  },
  methods: {
    beforeSave () {
      return this.verifyCountLimt()
    },
    handleAddChoice (rowIndex) {
      const choices = this.question.choices || []
      const value = this.getDefaultValue(choices)
      this.question.choices.splice(rowIndex + 1, 0, {
        value: value,
        text: ''
      })
    },
    getDefaultValue (choices) {
      let maxIndex = 0
      choices.forEach(item => {
        const index = +item.value.replace('item', '')
        maxIndex = index > maxIndex ? index : maxIndex
      })
      maxIndex = maxIndex + 1
      return `item${maxIndex}`
    },
    handleChoiceValueChange (choice) {
      if (choice.value === '' || choice.value.trim() === '') {
        choice.value = this.$store.getters.getDefaultItemValue(
          this.question.choices,
          'value',
          'item'
        )
      }
    },
    handleDeleteChoice (choices, rowIndex) {
      choices.splice(rowIndex, 1)
    },
    getChoicesFromWeb (val, source) {
      const choicesByUrl = this.question.choicesByUrl

      this.axios({
        method: 'get',
        url: choicesByUrl.url
      })
        .then(res => {
          this.webChoice = 'Choose...'
          const list = []
          const mappingField =
              choicesByUrl.titleName || choicesByUrl.valueName || ''

          // path存在时，如果res是一个对象则可取res[path]的值
          if (choicesByUrl.path) {
            if (typeof res === 'object' && !Array.isArray(res)) {
              const pathList = choicesByUrl.path.split('\\') // surveyjs中path的格式为'xx\yy\zz'
              for (let i = 0; i < pathList.length; i++) {
                res = res[pathList[i]]
              }
            } else {
              this.webChoicesList = []
              return
            }
          }
          if (Array.isArray(res) && res.length > 0 && mappingField) {
            const mappingFieldList = mappingField.split('.') // surveyjs中path的格式为'aa.bb.cc'
            res.forEach(item => {
              for (let i = 0; i < mappingFieldList.length; i++) {
                item = item[mappingFieldList[i]]
              }
              if (item) {
                // 确保下拉框的值有效
                list[list.length] = item
              }
            })
          }
          this.webChoicesList = list
        })
    }
  }
}
</script>

<style scoped>
.el-form /deep/ .el-form-item__content {
  text-align: left;
}

.display-inline-block {
  display: inline-block;
  width: 100%;
}

.drag-item {
  cursor: move;
  font-size: 20px;
}

.row-display {
  display: inline-block;
  width: 100%;
}

.row-display .empty-placeholder {
  display: inline-block;
  min-width: 20px;
}

.row-display .el-row {
  margin-bottom: 10px;
}

.el-form /deep/ .name-set-form-item .el-form-item__content > .el-input {
  width: calc(100% - 240px);
  display: block;
}

.el-form /deep/ .name-set-form-item .el-form-item__content > .el-select-box {
  position: absolute;
  right: 0;
  top: 42px;
}
</style>
