<script setup>
import axios from "axios";

import { ref, inject } from "vue";

import store from "@/store";
import router from "@/router";
import { useRoute } from "vue-router";

import { showToast } from "vant";
import { showLoadingToast,showSuccessToast } from 'vant';

import { Cropper } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";

import { register, checkLineId } from "@/api";

const URL = window.URL || window.webkitURL;

const route = useRoute();

const form = ref({
  verify: route.query.verify || null,
  aid: route.query.aid || undefined,
});

const title = ref("註冊成為會員");

const myCrop = ref(null);

const crop = ref({
  show: false,
  img: null,
});

if (route.query.verify) {
  title.value = "會員開通";
}

const validatorUrl = (val) => {
  if (val.length > 0) {
    return /(https?:\/\/|line:\/\/|tel:|mailto:)\S+/.test(val);
  } else {
    return true;
  }
};

const leaveReg = () => {
  window.location.replace("/error.html");
};

const onCrop = () => {
  const { canvas } = myCrop.value.getResult();
  if (canvas) {
    const imgFile = new FormData();
    canvas.toBlob(async (blob) => {
      let ufile = new File([blob], "image.jpg");
      imgFile.append("user_id", form.value.user_id);
      imgFile.append("fileType", "IMAGE");
      imgFile.append("file", ufile);

      crop.value.show = false;

      showLoadingToast({
        duration: 0,
        message: "圖片上傳中...",
        forbidClick: true,
      });

      let res = await axios.post(
        `${import.meta.env.VITE_APP_API_URL}/user/uploadAvatar`,
        imgFile,
        {}
      );

      if (res.data.code == 200) {
        form.value.avatar = res.data.data;
        showSuccessToast("上傳成功");
      } else {
        showToast.fail("上傳失敗");
      }
    }, "image/jpeg");
  }

  return;
};

const onClose = () => {
  crop.value.show = false;
};

const afterRead = async (file, name) => {
  crop.value.show = true;

  const ofile = file.file;

  crop.value.img = URL.createObjectURL(ofile);
  return;
};

const onSubmit = async () => {
  const liff = window.liff;
  try {
    if (!liff.isLoggedIn()) liff.login({ redirectUri: window.location.href });
  } catch (err) {
    console.log(`liff.state init error ${err}`);
    showToast("登入失敗。請聯絡管理員");
    router.push("/login");
  }

  const profile = await liff.getProfile();
  
  let checkRes = await checkLineId(profile.userId);

  if (checkRes.code !== 200) {
    showToast("您已是我們的會員，請直接登入");
    router.push("/login");
  }

  const id_token = liff.getIDToken();

  showLoadingToast({
    duration: 0,
    message: "資料傳送中...",
    forbidClick: true,
  });

  let regRes = await register({
    line_id: profile.userId,
    line_name: profile.displayName,
    line_picture: profile.pictureUrl,
    token: id_token,
    ...form.value,
  });
  console.log(regRes.code,"regRes.code")
  if (regRes.code === 500) {
    if (liff.isLoggedIn()) {
      liff.logout();
    }
    showToast("line 登入已過期");
    return;
  } else if (regRes.code === 200) {
    showToast("註冊成功");
    sessionStorage.setItem("token", regRes.data.token);
    sessionStorage.setItem("uid", regRes.data.uid);
    return router.push("/");
  } else {
    showToast("註冊失敗");
    return;
  }
};
</script>

<template>
  <div class="reg-container bg-lightPink">
    <van-nav-bar class="bg-skyBlue py-2">
      <template #title>
        <h5 class="text-white mb-1"><strong>{{title}}</strong></h5>
      </template>
    </van-nav-bar>
    
    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <div class="text-center">
            <van-uploader :after-read="afterRead" :max-count="1" name="averter" class="my-4">
              <div class="upload-main">
                <img
                  class="upload-img"
                  :src="form.avatar"
                  alt=""
                  v-if="form.avatar"
                />
                <img
                  class="upload-img"
                  src="@/assets/images/upload.jpg"
                  alt=""
                  v-else
                />
                <div class="ml-3">
                  <p class="text-skyBlue mb-2">上傳圖片，預設為Line頭像</p>
                  <van-button class="btn-darkBlue" icon="plus" block type="primary" size="small">上傳檔案</van-button>
                </div>
              </div>            
            </van-uploader>
          </div>

          <van-field
            v-model="form.real_name"
            label="姓名"
            name="pattern"
            required
            placeholder="請輸入您的姓名"
            :rules="[{ required: true, message: '姓名為必填' }]"
          />
          <van-field
            v-model="form.company"
            label="公司名稱"
            name=""
            required
            placeholder="請輸入您的公司名稱"
            :rules="[{ required: true, message: '公司名稱必填' }]"
          />
          <van-field
            v-model="form.title"
            label="職稱"
            name=""
            placeholder="請輸入您的職稱"
          />
          <van-field
            v-model="form.phone"
            label="手機"
            name=""
            required
            placeholder="Ex. 0900000001 不要有空格"
            :rules="[
              { required: true, message: '手機號必填' },
              { pattern: /\d{10}/, message: '手機號格式錯誤' },
            ]"
          />
          <van-field
            v-model="form.tel"
            label="市話"
            name=""
            placeholder="請輸入您的市話"
          />
          <van-field
            v-model="form.email"
            label="Email"
            name=""
            required
            placeholder="請輸入您的Email"
            :rules="[
              { required: true, message: 'Email必填' },
              {
                pattern: /^([\w\.\-]){1,64}\@([\w\.\-]){1,64}/,
                message: 'Email格式錯誤',
              },
            ]"
          />
          <van-field
            v-model="form.address"
            label="住址"
            name=""
            placeholder="請輸入您的地址"
          />
          <van-field
            v-model="form.url"
            label="網址"
            name=""
            placeholder="請輸入您的網址"
            :rules="[
              { validator: validatorUrl, message: '網址格式不正確,Ex. http://' },
            ]"
          />
          <van-field
            v-model="form.line"
            label="Line"
            name=""
            placeholder="請輸入您的Line ID"
          />
          <van-field
            v-model="form.facebook"
            label="Facebook"
            name=""
            placeholder="請輸入您的臉書連結"
          />
          <van-field
            v-model="form.ig"
            label="IG"
            name=""
            placeholder="請輸入您的IG ID"
          />
          <van-field
            v-model="form.youtube"
            label="YouTube"
            name=""
            placeholder="請輸入您的Youtube連結"
          />          
        </van-cell-group>
        <div class="m-3 d-flex">
          <van-button round block class="btn-skyBlue rounded-pill mx-1" @click="leaveReg">
            <h6>以後在說</h6>
          </van-button>
          <van-button round block class="btn-darkBlue rounded-pill mx-1" native-type="submit">
            <h6>送出註冊</h6>
          </van-button>
        </div>
      </van-form>
    </div>

    <van-popup class="cropPopup" v-model:show="crop.show" round closeable>
      <h5 class="text-center mt-3">檔案裁切上傳</h5>
      <div class="cropper-section">
        <div class="crop-area">
          <cropper
            class="cropper"
            ref="myCrop"
            :src="crop.img"
            :stencil-props="{
              aspectRatio: 1 / 1,
            }"
            :auto-zoom="true"
          />
        </div>
        <van-button round class="btn-tomatoRed rounded-pill w-50 mt-3" size="small" @click="onCrop">
          <h6>裁切確認</h6>
        </van-button>
      </div>
    </van-popup> 
  </div>
</template>

<style src="@/assets/css/main.css"></style>

<style lang="less" scoped>

</style>
