<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="goBack" />
      </view>
      <view v-show="state.step == 0">
        <view class="text-xxl text-bold text-black pd-b-20">
          {{ state.switch.reset ? '短信找回' : '找回密码' }}
        </view>
        <van-form class="transparent" @submit="onCheckCode">
          <van-field :class="{ 'field-focus': state.focus == 'phone' }" ref="phoneField" v-model="state.params.phone"
            placeholder="请输入手机号" type="digit" @focus="onFocus('phone')" @blur="onFocus('')" name="phone"
            :clearable="!state.switch.reset" :disabled="state.switch.reset" clear-trigger="always">
            <template #left-icon>
              <van-icon class-prefix="icon" name="shoujihao" />
            </template>
            <template #right-icon v-if="!state.switch.reset">
              <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' }" v-model="state.params.robot" ref="robotField"
            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" @tap="onRobotCode"
                :src="state.apiUrl + `/api/account/checkcode?type=2&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" enterkeyhint="done">
            <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" type="primary" block
              class="text-l" :color="setPwdOn ? 'linear-gradient(315deg, #FE521F 0%, #FE7902 100%)' : '#cccccc'" round>
              下一步
            </van-button>
          </div>
        </van-form>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, onBeforeMount, onMounted, ref } 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
  },
  switch: {
    reset: 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()
  if (query.phone) state.params.phone = query.phone
  if (query.reset) {
    state.switch.reset = true
    if (!state.params.phone) {
      Dialog.alert({
        title: '非法访问',
        message: '请正常操作访问#3',
        confirmButtonText: '返回首页'
      }).then(() => {
        uni.reLaunch({
          url: '/'
        })
      })
      return
    }
  }
})
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: 2
  }).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.findPwd({
    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 === '账号不存在，请先注册') {
      if (state.switch.reset) {
        Dialog.alert({
          title: '数据异常',
          message: '当前用户手机不存在，请联系开发人员#01',
          confirmButtonText: '返回首页'
        }).then(() => {
          uni.reLaunch({
            url: '/'
          })
        })
      } else {
        Dialog.confirm({
          message: '账号不存在，请先注册',
          title: "提示",
          cancelButtonText: '前往注册'
        }).catch(() => {
          // 减少用户二次填写
          uni.navigateTo({
            url: '/pages/login/register?phone=' + state.params.phone
          })
        });
      }
    }
  }).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('设置成功');
    goBack()
  }).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
}
function goBack() {
  if (state.switch.reset) {
    PageUtils.goBack()
  } else {
    goto('/pages/login/login')
  }
}
</script>

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