<template lang="pug">
  v-container(fluid)
    v-card.elevation-0
      v-card-title 您好!
      v-card-text
        p 門票已提供旅平險
        br 
        | 免門票的6歲以下兒童(註)
        br 
        | 由社團經費統一辦理旅平險
        br 
        | 註：102/11/13後出生
        br 
        | 兩人以上請按順序用逗號區隔（包含兩人)
        br
        | EX:袁太飽,袁二寶,袁三寶,韋小寶
        v-form(@submit.prevent="submit" v-model="isValid")
          v-text-field(v-model="form.NAMESAFE" label="姓名" :rules="[requireInput]")
          v-text-field(v-model="form.TWID" label="身分證字號" :rules="[requireInput]")
          p.grey--text 註1: (民國)出生年月日
          v-text-field(v-model="form.BIRTHDAY" label="(民國)出生年月日" :rules="[requireInput]")
          v-text-field(v-model="form.SAFERemarks" label="備註")
          v-btn.airplug(type="submit" dark block depressed large :disabled="!isValid") {{ isValid ? '填好送出完成報到' : '您還沒填好喔' }}
</template>
<script lang="ts">
import { Vue, Component } from "nuxt-property-decorator";
import querystring from "querystring";
import { initLIFF } from "~/plugins/liff";
import { IForm } from "~/models/submit";

@Component
export default class Home extends Vue {
  isValid = true;

  form = {
    NAMESAFE: "",
    TWID: "",
    BIRTHDAY: "",
    SAFERemarks: "",
    LINEUserID: ""
      };

  liff: any;

  async mounted() {
    const liffId = "1654797836-joLdA2Rl";
    const liff = (this.liff = await initLIFF(liffId));
    if (!liff.isLoggedIn()) {
      liff.login();
    } else {
      const profile = await liff.getProfile();
      this.form.LINEUserID = profile.userId;
      this.autofill(profile.userId);
      console.log(this.form);
    }
  }

  async autofill(uid: string) {
    const response = await this.$axios.get(`//${window.location.host}/autofill`, { params: { LINEUserID: uid } });
    const object = response.data[0];
    if (!object) {
      return;
    }
    for(const key in this.form) {
      this.form[key] = object[key];
    }
  }

  async submit() {
    try {
      await this.$axios.$post(`//${window.location.host}/submit`, this.form);
      this.liff.closeWindow();
    } catch (error) {
      alert("送出失敗");
    }
  }

  requireInput(value) {
    value = value || '';
    return !!value.trim() ? true : "這個欄位也要填喔";
  }

  isEmail(value) {
    return !!value.match(/.+@.+[.].+/g) ? true : "email 格式不正確";
  }

  isPhone(value) {
    return value.replace(/[^0-9]/g, "").length >= 9
      ? true
      : "電話號碼不正確， 市話記得加區碼喔";
  }
}
</script>
<style scoped>
button.airplug.theme--dark.v-btn:not(.v-btn--flat):not(.v-btn--text):not(.v-btn--outlined) {
  background-color: #44d62c !important;
  color: white !important;
}
button.airplug.theme--dark.v-btn.v-btn--disabled:not(.v-btn--flat):not(.v-btn--text):not(.v-btn--outlined) {
  opacity: 0.3;
}
</style>
