<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-user-login con">
    <view class="logo">
      <view class="logo-con">
        <image
          :src="uniLoginLogoImg"
          mode="heightFix"
          @tap="onToIndex"
        />
      </view>
    </view>
    <!-- 账号登录 -->
    <view
      v-if="!isForgetPassword && loginStatus === 0"
      class="login-form"
    >
      <!-- 账号 -->
      <view :class="['item', errorTips === 1 ? 'error' : '']">
        <view class="account">
          <input
            v-model="principal"
            type="text"
            maxlength="11"
            data-type="account"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterUsername')"
            @blur="onPrincipalInput"
            @confirm="onLogin"
          >
        </view>
        <view
          v-if="errorTips === 1"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.usernameWarn') }}
        </view>
      </view>
      <!-- 密码 -->
      <view :class="['item', errorTips === 2 ? 'error' : '']">
        <view class="account">
          <input
            v-model="credentials"
            type="text"
            :password="passwordType"
            data-type="password"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterPassword')"
            @confirm="onLogin"
            @blur="credentials = credentials.replace(/\s/g,'')"
          >
          <div class="image-box">
            <image
              :src="passwordImage"
              style="width:26rpx;height:18rpx"
              mode="heightFix"
              @tap="onShowPassword"
            />
          </div>
          <text
            class="input-suffix"
            @tap="onForgotPassword"
          >
            {{ $t('userLogin.forgetPwd') }}
          </text>
        </view>
        <view
          v-if="errorTips === 2"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterPassword') }}
        </view>
      </view>
      <!-- 按钮 -->
      <view>
        <button
          class="authorized-btn"
          @tap="onLogin"
        >
          {{ $t('userLogin.login') }}
        </button>
      </view>
      <!-- 服务条款 -->
      <view
        class="item statement"
      >
        <label
          class="statement-label"
          @tap.stop="onHandlePrivacyClick"
        >
          <checkbox
            class="check-box"
            color="#fff"
            :checked="isPrivacy === 1"
            @tap.stop="onHandlePrivacyClick"
          />
          <view style="color: #999999">
            {{ $t('userLogin.loginAgree') }}
            <text
              @tap.stop="onToTermsOfService('serviceTerms')"
            >《{{ $t('userLogin.termsOfService') }}》
            </text>
            <text
              style="color: #999999"
            >{{ $t('userLogin.and') }}
            </text>
            <text
              @tap.stop="onToTermsOfService('servicePolicy')"
            >《{{ $t('userLogin.privacyPolicy') }}》
            </text>
          </view>
        </label>
      </view>
    </view>
    <!-- 手机验证码登录 -->
    <view
      v-show="!isForgetPassword && loginStatus === 1"
      class="login-form"
    >
      <!-- 手机号 -->
      <view :class="['item', errorTips ? 'error' : '']">
        <view
          class="account"
          :style="{justifyContent:'unset',background: errorTips === 1 || errorTips === 8 ? '#FBEFEF' : '#fff'}"
        >
          <text class="input-item">
            +86
          </text>
          <input
            v-model="principal"
            type="number"
            maxlength="11"
            data-type="account"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterPhone')"
            @confirm="onLogin"
          >
        </view>
        <view
          v-if="errorTips === 1"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.phoneWarn') }}
        </view>
        <view
          v-if="!principal && errorTips === 8"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterPhone') }}
        </view>
        <view
          v-if="errorTips === 9"
          class="error-box"
        >
          <view class="error-text">
            {{ $t('userLogin.hadBind') }}
          </view>
          <image
            src="/static/images/icon-prompt.png"
            style="width:28rpx;height:28rpx;margin-top: 10rpx;"
            mode="heightFix"
          />
        </view>
      </view>
      <!-- 验证码 -->
      <view :class="['item', errorTips ? 'error' : '']">
        <view class="account">
          <input
            v-model="validCode"
            type="text"
            maxlength="6"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterCode')"
            @confirm="onLogin"
          >
          <text
            v-if="show"
            class="login-code"
            @tap="onGetCode"
          >
            {{ $t('userLogin.getCode') }}
          </text>
          <text
            v-if="!show"
            class="input-btn"
          >
            {{ count }} s
          </text>
        </view>
        <view
          v-if="errorTips === 3"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterCode') }}
        </view>
        <view
          v-if="errorTips === 6"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterCodeFirst') }}
        </view>
      </view>
      <!-- 按钮 -->
      <view>
        <button
          class="authorized-btn"
          @tap="onLogin"
        >
          {{ $t('userLogin.login') }}
        </button>
      </view>
      <!-- 服务条款 -->
      <view
        class="item statement"
      >
        <label
          class="statement-label"
          @tap.stop="onHandlePrivacyClick"
        >
          <checkbox
            class="check-box"
            color="#fff"
            :checked="isPrivacy === 1"
            @tap.stop="onHandlePrivacyClick"
          />
          <view style="color: #999999">
            {{ $t('userLogin.regAgree') }}
            <text
              @tap.stop="onToTermsOfService('serviceTerms')"
            >《{{ $t('userLogin.termsOfService') }}》
            </text>
            <text
              style="color: #999999"
            >{{ $t('userLogin.and') }}
            </text>
            <text
              @tap.stop="onToTermsOfService('servicePolicy')"
            >《{{ $t('userLogin.privacyPolicy') }}》
            </text>
          </view>
        </label>
      </view>
    </view>
    <!-- 微信登录 -->
    <view
      v-if="!isForgetPassword && loginStatus === 2"
      class="login-form"
    >
      <!-- 按钮 -->
      <view>
        <button
          v-if="!isPrivacy"
          class="authorized-btn"
          @tap="onMaskBtn"
        >
          {{ $t('userLogin.wechatOneKeyLogin') }}
        </button>
        <button
          v-else
          open-type="getPhoneNumber"
          class="authorized-btn"
          @getphonenumber="onGetPhoneNumberLogin"
        >
          {{ $t('userLogin.wechatOneKeyLogin') }}
        </button>
      </view>
      <!-- 服务条款 -->
      <view
        class="item statement"
      >
        <label
          class="statement-label"
          @tap.stop="onHandlePrivacyClick"
        >
          <checkbox
            class="check-box"
            color="#fff"
            :checked="isPrivacy === 1"
            @tap.stop="onHandlePrivacyClick"
          />
          <view style="color: #999999">
            {{ $t('userLogin.regAgree') }}
            <text
              @tap.stop="onToTermsOfService('serviceTerms')"
            >《{{ $t('userLogin.termsOfService') }}》
            </text>
            <text
              style="color: #999999"
            >{{ $t('userLogin.and') }}
            </text>
            <text
              @tap.stop="onToTermsOfService('servicePolicy')"
            >《{{ $t('userLogin.privacyPolicy') }}》
            </text>
          </view>
        </label>
      </view>
    </view>
    <!-- 修改密码 -->
    <view
      v-if="isForgetPassword"
      class="login-form"
    >
      <!-- 手机号 -->
      <view
        v-if="!nextBtn"
        :class="['item', errorTips ? 'error' : '']"
      >
        <view class="account">
          <input
            v-if="!isPersonalCenter"
            v-model="principal"
            type="number"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterPhone')"
            maxlength="11"
            @confirm="onNextStep"
          >
          <view v-else>
            {{ privacyNumber }}
          </view>
        </view>
        <view
          v-if="errorTips === 1"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.phoneWarn') }}
        </view>
        <view
          v-if="!principal && errorTips === 8"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterPhone') }}
        </view>
      </view>
      <!-- 验证码 -->
      <view
        v-if="!nextBtn"
        :class="['item', errorTips ? 'error' : '']"
      >
        <view class="account">
          <input
            v-model="validCode"
            type="text"
            class="int-yzm"
            maxlength="6"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterCode')"
            @confirm="onNextStep"
          >
          <text
            v-if="show"
            class="login-code"
            @tap="onGetCode"
          >
            {{
              $t('userLogin.getCode')
            }}
          </text>
          <text
            v-if="!show"
            class="input-btn"
          >
            {{ count }} s
          </text>
        </view>
        <view
          v-if="errorTips === 3"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterCode') }}
        </view>
        <view
          v-if="errorTips === 6"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterCodeFirst') }}
        </view>
      </view>
      <!-- 新密码 -->
      <view
        v-if="nextBtn"
        :class="['item', errorTips ? 'error' : '']"
      >
        <view class="account">
          <input
            type="text"
            :password="newPasswordType"
            data-type="0"
            :value="newPassWord"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterNew')"
            maxlength="20"
            @input="onGetPassInputVal"
            @confirm="onChangePassWord"
            @blur="newPasswordType = newPasswordType.replace(/\s/g,'')"
          >
          <div class="image-box">
            <image
              :src="newPasswordImage"
              style="width:26rpx;height:18rpx"
              mode="heightFix"
              @tap="onShowNewPassword"
            />
          </div>
        </view>
        <view
          v-if="errorTips === 4"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterNew') }}
        </view>
        <view
          v-if="errorTips === 9"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.passwordVerification') }}
        </view>
        <view
          v-if="errorTips === 10"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.pwdCantBeEmpty') }}
        </view>
      </view>
      <!-- 确认密码 -->
      <view
        v-if="nextBtn"
        :class="['item', errorTips ? 'error' : '']"
      >
        <view class="account">
          <input
            type="text"
            :password="conNewPasswordType"
            data-type="1"
            :value="comNewPassWord"
            placeholder-class="inp-palcehoder"
            :placeholder="$t('userLogin.enterNewAgain')"
            maxlength="20"
            @input="onGetPassInputVal"
            @confirm="onChangePassWord"
            @blur="conNewPasswordType = conNewPasswordType.replace(/\s/g,'')"
          >
          <div class="image-box">
            <image
              :src="conNewPasswordImage"
              style="width:26rpx;height:18rpx"
              mode="heightFix"
              @tap="onShowConNewPassword"
            />
          </div>
        </view>
        <view
          v-if="errorTips === 5"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.enterNewAgain') }}
        </view>
        <view
          v-if="errorTips === 7 && !identical"
          class="error-text"
        >
          <text class="warning-icon">
            !
          </text>
          {{ $t('userLogin.comparedPassword') }}
        </view>
      </view>

      <view
        v-if="isForgetPassword && !nextBtn"
        style="text-align: center;"
      >
        <button
          class="authorized-btn"
          @tap="onNextStep"
        >
          {{ $t('userLogin.nextStep') }}
        </button>
        <view
          v-if="!isPersonalCenter"
          class="back-login"
          @tap="onGoBack"
        >
          {{ $t('userLogin.BackLogin') }}
        </view>
      </view>
      <view
        v-if="isForgetPassword && nextBtn"
        style="text-align: center;"
      >
        <button
          class="authorized-btn"
          @tap="onChangePassWord"
        >
          {{ $t('userLogin.confirmChanges') }}
        </button>
        <view
          v-if="!isPersonalCenter"
          class="back-login"
          @tap="onGoBack"
        >
          {{ $t('userLogin.BackLogin') }}
        </view>
      </view>
    </view>
    <!-- 其他登录方式 -->
    <view
      v-if="!isForgetPassword"
      class="footer"
      :style="{top: regLocation}"
    >
      <view class="other-login-text">
        {{ $t('userLogin.otherLogMethods') }}
      </view>
      <view class="other-login">
        <!-- #ifdef MP-WEIXIN -->
        <view
          class="other-login-one"
          @tap="onOtherLogin(1)"
        >
          <image
            :src="loginStatus === 0 || loginStatus === 1 ? iconWeixin:iconMobilePphoneM"
            mode="heightFix"
          />
          <view>
            {{
              loginStatus === 0 || loginStatus === 1 ? $t('userLogin.wechatLogin') : $t('userLogin.phoneLogin')
            }}
          </view>
        </view>
        <!-- #endif -->
        <view
          class="other-login-two"
          @tap="onOtherLogin(2)"
        >
          <image
            :src="loginStatus === 1 || loginStatus === 2 ? iconPassword:iconMobilePphoneM"
            mode="heightFix"
          />

          <view>
            {{
              loginStatus === 1 || loginStatus === 2 ? $t('userLogin.accountLogin') : $t('userLogin.phoneLogin')
            }}
          </view>
        </view>
      </view>
    </view>

    <!--  隐私协议  -->
    <confirm-pop
      :show-pop="showAgreementPop"
      :pop-content="popContent"
      @handle-pop-cancel="showAgreementPop = false"
      @handle-pop-confirm="onHandlePrivacyClick"
    >
      <template #default>
        <view class="content">
          请您仔细阅读并充分理解相关条款，点击同意即代表您已阅读并同意
          <text @tap.stop="onToTermsOfService('serviceTerms')">
            《服务条款》
          </text>与
          <text @tap.stop="onToTermsOfService('servicePolicy')">
            《隐私政策》
          </text>
        </view>
      </template>
    </confirm-pop>
  </view>
</template>

<script setup>
import { encrypt } from '@/utils/crypto'
import { AppType } from '@/utils/constant'
import util from '@/utils/util'
import * as cartCount from '@/utils/cart-count.js'
import logoPng from '@/static/logo.png'
import iconPassword from '@/package-user/static/images/password.png'
import iconMobilePphoneM from '@/package-user/static/images/mobile-phone.png'
import iconWeixin from '@/package-user/static/images/weixin.png'
import iconHide from '@/package-user/static/images/icon-hide.png'
import iconView from '@/package-user/static/images/icon-view.png'

const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

const principal = ref('')
const credentials = ref('')
const isForgetPassword = ref(false) // 是否修改密码
const isPersonalCenter = ref(false) // 是否从个人中心页面跳转过来
const show = ref(true) // 获取验证码按钮
// 验证码相关
const validCode = ref('') // 验证码

const nextBtn = ref(false) // 修改密码下一步
const newPassWord = ref('') // 新密码
const comNewPassWord = ref('') // 确认新密码

const errorTips = ref(0) // 错误提示
const identical = ref(Boolean) // 是否一致
const uniLoginLogoImg = ref(uni.getStorageSync('cloudUniLoginLogoImg'))
const isPrivacy = ref(uni.getStorageSync('cloudIsPrivacy') || 0)
const passwordType = ref(true)

const loginStatus = ref(0) // 选择的登录方式 0-密码、1-验证码、2-微信
const newPasswordType = ref(true)
const newPasswordImage = ref(iconHide)
const conNewPasswordImage = ref(iconHide)
const appType = uni.getStorageSync('cloudAppType')

const privacyNumber = ref('')
watch(() => loginStatus.value, (nv) => {
  errorTips.value = 0
  validCode.value = ''
  principal.value = ''
  credentials.value = ''
  if (nv === 1 || nv === 2) {
    principal.value = uni.getStorageSync('cloudUserDetails').userMobile || ''
    const pre = principal.value.substr(0, 3)
    const next = principal.value.substr(7, 4)
    privacyNumber.value = pre + '****' + next
  }
})

/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  if (options?.isWebview) {
    // 是否为web-view跳转登录
    const pages = getCurrentPages()
    // 登录后的回跳地址
    uni.setStorageSync('cloudRouteUrlAfterLogin', pages[pages.length - 2].$page.fullPath)
  }
  if (options && options.isForgetPassword) {
    isForgetPassword.value = options.isForgetPassword
    uni.setNavigationBarTitle({
      title: $t('userLogin.changePassword')
    })
  }
  if (options && options.isPersonalCenter) {
    isPersonalCenter.value = options.isPersonalCenter
    uni.setNavigationBarTitle({
      title: $t('userLogin.changePassword')
    })
  } else {
    // 头部导航标题
    uni.setNavigationBarTitle({
      title: $t('userLogin.userLogin')
    })
  }
  loginStatus.value = appType === AppType.MINI ? 2 : 1

  // 获取网站配置
  onGetWebConfig()

  // 如果没有 tempUid 重新请求一个
  if (!uni.getStorageSync('cloudTempUidCloud')) util.weChatLogin()
})

/**
 * 生命周期函数--监听页面初次渲染完成
 */
const regLocation = ref('')
onReady(() => {
  uni.getSystemInfo({
    success: res => {
      // 根据屏幕高度设置 top 值
      regLocation.value = res.windowHeight - 150 + 'px'
    }
  })
})

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: isForgetPassword.value ? $t('userLogin.changePassword') : $t('userLogin.userLogin')
  })
})

const onGetWebConfig = () => {
  const params = {
    url: '/tmerclub_admin/ua/web_config/get_activity',
    method: 'GET',
    data: {
      webConfigType: 'H5_WEBSITE_CONFIG'
    }
  }
  http.request(params).then(res => {
    if (res && res.loginLogoImg) {
      uniLoginLogoImg.value = res.loginLogoImg.indexOf('http') > -1 ? res.loginLogoImg : resourcesUrl + res.loginLogoImg
    } else {
      uniLoginLogoImg.value = logoPng
    }
  })
}

const popContent = reactive({
  confirmText: '同意',
  slot: true,
  title: '温馨提示'
})
const showAgreementPop = ref(false)
// #ifdef MP-WEIXIN
/**
 * 蒙版按钮
 */
const onMaskBtn = () => {
  showAgreementPop.value = true
}

/**
 * 微信小程序获取手机号一键登录按钮
 */
const onGetPhoneNumberLogin = (e) => {
  // 拒绝了授权
  if (!e.detail.code) {
    return
  }
  const params = {
    url: '/tmerclub_auth/ua/ma/login',
    method: 'POST',
    data: {
      code: e.detail.code,
      tempUid: uni.getStorageSync('cloudTempUidCloud')
    }
  }
  http.request(params).then(res => {
    if (res.accessToken) {
      uni.setStorageSync('cloudIsPrivacy', 1)
      uni.setStorageSync('cloudHadLogin', true)
      uni.setStorageSync('cloudToken', res.accessToken)
      uni.setStorageSync('cloudLoginResult', res) // 保存整个登录数据
      const expiresTimeStamp = res.expiresIn * 1000 / 2 + new Date().getTime()
      // 缓存token的过期时间
      uni.setStorageSync('cloudExpiresTimeStamp', expiresTimeStamp)

      // 还原全局 正在登录状态
      util.resetLoginSts()
      // 请求购物车数量
      cartCount.getCartCount()
      uni.redirectTo({
        url: '/package-user/pages/login-success/login-success'
      })
    }
  }).catch(err => {
    onLoginErrHandle(err)
  })
}
// #endif

/**
 * 条款点击事件(勾选/取选)
 */
const onHandlePrivacyClick = () => {
  isPrivacy.value = isPrivacy.value === 1 ? 0 : 1
  showAgreementPop.value = false
}

const onGetPassInputVal = (e) => {
  const type = parseInt(e.currentTarget.dataset.type)
  if (type === 0) {
    newPassWord.value = e.detail.value
    // 密码由字母、数字和特殊符号三种字符组成8-20位半角字符，区分大小写
    const reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*(\W|_))[A-Za-z\d(\W|_)]{8,20}$/
    const result = reg.test(newPassWord.value)
    if (!result) {
      errorTips.value = 9
    } else {
      errorTips.value = 0
    }
  } else if (type === 1) {
    if (errorTips.value === 9) {
      return
    }
    comNewPassWord.value = e.detail.value
    setTimeout(() => {
      if (errorTips.value === 9 || errorTips.value === 10) {
        return
      }
      if (
        comNewPassWord.value &&
        newPassWord.value &&
        comNewPassWord.value !== newPassWord.value
      ) {
        errorTips.value = 7
        identical.value = false
      } else if (!comNewPassWord.value) {
        errorTips.value = 5
      } else {
        errorTips.value = 0
        identical.value = true
      }
    }, 1000)
  }
}

const onPrincipalInput = () => {
  principal.value = principal.value.replace(/\s/g, '')
}

/**
 * 登录
 */
const onLogin = () => {
  // 密码账号登录
  if (loginStatus.value === 0) {
    errorTips.value = !principal.value.trim() ? 1 : !credentials.value.trim() ? 2 : 0
  }
  // 验证码登录 - 手机号校验
  if (loginStatus.value === 1) {
    errorTips.value = !principal.value.trim() ? 8 : !util.checkPhoneNumber(principal.value) ? 1 : !validCode.value.trim() ? 3 : 0
  }
  if (errorTips.value) return
  if (isPrivacy.value !== 1) {
    showAgreementPop.value = true
    return
  }
  const url = uni.getStorageSync('cloudAppType') > AppType.MP ? loginStatus.value === 0 ? '/tmerclub_auth/ua/login' : '/tmerclub_auth/ua/login_with_code' : loginStatus.value === 0 ? '/tmerclub_auth/ua/wx/login' : '/tmerclub_auth/ua/login_with_code'
  const params = {
    url,
    method: 'POST',
    data: {
      sysType: 0,
      socialType: uni.getStorageSync('cloudAppType'),
      tempUid: uni.getStorageSync('cloudAppType') <= 2 ? uni.getStorageSync('cloudTempUidCloud') || 'mall' : uni.getStorageSync('cloudTempUidCloud'),
      userName: loginStatus.value === 0 ? principal.value : undefined,
      passWord: loginStatus.value === 0 ? encrypt(credentials.value) : undefined,
      mobile: loginStatus.value === 1 ? principal.value : undefined,
      validCode: loginStatus.value === 1 ? validCode.value : undefined
    }
  }
  http.request(params).then((res) => {
    util.loginSuccess(res.tokenInfo ? res.tokenInfo : res)
  }).catch((err) => {
    setTimeout(() => {
      onLoginErrHandle(err)
    }, 50)
  })
}

/**
 * 登录异常
 */
const onLoginErrHandle = (err) => {
  if (err.code === 'A00001' || err.code === 'A00005' || err.code === 'A00006') {
    uni.showToast({
      title: err.msg || 'Error',
      icon: 'none'
    })
  }
  if (err.code === 'A00012') {
    // 还原全局 正在登录状态
    util.resetLoginSts()
    // tempUid 错误，重新获取
    uni.removeStorageSync('cloudTempUidCloud')
    uni.showModal({
      showCancel: false,
      title: $t('userLogin.tips'),
      content: $t('userLogin.codeErrorTips'),
      confirmText: $t('userLogin.confirm'),
      success: res => {
        if (res.confirm) {
          // #ifdef H5
          window.history.replaceState({}, '', window.location.href.split('?')[0])
          // #endif
          util.weChatLogin()
        }
      }
    })
  }
  if (err.code === 'A04002') {
    // 弹窗
    uni.showModal({
      showCancel: false,
      title: $t('userLogin.bindedTipsTit'),
      content: $t('userLogin.bindedTipsCon'),
      confirmText: $t('userLogin.bindedTipsBtn'),
      confirmColor: '#E43130'
    })
  }
}

/**
 * 回到首页
 */
const onToIndex = () => {
  if (isPersonalCenter.value) return
  uni.switchTab({
    url: '/pages/index/index'
  })
}

/**
 * 去条款页
 */
const onToTermsOfService = (key) => {
  uni.navigateTo({
    url: '/pages/terms-page/terms-page?sts=' + key
  })
}

// 控制密码输入框显隐
const passwordImage = ref(iconHide)
const onShowPassword = () => {
  passwordImage.value = passwordType.value ? iconView : iconHide
  passwordType.value = !passwordType.value
}
// 控制新密码输入框显隐
const onShowNewPassword = () => {
  newPasswordImage.value = newPasswordType.value ? iconView : iconHide
  newPasswordType.value = !newPasswordType.value
}
// 控制确认密码输入框显隐
const conNewPasswordType = ref(true)
const onShowConNewPassword = () => {
  conNewPasswordImage.value = conNewPasswordType.value ? iconView : iconHide
  conNewPasswordType.value = !conNewPasswordType.value
}
// 其他登录方式
const onOtherLogin = (val) => {
  if (val === 1) {
    loginStatus.value = loginStatus.value === 0 || loginStatus.value === 1 ? 2 : 1
  } else {
    loginStatus.value = loginStatus.value === 1 || loginStatus.value === 2 ? 0 : 1
  }
}
/**
 * 修改密码（登录页修改密码按钮）
 */
const onForgotPassword = () => {
  isForgetPassword.value = true
  errorTips.value = 0
  principal.value = ''
  credentials.value = ''
  uni.setNavigationBarTitle({
    title: $t('userLogin.changePassword')
  })
}
// 返回
const onGoBack = () => {
  principal.value = ''
  errorTips.value = null
  newPassWord.value = ''
  validCode.value = ''
  comNewPassWord.value = ''
  isForgetPassword.value = false
  nextBtn.value = false

  uni.setNavigationBarTitle({
    title: $t('userLogin.userLogin')
  })
}

let timer = null
const count = ref('')
/**
 * 获取验证码
 */
const onGetCode = () => {
  if (!principal.value.trim()) {
    errorTips.value = 8
    return
  }
  // 判断手机号码格式是否正确
  if (!util.checkPhoneNumber(principal.value)) {
    errorTips.value = 1
    return
  }
  errorTips.value = 0
  const params = {
    url: isForgetPassword.value ? '/tmerclub_biz/ua/sms/verification_code/update_pwd' : '/tmerclub_biz/ua/sms/verification_code/login_code',
    method: 'put',
    selfLoading: true,
    data: {
      mobile: principal.value
    }
  }
  http.request(params).then(() => {
    startInterval()
  })
}

/**
 * 倒计时
 */
const startInterval = () => {
  const entryTime = parseInt(new Date().getTime() / 1000) // 进入页面得当前时间
  let currentTime = 0 // 当前时间
  const maxtime = 60 // 传入秒钟 = 最多走几秒
  count.value = maxtime
  show.value = false
  timer = setInterval(() => {
    currentTime = parseInt(new Date().getTime() / 1000) // 在定时器里面每隔一秒记录当前时间；
    const TimeDifference = (currentTime - entryTime) // 时间差
    const mytime = maxtime - TimeDifference // 传入的秒数 - 已经走掉的秒数  = 当前还剩多少秒数
    if (TimeDifference <= maxtime) { // 如果已经走掉的秒数 小于等于  传入的秒数
      count.value = Math.floor(mytime % 60)
    } else {
      clearInterval(timer)
      timer = null
      show.value = true
    }
  }, 1000)
}

let checkUpdatePwdSmsFlag = '' // 校验验证码成功的标识
/**
 *  修改密码（下一步）
 */
const onNextStep = () => {
  if (!principal.value.trim()) {
    errorTips.value = 8
    return
  }
  if (!util.checkPhoneNumber(principal.value)) {
    errorTips.value = 1
    return
  }
  if (!validCode.value.trim()) {
    // 请输入验证码
    errorTips.value = 3
    return
  }
  errorTips.value = 0
  // 校验验证码
  const params = {
    url: '/tmerclub_biz/ua/sms/verification_code/check_update_pwd',
    method: 'put',
    data: {
      mobile: principal.value,
      validCode: validCode.value
    }
  }
  http.request(params).then((res) => {
    checkUpdatePwdSmsFlag = res
    nextBtn.value = !nextBtn.value
  }).catch((err) => {
    uni.showToast({
      title: err.msg,
      icon: 'none',
      duration: 1500
    })
  })
}
/**
 * 修改密码(确认按钮)
 */
const onChangePassWord = () => {
  if (errorTips.value === 9 || errorTips.value === 10) {
    return
  }
  if (!newPassWord.value) {
    errorTips.value = 4
    return
  }
  if (!newPassWord.value.trim()) {
    errorTips.value = 10
    return
  }
  if (!comNewPassWord.value) {
    errorTips.value = 5
    return
  }
  if (
    comNewPassWord.value &&
    newPassWord.value &&
    comNewPassWord.value !== newPassWord.value
  ) {
    errorTips.value = 7
    identical.value = false
    return
  }
  errorTips.value = 0
  const params = {
    url: '/tmerclub_auth/ua/forget_password',
    method: 'put',
    data: {
      checkUpdatePwdSmsFlag, // 校验登陆注册验证码成功的标识
      mobile: principal.value,
      newPassword: encrypt(newPassWord.value),
      sysType: 0
    }
  }
  http.request(params).then(() => {
    uni.showToast({
      title: '修改成功',
      icon: 'none',
      duration: 1500
    })
    setTimeout(() => {
      isForgetPassword.value = false
      uni.removeStorageSync('cloudToken')
      uni.removeStorageSync('cloudLoginResult')
      uni.removeStorageSync('cloudUserDetails')
      uni.removeStorageSync('cloudExpiresTimeStamp')
      // 变更uuid (数据分析)
      uni.removeStorageSync('cloudOid')
      http.getOid()
      uni.redirectTo({
        url: '/package-user/pages/user-login/user-login'
      })
    }, 1500)
  })
}

</script>
<style scoped lang="scss">
@use "./user-login.scss";
</style>
