<template>
  <el-popover
    placement="left-start"
    popper-class="answer-popover"
    width="310"
    trigger="hover"
  >
    <el-radio-group v-model="bAnswer" @change="bAnswerChange">
      <el-radio v-for="item in radioList" :key="item.code" :label="item.code">{{
        item.name
      }}</el-radio>
    </el-radio-group>
    <div class="answer-divider"></div>
    <el-checkbox-group v-model="oAnswer" @change="oAnswerChange">
      <el-checkbox v-for="item in choiceList" :key="item" :label="item">{{
        item
      }}</el-checkbox>
    </el-checkbox-group>
    <el-button slot="reference" :type="answer ? 'primary' : 'default'" plain>{{
      answerDisplay || "请设置答案"
    }}</el-button>
  </el-popover>
</template>

<script>
const RADIO_LIST = [
  {
    name: "√",
    code: "true"
  },
  {
    name: "×",
    code: "false"
  }
];
const RADIOS = RADIO_LIST.map(item => item.code);
const RADIO_DICT = {};
RADIO_LIST.forEach(item => (RADIO_DICT[item.code] = item.name));

export default {
  name: "answer-popover",
  props: {
    value: {
      type: String
    }
  },
  data() {
    return {
      answer: "",
      oAnswer: [],
      bAnswer: null,
      choiceList: "abcdefghijklmnopqrstuvwxyz".toUpperCase().split(""),
      radioList: RADIO_LIST
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val === this.answer) return;

        if (RADIOS.includes(val)) {
          this.bAnswer = val;
        } else {
          this.oAnswer = val.split("");
        }
        this.updateAnswer();
      }
    }
  },
  computed: {
    answerDisplay() {
      if (this.bAnswer) {
        return RADIO_DICT[this.bAnswer];
      }
      return [...this.oAnswer].sort((a, b) => (a < b ? -1 : 1)).join("");
    }
  },
  methods: {
    oAnswerChange(val) {
      if (val) this.bAnswer = null;
      this.updateAnswer();
      this.emitChange();
    },
    bAnswerChange(val) {
      if (val) this.oAnswer = [];
      this.updateAnswer();
      this.emitChange();
    },
    updateAnswer() {
      if (this.bAnswer) {
        this.answer = this.bAnswer;
        return;
      }
      this.oAnswer.sort((a, b) => (a < b ? -1 : 1));
      this.answer = this.oAnswer.join("");
    },
    emitChange() {
      this.$emit("input", this.answer);
      this.$emit("change", this.answer);
    }
  }
};
</script>
