<template>
  <div v-loading="is_loading" class="selector">
    <!-- <TableLayout :column="column" :data="table_data">
      <template v-slot:action="props">
        <p v-if="props.row.action != null">{{ props.row.action }}</p>
        <div v-else>
          <el-button type="text" @click="current_question_type = props.row.typeId;fixed_questions_show = true">固定选题</el-button>
          <el-button type="text" @click="currentQuestion = props.row; previewQuestionShow = true">随机选题</el-button>
          <el-button type="text" icon="el-icon-delete" @click="deleteQuestions($event, props.row)"
            style="color:#f04343 !important">清除</el-button>
        </div>
      </template>
    </TableLayout> -->
    <div class="gy-table">
      <table>
        <thead>
          <tr class="blod">
            <td>组成</td> <td colspan="2">固定题</td> <td colspan="2">随机题</td> <td colspan="5"></td>
          </tr>
        </thead>
        <tr class="blod">
          <td>题型</td> <td>选择试题</td> <td>试题数</td> <td>选择试题</td> <td>试题数</td> <td>每题分值</td> <td>总题数</td> <td>分值</td> <td rowspan="4">操作</td>
        </tr>
        <tbody>
          <tr v-for="item in table_data" :key="item.type">
            <td>{{ item.type }}</td>
            <td>
              <el-button
                type="text"
                @click="
                  current_question_type = item.typeId;
                  fixed_questions_show = true;
                "
                >固定选题
              </el-button>
            </td>
            <td>{{ item.fixdQuestions.length }}</td>
            <td>
              <el-button
                type="text"
                @click="
                  current_question_type = item.typeId;
                  rand_questions_show = true;
                "
                >随机选题
              </el-button>
            </td>
            <td>{{ item.randQuestions.length }}</td>
            <td>
              <!-- <el-input type="number" v-model="item.itemScore" style="width:80px" min="0"> -->
              <!-- </el-input> -->
              <el-input-number
                @change="
                  (nv, ov) => {
                    if (typeof nv != 'number')
                      $nextTick(() => {
                        item.itemScore = ov;
                      });
                  }
                "
                v-model="item.itemScore"
                size="mini"
                style="width: 120px"
                :min="1"
                label="描述文字"
              >
              </el-input-number>
            </td>
            <td>{{ item.fixdQuestions.length + item.randQuestions.length }}</td>
            <td>
              {{
                (item.fixdQuestions.length + item.randQuestions.length) *
                item.itemScore
              }}
            </td>
            <td>
              <div>
                <el-button
                  type="text"
                  @click="deleteThisType(item)"
                  style="color: red"
                  >删除
                </el-button>
              </div>
            </td>
          </tr>
        </tbody>
        <tfoot>
          <tr class="blod">
            <td>总分</td>
            <td colspan="6">{{ totalScore }}</td>
          </tr>
        </tfoot>
      </table>
    </div>
    <FixedQuestionSelectTable
      v-if="fixed_questions_show"
      @onCancel="fixed_questions_show = false"
      :questionType="current_question_type"
      :oldSelection="getOldSelection('fixed')"
      @current-change="fixedChange"
      :excludeIds="getExclude('fixed')"
    >
    </FixedQuestionSelectTable>
    <RandQuestionSelecter
      v-if="rand_questions_show"
      @onCancel="rand_questions_show = false"
      :questionType="current_question_type"
      @current-change="randChange"
      :oldSelection="getOldSelection('rand')"
      :excludeIds="getExclude('rand')"
    >
    </RandQuestionSelecter>
  </div>
</template>

<script>
import '@/views/assessment-evaluation/utils/gyStyle.scss'
import { getQuestionTypeOptionsApi } from '@/api/assessment-evaluation/questions'
import FixedQuestionSelectTable from './FixedQuestionSelectTable.vue'
import RandQuestionSelecter from './RandQuestionSelecter.vue'
export default {
  components: {
    /*
     * TableLayout,
     */
    FixedQuestionSelectTable,
    RandQuestionSelecter
  },
  data: () => ({
    column: [],
    table_data: [],
    is_loading: false,
    fixed_questions_show: false,
    rand_questions_show: false,
    question_type_options: [],
    current_question_type: null
  }),
  props: {
    questionData: {
      require: false,
      default: null
    },
    isMounted: {
      default: false
    }
  },
  watch: {
    table_data: {
      deep: true,
      handler (nv) {
        const formData = this.dataFormat()
        this.$emit('current-change', formData)
      }
    },
    questionData: {
      deep: true,
      immediate: true,
      handler (nv) {
        this.questionDataFormat(nv)
      }
    }
  },
  computed: {
    /**
     * 总分数 - 计算属性
     */
    totalScore () {
      if (this.table_data.length > 0) {
        return this.table_data.reduce((prev, item, arr) => {
          /*
           *
           */
          return (
            prev +
            (item.fixdQuestions.length + item.randQuestions.length) *
              item.itemScore
          )
        }, 0)
      } else {
        return 0
      }
    }
  },
  mounted () {
    this.isMounted && this.getQuestionTypeOptions()
  },
  activated () {
    this.getQuestionTypeOptions()
  },
  methods: {
    /*
     * 从表中删除问题。
     */
    deleteThisType (type) {
      type.fixdQuestions = []
      type.randQuestions = []
    },
    /*
     * 用于格式化从父组件传入的数据的方法。
     */
    questionDataFormat (nv) {
      /*
       *
       */
      if (nv != null && Object.keys(nv).includes('fixdQuestions')) {
        /*
         *
         */
        this.table_data = this.question_type_options.map((item) => {
          const thisTypeFixdQuestions = nv.fixdQuestions.filter(
            (qus) => qus.typeId === item.id
          )
          const thisTypeRandQuestions = nv.randQuestions.filter(
            (qus) => qus.typeId === item.id
          )
          return {
            type: item.name,
            typeId: item.id,
            fixdQuestions: thisTypeFixdQuestions,
            randQuestions: thisTypeRandQuestions,
            itemScore:
              thisTypeFixdQuestions.length > 0
                ? thisTypeFixdQuestions[0].itemScore
                : thisTypeRandQuestions.length > 0
                  ? thisTypeRandQuestions[0].itemScore
                  : 1
          }
        })
      }
    },
    /**
     * 数据格式化
     */
    dataFormat () {
      const questions = this.table_data.reduce(
        (prev, item, arr) => {
          let fixd = item.fixdQuestions
          let rand = item.randQuestions
          fixd = fixd.map((question) => ({
            ...question,
            itemScore: item.itemScore
          }))
          rand = rand.map((question) => ({
            ...question,
            itemScore: item.itemScore
          }))
          prev.fixdQuestions = prev.fixdQuestions.concat(fixd)
          prev.randQuestions = prev.randQuestions.concat(rand)
          prev.totalScore += (fixd.length + rand.length) * item.itemScore
          prev.questionCount += fixd.length + rand.length
          return prev
        },
        {
          fixdQuestions: [],
          randQuestions: [],
          totalScore: 0,
          questionCount: 0
        }
      )
      /*
       *
       */
      return questions
    },
    /**
     * 固定选题被改变
     */
    fixedChange (questionList) {
      const currentRow = this.table_data.find(
        (item) => item.typeId === this.current_question_type
      )
      currentRow.fixdQuestions = JSON.parse(JSON.stringify(questionList))
      this.fixed_questions_show = false
    },
    /**
     * 随机选题被改变
     */
    randChange (questionList) {
      const currentRow = this.table_data.find(
        (item) => item.typeId === this.current_question_type
      )
      currentRow.randQuestions = JSON.parse(JSON.stringify(questionList))
      this.rand_questions_show = false
    },
    /**
     * 获取已选中项
     */
    getOldSelection (type = 'fixed') {
      const currentRow = this.table_data.find(
        (item) => item.typeId === this.current_question_type
      )
      return type === 'fixed'
        ? currentRow.fixdQuestions
        : currentRow.randQuestions
    },
    getExclude (type = 'fixed') {
      if (!this.current_question_type) {
        return null
      }
      const currentRow = this.table_data.find(
        (item) => item.typeId === this.current_question_type
      )
      if (type === 'fixed') {
        return currentRow.randQuestions.map((item) => item.id)
      } else {
        return currentRow.fixdQuestions.map((item) => item.id)
      }
    },
    // 获取问题类型的 API 调用。
    getQuestionTypeOptions () {
      getQuestionTypeOptionsApi()
        .then(({ data }) => {
          this.question_type_options = data
          if (Object.keys(this.questionData).includes('fixdQuestions')) {
            this.questionDataFormat(this.questionData)
            return
          }
          this.table_data = this.question_type_options.map((item) => ({
            type: item.name,
            typeId: item.id,
            fixdQuestions: [],
            randQuestions: [],
            itemScore: 1
          }))
        })
        .catch((err) => {
          console.info(err)
        })
        .finally((_) => {
          this.is_loading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.table_layout ::v-deep .el-table--small .el-table__cell {
  padding: 3px 0;
}

.table_layout ::v-deep .el-table .el-table__row:first-child .cell {
  font-weight: bold !important;
}
</style>
