<template>
  <view class="ss-p-30 head-box">
    <view class="head-title">欢迎来到门墩儿，新用户注册领积分</view>
    <view class="head-subtitle ss-m-t-30 justify-center">未注册的手机号，验证后自动注册账号</view>

    <view class="ss-m-t-60">
      <!-- 短信验证码登录 -->
      <uni-forms
        ref="smsLoginRef"
        v-model="state.sms"
        :rules="state.smsRules"
        validateTrigger="bind"
        labelWidth="140"
        labelAlign="center"
      >
        <uni-forms-item name="phone" label="手机号">
          <uni-easyinput placeholder="请输入手机号" v-model="state.sms.phone" :inputBorder="false" type="number">
            <template v-slot:right>
              <button class="login-code" :disabled="state.isMobileEnd" :class="{ 'code-btn-end': state.isMobileEnd }" @tap="handleCode">
                {{ getSmsTimer('smsLogin') }}
              </button>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item name="code" label="验证码">
          <uni-easyinput placeholder="请输入验证码" v-model="state.sms.code" :inputBorder="false" type="number" maxlength="6"></uni-easyinput>
        </uni-forms-item>
      </uni-forms>
      <!-- <view>
        <button v-if="!protocol" class="wxLogon" type="text" :plain="true" @click="showProtocolToast">微信一键登录</button>
        <button v-else class="wxLogon" type="text" :plain="true" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信一键登录</button>
      </view> -->

      <button class="send-button" @tap="handleLogin"> 注册 </button>
      <view class="agreement-box ss-flex ss-row-center">
        <uni-icons size="20" :type="protocol ? 'checkbox-filled' : 'circle'" :color="protocol ? '#00B760' : '#ccc'" @tap="protocol = !protocol"></uni-icons>
        <view class="color-999 ss-flex ss-col-center ss-m-l-8 font-size-13">
          我已阅读并遵守
          <view class="color-primary" @tap.stop="handleToDetail('user')">
            《用户协议》
          </view>
          <view class="agreement-text">和</view>
          <view class="color-primary" @tap.stop="handleToDetail('privacy')">
            《隐私协议》
          </view>
        </view>
      </view>
    </view>

    <!-- <AdvertisePop></AdvertisePop> -->

    <!-- <uni-popup ref="popup" background-color="#fff" type="bottom" :is-mask-click="false">
      <view style="padding: 20px;">
        <view class="text-center ss-m-b-50 font-size-20 color-primary">请完善您的基本信息</view>
        <uni-forms
          ref="baseInfoRef"
          v-model="formData"
          :rules="formRules"
          validateTrigger="bind"
          label-width="75px"
          labelAlign="center"
        >
          <uni-forms-item name="name" label="姓名" required>
            <uni-easyinput placeholder="请输入姓名" v-model="formData.name" :inputBorder="false" type="text"></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="phone" label="联系电话" required>
            <uni-easyinput placeholder="请输入联系电话" v-model="formData.phone" :inputBorder="false" type="number"></uni-easyinput>
          </uni-forms-item>
          <uni-forms-item name="sex" label="性别" required>
            <uni-data-picker v-model="formData.sex" :localdata="dictObj.sex" :clear-icon="false" popup-title="请选择性别" :map="{ text: 'label', value: 'value' }"></uni-data-picker>
          </uni-forms-item>
          <uni-forms-item name="jobStatus" label="求职状态" required>
            <uni-data-picker v-model="formData.jobStatus" :localdata="dictObj.jobStatus" :clear-icon="false" popup-title="请选择求职状态" :map="{ text: 'label', value: 'value' }"></uni-data-picker>
          </uni-forms-item>
          <uni-forms-item name="expType" label="工作经验" required>
            <uni-data-picker v-model="formData.expType" :localdata="dictObj.exp" :clear-icon="false" popup-title="请选择工作经验" :clear="false" :map="{ text: 'label', value: 'value' }"></uni-data-picker>
          </uni-forms-item>
          <uni-forms-item name="eduType" label="最高学历" required>
            <uni-data-picker v-model="formData.eduType" :localdata="dictObj.edu" :clear-icon="false" popup-title="请选择最高学历" :clear="false" :map="{ text: 'label', value: 'value' }"></uni-data-picker>
          </uni-forms-item>
        </uni-forms>
      </view>
      <view class="f-horizon-center">
				<button type="primary" size="default" class="send-button"  @click="submit">提 交</button>
			</view>
		</uni-popup> -->
  </view>
</template>

<script setup>
// 扫码登录注册
import { ref, unref } from 'vue'
import { mobile, code } from '@/utils/validate'
import { getSmsCode, getSmsTimer } from '@/utils/code'
import { userStore } from '@/store/user'
import { onLoad } from '@dcloudio/uni-app'
import { useIM } from '@/hooks/useIM'
import { watch } from 'vue'
// import AdvertisePop from '@/components/Advertisement'
// import { dictObj } from '@/utils/position.js'
// import { savePersonSimpleInfo } from '@/api/user'
// import { showAuthModal } from '@/hooks/useModal'

const useUserStore = userStore()
const smsLoginRef = ref()
const protocol = ref(false)
// const popup = ref()
// const baseInfoRef = ref()
// const formData = ref({})
const state = ref({
  isMobileEnd: false, // 手机号输入完毕
  codeText: '获取验证码',
  sms: {
    phone: '',
    code: '',
    inviteCode: ''
  },
  smsRules: {
    code,
    phone: mobile
  }
})
// const formRules = {
// 	name:{
// 		rules: [{required: true, errorMessage: '请输入姓名' }]
// 	},
//   phone:{
// 		rules: [{required: true, errorMessage: '请输入联系电话' }]
// 	},
// 	sex : {
// 		rules: [{required: true, errorMessage: '请选择您的性别' }]
// 	},
//   expType: {
// 		rules: [{required: true, errorMessage: '请选择您的工作年限' }]
// 	},
//   eduType: {
// 		rules: [{required: true, errorMessage: '请选择您的最高学历' }]
// 	},
//   jobStatus: {
// 		rules: [{required: true, errorMessage: '请选择您的求职状态' }]
// 	}
// }

const { resetConfig } = useIM()
watch(() => useUserStore?.accountInfo?.userId, (newVal, oldVal) => {
  if (useUserStore.refreshToken) {
		// 监听登录状态
    resetConfig()
	}
})

onLoad((options) => {
  console.log(options, 'options-my-share=========')
  // const testOptions = { scene: "shareId%3D1" }
	if (options.scene) {
    const scene = decodeURIComponent(options.scene)
    const shareUserId = scene.split('=')[1]
    state.value.sms.inviteCode = shareUserId
    console.log(shareUserId, 'shareUserId')
  }
})

// 获取验证码
const handleCode = () => {
  if (!state.value.sms.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
      duration: 2000
    })
    return
  }
  getSmsCode('smsLogin', state.value.sms.phone)
}

// 查看协议详情
const handleToDetail = (type) => {
  const url = type === 'user' ? '/pagesB/agreement/user' : '/pagesB/agreement/privacy'
  uni.navigateTo({
    url
  })
}

// 登录
const handleLogin = async () => {
  if (!protocol.value) return uni.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' })
  const validate = await unref(smsLoginRef).validate()
  if (!validate) return
  if (!state.value.sms.inviteCode) {
    uni.showToast({
      title: '邀请码缺失，请重新扫码',
      icon: 'none'
    })
    return
  }
  const result = await useUserStore.handleShareUserRegister(state.value.sms)
  if (!result || !Object.keys(result).length) return
  uni.switchTab({
    url: '/pages/index/my'
  })
  
  // uni.showToast({ icon: 'none', title: '请先完善信息' })
  // formData.value.phone = state.value.sms.phone
  // popup.value.open()
}

// const submit = async () => {
//   const validate = await unref(baseInfoRef).validate()
//   if (!validate) return uni.showToast({ title: '请将信息补充完整', icon: 'none' })
//   try {
//     uni.showToast({ title: '保存成功', icon: 'none' })
//     await useUserStore.getInfo()
//     await useUserStore.getUserInfo()
//     uni.switchTab({
//       url: '/pages/index/position'
//     })
//   } catch (err) {
//     uni.showToast({ title: err.msg || '保存失败', icon: 'none' })
//   }
// }


// const showProtocolToast = () => {
//   uni.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' })
// }

// // 微信登录
// const getPhoneNumber = async (e) => {
//   if (e?.detail?.errMsg !== 'getPhoneNumber:ok') {
//     uni.showToast({ title: '微信登录失败', icon: 'none' })
//     return
//   }
//   changeType.value = 'login'
//   wx.login({
//     success: async (result) => {
//       const wxLoginCode = result?.code || ''
//       const query = {
//         loginCode: wxLoginCode,
//         phoneCode: e.detail.code,
//         state: e.detail.encryptedData,
//       }
//       await useUserStore.handleSmsLogin(query, 2)
//     },
//     fail:(res)=> { console.log("获取登录凭证code失败！", res) }
//   })
// }
</script>

<style scoped lang="scss">
.login-code {
  width: 73px;
  min-width: 73px;
  color: #00B760;
  text-align: center; 
  font-size: 12px; 
  cursor: pointer;
  border: 1px dashed #00B760;
  border-radius: 26px;
  padding: 0;
}
.head-title {
  font-size: 40rpx;
  text-align: center;
  color: #00B760;
}
.wxLogon {
  text-align: center;
  font-size: .85em;
  color: #00B760;
  border: none;
  margin: 0;
  padding: 0;
  // margin: 40rpx;
  margin-top: -20px;
  margin-bottom: -15px;
}
</style>
