<template>
  <div class="reg-container">
<van-nav-bar :title="title" />
<van-form @submit="onSubmit">
  <van-cell-group inset>
    <van-field
      v-model="form.phone"
      label="手機號碼"
      name=""
      required
      placeholder="Ex. 0900000001 不要有空格"
     :rules="[{ required: true, message: '手機號必填' },{ pattern: /\d{10}/ , message: '手機號格式錯誤' }]"
    />
  </van-cell-group>
  <div style="margin: 16px;">
    <van-button round block type="primary" native-type="submit">
      送出註冊
    </van-button>
    <br/>
    <van-button round block type="default" @click="leaveReg">
      以後在說
    </van-button>
  </div>
</van-form>
    <van-overlay :show="crop.show" @click="crop.show = false" />
    <div class="cropper-section" v-if="crop.show">
      <div class="crop-area">
            <cropper
                class="cropper"
                ref="myCrop"
                :src="crop.img"
                :stencil-props="{
                    aspectRatio: 1/1
                }"
                :auto-zoom="true"
            />          
      </div>
      <div class="crop-btn">
        <van-button type="primary" size="small" plain @click="onClose">取消</van-button>
        <van-button type="success" size="small" plain @click="onCrop">剪裁</van-button>    
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'
import Cookies from 'js-cookie'

import { ref } from 'vue'

import store from '@/store'
import router from '@/router'
import { useRoute } from 'vue-router'

import {Toast} 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

              Toast.loading({
                duration: 0,
                message: '圖片上傳中...',
                forbidClick: true,
              });

              let res = await axios.post(
                `${process.env.VUE_APP_API_URL}/user/uploadAvatar`,
                imgFile,
                {
                }
              )

              if (res.data.code == 200) {
                  form.value.avatar =  res.data.data
                  Toast.success('上傳成功');
              }else{
                  Toast.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 () => {

    let { id_token } = JSON.parse(sessionStorage.getItem('line'))

    Toast.loading({
      duration: 0,
      message: '資料傳送中...',
      forbidClick: true,
    });

    if(Cookies.get('refer_code')){
      form.value.refer_code = Cookies.get('refer_code')
    }

    let regRes = await register({token: id_token , ...form.value})

    if(regRes.code === 500){
      Toast('line 登入已過期')
      return router.push('/login')
    }else if(regRes.code === 200){
      Toast('註冊成功')
      Cookies.set('token',regRes.data.token, { expires: 365 ,domain: process.env.VUE_APP_DOMAIN})
      Cookies.set('uid',regRes.data.uid, { expires: 365 ,domain: process.env.VUE_APP_DOMAIN})
      return router.push('/')
    }else{
      Toast('註冊失敗')
      return router.push('/login')
    }
}

</script>



<style lang="less" scoped>
.container{
    padding-bottom: 30px;
}
.title{
    font-size: 20px;
    text-align: center;
}

.upload-img{
  width: 80px;
}

.cropper {
	height: 300px;
	// width: 300px;
	background: #DDD;
}

.cropper-section{
  margin: 0 auto;
  position: fixed;
  text-align: center;
  top: 50px;
  // left: 0;
	height: 350px;
	width: 100%;
  max-width: 500px;
  background: #DDD;
  z-index: 8888;
  .crop-area{
    margin: 5 auto;
    width: 100%;
    height: 330px;
  }
  .crop-btn{
    background-color: #666;
    text-align: center;
  }
}  
</style>