<template>
  <view class="bg-white bg-max">
    <view class="pd-40">
      <view class="text-xxl pd-b-20 mg-l-10-m">
        <van-icon name="arrow-left" @tap="goto('/pages/login/login')" />
      </view>
      <view v-show="state.step == 0">
        <view class="text-xxl text-bold text-black pd-b-20">注册</view>
        <van-form class="transparent" @submit="onCheckCode">
          <van-field :class="{ 'field-focus': state.focus == 'phone' }" ref="phoneField" v-model="state.params.phone"
            name="phone" placeholder="请输入手机号" type="digit" @focus="onFocus('phone')" @blur="onFocus('')" clearable
            clear-trigger="always">
            <template #left-icon>
              <van-icon class-prefix="icon" name="shoujihao" />
            </template>
            <template #right-icon>
              <van-icon v-if="validPhone" color="#39b54a" name="checked" />
              <van-icon v-else-if="state.params.phone.length == 11" color="#e54d42" name="clear" />
              <van-icon v-else-if="state.params.phone.length > 0" color="#e54d42" name="warning" />
            </template>
          </van-field>
          <van-field :class="{ 'field-focus': state.focus == 'robot' }" ref="robotField" v-model="state.params.robot"
            autocomplete="off" placeholder="请输入图形校验码" @focus="onFocus('robot')" @blur="() => { onFocus(''); }" clearable
            clear-trigger="always">
            <template #left-icon>
              <van-icon class-prefix="icon" name="yanzhengma" />
            </template>
            <template #right-icon>
              <van-image v-if="validPhone" height="75rpx" class="mg-v-25-m mg-l-20" @tap="onRobotCode"
                :src="state.apiUrl + `/api/account/checkcode?type=1&phone=${state.params.phone}&t=${state.timestamp}`" />
            </template>
          </van-field>
          <van-field :class="{ 'field-focus': state.focus == 'code' }" v-model="state.params.code" autocomplete="off"
            placeholder="请输入手机验证码" type="digit" @focus="onFocus('code')" @blur="onFocus('')" clearable
            clear-trigger="always">
            <template #left-icon>
              <van-icon name="envelop-o" />
            </template>
            <template #right-icon>
              <van-button :disabled="!sendCodeOn" plain :color="sendCodeOn ? '#FE521F' : '#cccccc'" class="mg-l-20"
                size="small" @tap="onSendCode" :loading="state.loading.sendCode">
                {{ countDownStr > 0 ? `${countDownStr}s后重新发送` : '获取验证码' }}
              </van-button>
            </template>
          </van-field>
          <div class="pd-v-50">
            <van-button :disabled="!checkCodeOn" native-type="submit" :loading="state.loading.checkCode" class="text-l"
              :color="checkCodeOn ? 'linear-gradient(315deg, #FE521F 0%, #FE7902 100%)' : '#cccccc'" round block>
              下一步
            </van-button>
          </div>
        </van-form>
      </view>
      <view v-show="state.step == 1">
        <view class="text-xxl text-bold text-black pd-b-20">设置密码</view>
        <view class="text-ss pd-t-5 pd-b-30">
          请输入正确格式（只可包含数字，英文和下划线），且长度为6-16位之间
        </view>
        <van-form class="transparent" @submit="onSetPwd">
          <van-field :class="{ 'field-focus': state.focus == 'pwd' }" ref="pwdField" v-model="state.params.pwd"
            autocomplete="off" clear-trigger="always" clearable placeholder="请输入新密码"
            :type="state.showPwd ? 'text' : 'password'" @focus="onFocus('pwd')" @blur="onFocus('')">
            <template #left-icon>
              <van-icon class-prefix="icon" name="mima" />
            </template>
            <template #right-icon>
              <van-icon class="mg-l-30" class-prefix="icon" @tap="onShowPwd"
                :name="state.showPwd ? 'xianshimima' : 'yincangmima'" />
            </template>
          </van-field>
          <van-field :class="{ 'field-focus': state.focus == 'rePwd' }" v-model="state.params.rePwd" autocomplete="off"
            clear-trigger="always" clearable placeholder="请再次输入" :type="state.showRePwd ? 'text' : 'password'"
            @focus="onFocus('rePwd')" @blur="onFocus('')">
            <template #left-icon>
              <van-icon class-prefix="icon" name="mima" />
            </template>
            <template #right-icon>
              <view class="flex">
                <template v-if="state.params.rePwd">
                  <van-icon v-if="validReRwd" color="#39b54a" name="checked" />
                  <van-icon v-else color="#e54d42" name="clear" />
                </template>
                <van-icon class="mg-l-30" class-prefix="icon" @tap="onShowRePwd"
                  :name="state.showRePwd ? 'xianshimima' : 'yincangmima'" />
              </view>
            </template>
          </van-field>
          <div class="pd-v-50">
            <van-button :disabled="!setPwdOn" native-type="submit" :loading="state.loading.setPwd" class="text-l"
              :color="setPwdOn ? 'linear-gradient(315deg, #FE521F 0%, #FE7902 100%)' : '#cccccc'" round block>
              下一步
            </van-button>
          </div>
        </van-form>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref, onMounted, onBeforeMount } from 'vue';
import { Toast } from 'vant';
import { useCountDown } from '@vant/use';
import md5 from 'md5';
import api from '@/api'
import { Dialog } from "vant";
import { PageUtils } from '@/utils/utils'
const state = reactive({
  params: {
    phone: '',
    robot: '',
    code: '',
    pwd: '',
    rePwd: '',
    authCode: ''
  },
  timestamp: 0,
  focus: '',
  step: 0,
  showKeyboard: false,
  loading: {
    sendCode: false,
    checkCode: false,
    setPwd: false
  },
  showPwd: false,
  showRePwd: false,
  apiUrl: uni.getStorageSync("uniEnv")?.api_url || ""
})
const phoneField: any = ref()
const robotField: any = ref()
const pwdField: any = ref()
const countDown = useCountDown({
  time: 60 * 1000
});
const countDownStr = computed(() => {
  return countDown.current.value.seconds
})
const validPhone = computed(() => {
  state.timestamp = new Date().getTime()
  return state.params.phone.length == 11 && /^1[3456789]\d{9}$/.test(state.params.phone)
})
const sendCodeOn = computed(() => {
  return !!(countDownStr.value == 0 && state.params.phone.length == 11 && /^1[3456789]\d{9}$/.test(state.params.phone) && !state.loading.sendCode)
})
const checkCodeOn = computed(() => {
  return !!(state.params.phone && state.params.robot && state.params.code)
})
const setPwdOn = computed(() => {
  return !!(state.params.pwd == state.params.rePwd && state.params.pwd && state.params.rePwd)
})
const validReRwd = computed(() => {
  return state.params.pwd == state.params.rePwd
})

onBeforeMount(() => {
  const query: any = PageUtils.getCurQuery()
  // 从忘记密码那边过来，可能会带上phone参数
  if (query.phone) state.params.phone = query.phone
})
onMounted(() => {
  // 可能开发人员会直接，step = 1，所以我额外加了个判断
  setTimeout(() => {
    if (state.step == 0) {
      if (state.params.phone) {
        robotField.value && robotField.value.focus()
      } else {
        phoneField.value && phoneField.value.focus()
      }
    } else if (state.step == 1) {
      pwdField.value && pwdField.value.focus()
    }
  })
})
function onFocus(focus: string) {
  state.focus = focus
}
function onRobotCode() {
  Toast.loading({
    message: '加载中',
    forbidClick: true,
  });
  state.timestamp = new Date().getTime()
}
function onSendCode() {
  if (!state.params.robot) {
    Toast('验证码不可为空')
    return
  }
  if (state.loading.sendCode || !sendCodeOn) return
  state.loading.sendCode = true
  Toast.loading({
    message: '加载中',
    forbidClick: true,
  });
  api.authcode({
    mobilePhone: state.params.phone,
    checkCode: state.params.robot,
    authType: 1
  }).then((data: any) => {
    state.params.code = ''
    countDown.reset();
    countDown.start();
  }).finally(() => {
    state.loading.sendCode = false
  })
}
function onCheckCode() {
  if (state.loading.checkCode) return
  state.loading.checkCode = true
  api.signup({
    mobilePhone: state.params.phone,
    checkCode: state.params.robot,
    authCode: state.params.code
  }).then((data: any) => {
    state.params.authCode = data
    state.step = 1
    setTimeout(() => {
      pwdField.value && pwdField.value.focus()
    })
  }).catch((data: any) => {
    if (data === '该手机号已经被注册了') {
      Dialog.confirm({
        message: '该手机号已经被注册了',
        title: "提示",
        cancelButtonText: '返回登录页'
      }).catch(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      });
    }
  }).finally(() => {
    state.loading.checkCode = false
  })
}
function onSetPwd() {
  if (!/^[0-9a-zA-Z_]{6,16}$/.test(state.params.pwd)) {
    Dialog.alert({
      title: '提示',
      message: '请输入正确格式（只可包含数字，英文和下划线），且长度为6-16位之间',
    })
    return
  }
  if (state.loading.setPwd) return
  state.loading.setPwd = true
  api.setPwd({
    mobilePhone: state.params.phone,
    newPwd: state.params.pwd,
    confirmPwd: state.params.rePwd,
    authCode: state.params.authCode
  }).then(() => {
    Toast.success('注册成功');
    uni.reLaunch({
      url: '/pages/login/login'
    })
  }).finally(() => {
    state.loading.setPwd = false
  })
}
function goto(url: any) {
  url && uni.navigateTo({ url })
}
function onShowPwd() {
  state.showPwd = !state.showPwd
}
function onShowRePwd() {
  state.showRePwd = !state.showRePwd
}
</script>

<style lang="scss" scoped>
</style>
