<template>
  <div class="Mdr-container-component">
    <cr-button class="Mdrc-component-button" @click="showPicker">
      选择出生年份
    </cr-button>
    <cr-popup v-model="showPopup" position="bottom">
      <cr-picker
        ref="picker"
        show-toolbar
        selected-index="12"
        :columns="ageScope"
        @confirm="onConfirm"
        @cancel="showPopup = false"
      />
    </cr-popup>
  </div>
</template>
<script>
import { ageScope } from "../constants";
import { parseTime } from "@/service/utils";

export default {
  name: "Age",
  props: {
    currentAnswer: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      showPopup: false,
      ageScope,
      refreshed: false
    };
  },
  methods: {
    showPicker() {
      this.showPopup = true;
      if (!this.refreshed) {
        this.$refs.picker.refreshColumns();
        this.refreshed = true;
      }
    },
    onCancel() {
      this.showPopup = false;
    },
    onConfirm(picker, res) {
      const year = res[0].slice(0, 4);
      const currentYear = parseTime("", "{y}");
      const age = currentYear - year;
      this.showPopup = false;
      this.$emit("update:currentAnswer", `${age}岁`);
      this.$emit("nextQuestion");
    }
  }
};
</script>
<style lang="less" src="../index.less" scoped></style>
