<template>
  <div class="goto-wrapper">
    <div class="global-box">
      <el-button type="success" size="small" class="el-icon-plus" @click="handleAddGlobal">{{ $t('editor.etab03') }}</el-button>
    </div>
    <el-table :data="gotos" v-show="showTable">
      <el-table-column :label="$t('editor.etab04')">
        <template slot-scope="scope">
          <el-select v-model="scope.row.sourceQuestionSubName" v-if="isMatrix" size="small" @change="handleChangeMatrixQuestion(scope.row)">
            <el-option v-for="(item, index) in getMatrixOptions(question)" :value="item.value" :label="item.label" :key="index"></el-option>
          </el-select>
          <span v-else>{{question.title || question.name}}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('editor.etab05')">
        <template slot-scope="scope">
          <el-select v-model="scope.row.condition" size="small" @change="handleChangeCondition(scope.row)">
            <el-option v-for="item in conditionList" :value="item.value" :label="item.label" :key="item.value"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('editor.questOptValue')">
        <template slot-scope="scope">
          <div v-if="!!scope.row.sourceQuestionSubName && !!scope.row.condition && ['empty', 'notempty'].indexOf(scope.row.condition) == -1">
            <el-select v-model="scope.row.value" size="small" v-if="question.type == 'matrix'">
              <el-option v-for="(item, index) in question.columns" :value="item.value || item" :label="item.text || item.value || item" :key="index"></el-option>
            </el-select>
            <el-select v-model="scope.row.value" v-else-if="['radiogroup', 'dropdown'].indexOf(scope.row.sourceQuestionType) > -1 || ('imagepicker' == scope.row.sourceQuestionType && question.multiSelect != true)" size="small">
              <el-option v-for="(item, index) in question.choices" :value="item.value || item" :label="item.text || item.value || item" :key="index"></el-option>
            </el-select>
            <el-select v-model="scope.row.value" v-else-if="scope.row.sourceQuestionType == 'checkbox' || ('imagepicker' == scope.row.sourceQuestionType && question.multiSelect == true)" multiple size="small">
              <el-option v-for="(item, index) in question.choices" :value="item.value || item" :label="item.text || item.value || item" :key="index"></el-option>
            </el-select>
            <el-switch v-model="scope.row.value" v-else-if="scope.row.sourceQuestionType === 'boolean'"></el-switch>
            <el-select v-model="scope.row.value" v-else-if="scope.row.sourceQuestionType == 'panel'" size="small">
               <el-option v-for="(item, index) in getPanelOptions(scope.row.sourceQuestionSubName)" :value="item.value || item" :label="getChoiceTitle(item)" :key="index"></el-option>
            </el-select>
            <el-input v-model="scope.row.value" v-else size="small"/>
          </div>
          <el-input v-model="scope.row.value" v-else size="small" :disabled="true"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('editor.etab06')">
        <template slot-scope="scope">
          <el-select v-model="scope.row.targetPageName" size="small" @change="handlePageSelectChange(scope.row)">
            <el-option v-for="(page, pageIdx) in pages" :value="page.name" :label="formatterPageLabel(page, pageIdx)" :key="pageIdx"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('editor.etab07')">
        <template slot-scope="scope">
          <el-select v-model="scope.row.targetQuestionName" filterable size="small">
            <template v-for="(tarQ, tarQIdx) in getTargetQuestions(scope.row.targetPageName)">
              <el-option  :title="tarQ.title" :value="getTargetQuestionName(tarQ)" :label="formatterQuestionLabel(tarQ)" :key="tarQIdx" v-if="question.name != tarQ.name"></el-option>
            </template>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column :label="$t('editor.etab08')" width="90">
        <template slot-scope="scope">
          <el-button circle size="mini" icon="el-icon-plus" @click="handleAdd(gotos, scope.$index)"></el-button>
          <el-button circle size="mini" icon="el-icon-minus" @click="handleDelete(gotos, scope.$index)"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  props: ['question'],
  data () {
    return {
      showTable: false,
      conditionList: [// 条件列表
        // {
        //   value: "empty",
        //   label: this.$t('question.condEmpty') //"为空"
        // },
        {
          value: 'notempty',
          label: this.$t('question.condNotEmpty') // "不为空"
        },
        {
          value: '=',
          label: this.$t('question.condEqual') // "等于"
        },
        {
          value: '<>',
          label: this.$t('question.condNotEqual') // "不等于"
        },
        {
          value: 'contains',
          label: this.$t('question.condContains') // "包含"
        },
        {
          value: 'notcontains',
          label: this.$t('question.condNotContains') // "不包含"
        },
        // TODO 添加anyof、allof
        // {
        //   value: "anyof",
        //   label: "any of"
        // },
        // {
        //   value: "allof",
        //   label: "all of"
        // },
        {
          value: '>',
          label: this.$t('question.condGreater') // "大于"
        },
        {
          value: '<',
          label: this.$t('question.condSmaller') // "小于"
        },
        {
          value: '>=',
          label: this.$t('question.condGELE') // "大于或等于"
        },
        {
          value: '<=',
          label: this.$t('question.condSMLE') // "小于或等于"
        }
      ],
      initialGoto: {
        sourceQuestionName: this.question.name, // 当前题名称
        sourceQuestionSubName: '', // 当前题名称，在题为矩阵类型时，区别于sourceQuestionName
        sourceQuestionType: '', // 当前题类型
        condition: '', // 条件
        value: '', // 当前题的可能值
        targetPageName: '', // 目标页名称
        targetQuestionName: '' // 目标题名称
      },
      trigger: {
        // sourceQuestionName: item.sourceQuestionName,
        // "type": "skip",
        // "expression": `{${item.sourceQuestionSubName}} ${item.condition} ${curVal}`,
        // "gotoName": item.targetQuestionName
      }
    }
  },
  computed: {
    isMatrix () {
      return ['matrix', 'matrixdropdown', 'matrixdynamic', 'panel', 'multipletext'].indexOf(this.question.type) > -1
    },
    pages () {
      return this.$store.state.survey.model.pages
    },
    gotos: {
      get () {
        let resGotos = []
        const qGotos = this.question.gotos
        if (Array.isArray(qGotos)) {
          resGotos = qGotos
          if (qGotos.length > 0) {
            /* eslint-disable */
            this.showTable = true
          }
        }
        return resGotos
      },
      set (value) {
        this.question.gotos = value
        if (value.length > 0) {
          this.showTable = true
        } else {
          this.showTable = false
        }
      }
    }
  },
  methods: {
    getChoiceTitle(item){
      let title = item
      if(typeof item === 'object'){
        title = item.pText ?  [item.pText,item.text].join('.') : item.text
      }
      return title
    },
    /**
     * 获取级联题选项
     * */ 
    getPanelOptions(qName){
        let options = []
        this.question.elements.forEach(qItem => {
          if(qItem.name === qName){
            options = qItem.choices
          }
        })
        return options
    },
    /**
     * 获取矩阵题选项
     */
    getMatrixOptions (question) {
      const matrixOptions = []
      switch (question.type) {
        case 'matrix':
          question.rows.forEach(row => {
            matrixOptions.push({
              value: `${question.name}.${row.value || row}`,
              label: row.text || row.value || row,
              cellType: 'dropdown'
            })
          })
          break
        case 'matrixdropdown':
          question.rows.forEach(row => {
            question.columns.forEach(col => {
              matrixOptions.push({
                value: `${question.name}.${row.value || row}.${col.name}`,
                label: `${row.text || row.value || row}.${col.title || col.name}`,
                cellType: col.cellType || question.cellType || 'dropdown'
              })
            })
          })
          break
        case 'matrixdynamic':
          question.columns.forEach(col => {
            matrixOptions.push({
              value: `${question.name}[0].${col.name}`,
              label: col.title || col.name,
              cellType: col.cellType || question.cellType || 'dropdown'
            })
          })
          break
        case 'panel':
          question.elements.forEach(qItem => {
            matrixOptions.push({
              value: `${qItem.name}`,
              label: qItem.title || qItem.name,
              cellType: 'panel'
            })
          })
          break
        case 'multipletext':
          question.items.forEach(qItem => {
            matrixOptions.push({
              value: `${question.name}.${qItem.name}`,
              label: qItem.title || qItem.name,
              cellType: 'text'
            })
          })
          break
      }

      return matrixOptions
    },
    /**
     * 新增goto
     */
    handleAddGlobal () {
      const resGotos = this.gotos
      const resGoto = { ...this.initialGoto }
      if (!this.isMatrix) {
        _.merge(resGoto, {
          sourceQuestionSubName: this.question.name,
          sourceQuestionType: this.question.type
        })
      }
      resGotos.push(resGoto)
      this.gotos = resGotos
    },
    /**
     * 新增goto：在当前goto选项后新增
     */
    handleAdd (gotos, idx) {
      const resGotos = gotos
      const resGoto = { ...this.initialGoto }
      if (!this.isMatrix) {
        _.merge(resGoto, {
          sourceQuestionSubName: this.question.name,
          sourceQuestionType: this.question.type
        })
      }
      resGotos.splice(idx + 1, 0, resGoto)
      this.gotos = resGotos
    },
    /**
     * 删除goto
     */
    handleDelete (gotos, idx) {
      const resGotos = gotos
      resGotos.splice(idx, 1)
      this.gotos = resGotos
    },
    /**
     * 当前题目为矩阵题时，选择/改变当前题目时修改“值”的组件; 清空条件、值
     */
    handleChangeMatrixQuestion (goto) {
      for (const item of this.getMatrixOptions(this.question)) {
        if (goto.sourceQuestionSubName === item.value) {
          goto.sourceQuestionType = item.cellType
        }
      }
      _.merge(goto, {
        condition: '',
        value: ''
      })
    },
    /**
     * 修改条件：重置值
     */
    handleChangeCondition (goto) {
      let val = goto.value
      // 布尔类型时，初始化值为true
      if (goto.sourceQuestionType == 'boolean' && ['true', 'false'].indexOf(String(val)) == -1) {
        val = false
      }
      // 条件改变为empty和notempty时，置空值
      if (['empty', 'notempty'].indexOf(goto.condition) > -1) {
        val = ''
      }
      _.merge(goto, {
        value: val // 初始化
      })
    },
    /**
     * 改变目标页：清空目标题名称
     */
    handlePageSelectChange (goto) {
      _.merge(goto, {
        targetQuestionName: ''
      })
    },
    /**
     * 获取所有可能的目标题
     */
    getTargetQuestions (pageName) {
      let list = []
      const currentPageQuestions = this.$store.getters.getQuestionsByPageName(pageName)
      // 默认返回指定页所有题
      let res = currentPageQuestions
      // 如果目标题在当前页，只可跳转到当前题之后
      const idx = currentPageQuestions.findIndex(item => item.name === this.question.name)
      if (idx > -1) {
        res = [...currentPageQuestions].splice(idx + 1)
      }
      res.map(item=>{
        const elements = item.elements || []
        if(item.type === 'panel'){
          elements.forEach(item2=>{
            list.push({
              ...item2,
              pTitle: item.title
            })
          })
        }else{
          list.push(item)
        }
      })
      return list
    },
    /**
     * 格式化page label
     */
    formatterPageLabel (page, pageIndex) {
      const idx = page.name.split('page')[1]
      let title = page.title || ''
      title = title.substring(0, 10)
      title = this.$t('editor.selectPage', {'0': pageIndex+1, '1': title})
      // return `p${pageIndex+1}-${title}`
      return title
    },
    /**
     * 格式化question label
     */
    formatterQuestionLabel (question) {
      // const idx = question.name.split('question')[1]
      const pTitle = question.pTitle || ''
      let title = question.title || question.name
      title = title.substring(0, 10)
      // return `q${idx}-${title}`
      return pTitle ? pTitle + '-' + title : title
    },
    /**
     * 获取TargetQuestionName
     * */ 
    getTargetQuestionName(tarQ){
      return tarQ.name
    }
  }
}
</script>

<style lang="scss" scoped>
.goto-wrapper{
  .global-box{
    .el-button--success {
      background: #48A736;
      border-radius: 2px;
      min-width: 80px;
    }
  }
}
.row-display {
  display: inline-block;
  width: 100%;
}

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

.row-display .el-row {
  margin-bottom: 10px;
}
</style>
