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

https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j page-find-pwd">
    <view class="welcome">
      {{ registerStep === 1 ? $t('wangJiMiMa-0') : $t('sheZhiMiMa') }}
    </view>
    <view class="shop-name">
      {{ configuration.bsTitleContent }}
    </view>
    <view class="form">
      <!-- 校验验证码 -->
      <uni-forms
        v-if="registerStep === 1"
        ref="loginForm"
      >
        <uni-forms-item name="mobile">
          <!-- <uni-easyinput v-model="dataForm.userName" type="text" placeholder="手机号" place /> -->
          <view class="account">
            <uni-easyinput
              :key="1"
              v-model="dataForm.mobile"
              maxlength="11"
              :class="[errorTips === 1 || errorTips === 2 ? 'error-border' : '', 'int-yzm']"
              type="text"
              placeholder-class="inp-palcehoder"
              :placeholder="$t('shouJiHao')"
              @focus="handleInpFocus(1)"
            />
          </view>
          <view
            v-if="errorTips === 1"
            class="error-text"
          >
            <!-- <text class="warning-icon">!</text> -->
            {{ $t('qingShuRuShouJiHao') }}
          </view>
          <view
            v-if="errorTips === 2"
            class="error-text"
          >
            <!-- <text class="warning-icon">!</text> -->
            {{ $t('qingShuRuZhengQueShouJiHao') }}
          </view>
        </uni-forms-item>
        <uni-forms-item name="validCode">
          <view :class="[errorTips === 3 ? 'error-border' : '', 'account']">
            <uni-easyinput
              :key="2"
              v-model="dataForm.validCode"
              type="text"
              class="int-yzm"
              placeholder-class="inp-palcehoder"
              :placeholder="$t('yanZhengMa')"
              maxlength="6"
              @focus="handleInpFocus(3)"
            />
            <text
              v-if="show"
              class="input-item"
              @click="showCheck"
            >
              {{ $t('huoQuYanZhengMa') }}
            </text>
            <text
              v-if="!show"
              class="input-item getcode"
            >
              {{ count }} s
            </text>
          </view>
          <view
            v-if="errorTips === 3"
            class="error-text"
          >
            <!-- <text class="warning-icon">!</text> -->
            {{ $t('qingShuRuYanZhengMa') }}
          </view>
        </uni-forms-item>
      </uni-forms>
      <!-- 修改密码 -->
      <uni-forms
        v-if="registerStep === 2"
        ref="loginForm"
      >
        <uni-forms-item
          v-if="isEdit"
          name="password"
        >
          <!-- <uni-easyinput v-model="dataForm.userName" type="text" placeholder="手机号" place /> -->
          <view class="account">
            <uni-easyinput
              :key="5"
              v-model="dataForm.oldpassword"
              :class="[errorTips === 4 ? 'error-border' : '', 'int-yzm']"
              type="password"
              placeholder-class="inp-palcehoder"
              :placeholder="$t('yuanMiMa')"
              @focus="handleInpFocus(4)"
              @blur="dataForm.oldpassword = dataForm.oldpassword.replace(/\s/g, '')"
            />
          </view>
          <view
            v-if="errorTips === 4"
            class="error-text"
          >
            <!-- <text class="warning-icon">!</text> -->
            {{ $t('qingShuRuYuanMiMa') }}
          </view>
        </uni-forms-item>
        <uni-forms-item name="password">
          <!-- <uni-easyinput v-model="dataForm.userName" type="text" placeholder="手机号" place /> -->
          <view class="account">
            <uni-easyinput
              :key="3"
              v-model="dataForm.password"
              :class="[errorTips === 1 ? 'error-border' : '', 'int-yzm']"
              type="password"
              maxlength="20"
              placeholder-class="inp-palcehoder"
              :placeholder="$t('sheZhiXinMiMa')"
              @focus="handleInpFocus(1)"
              @blur="dataForm.password = dataForm.password.replace(/\s/g, '')"
            />
          </view>
          <view
            v-if="errorTips === 1"
            class="error-text"
          >
            {{ $t('qingShuRuMiMa') }}
          </view>
          <view
            v-if="errorTips === 7"
            class="error-text"
          >
            {{ passwordTip }}
          </view>
        </uni-forms-item>
        <uni-forms-item name="valPassword">
          <view class="account">
            <uni-easyinput
              :key="4"
              v-model="valPassword"
              :class="[errorTips === 2 ? 'error-border' : '', 'int-yzm']"
              type="password"
              maxlength="20"
              placeholder-class="inp-palcehoder"
              :placeholder="$t('zhongFuXinMiMa')"
              @focus="handleInpFocus(2)"
              @blur="valPassword = valPassword.replace(/\s/g, '')"
            />
          </view>
          <view
            v-if="errorTips === 2"
            class="error-text"
          >
            <!-- <text class="warning-icon">!</text> -->
            {{ $t('liangCiMiMaBuYiZhi') }}
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <button
      class="login-btn button"
      type="default"
      hover-class="none"
      @tap="submit()"
    >
      {{ registerStep === 1 ? $t('xiaYiBu') : $t('wanCheng') }}
    </button>
    <!-- <button class="login-btn" type="default" hover-class="none" @tap="submit()">下一步</button> -->
    <view
      v-if="!isEdit"
      class="footer"
    >
      <!-- <view v-if="registerStep === 2" class="back" @tap="back()">上一步</view> -->
      <view
        class="find-pwd"
        @tap="toLogin()"
      >
        {{ $t('yiYouZhangHuQianQuDengLu') }}
      </view>
    </view>

    <view
      v-if="showSuccess"
      class="set-pwd-s"
    >
      <image
        class="set-pwd-img"
        src="../../static/images/set-pwd-s.png"
      />
      <view class="set-pwd-tit">
        {{ $t('gongXiNinMiMaXiuGaiChengGong') }}
      </view>
      <view class="set-pwd-tip">
        {{ $t('secondsHouZiDongTiaoZhuan').replace('[second]', second) }}
      </view>
    </view>
    <view
      v-if="showSuccess"
      class="mask"
    />
    <verify
      ref="verifyRef"
      :mode="'pop'"
      captcha-type="blockPuzzle"
      :v-space="15"
      :img-size="{ width: '320px', height: '160px' }"
      @success="getCode"
    />
  </view>
</template>

<script setup>
import { reactive } from 'vue'
import { validPassword } from '@/utils/validate.js'

const Data = reactive({
// 商家端PC域名
  merchantPlatformUrl: import.meta.env.VITE_APP_MERCHANT_PKATFORM_URL,
  dataForm: {
    mobile: '',
    validCode: '',
    password: '',
    oldpassword: ''
  },
  valPassword: '',
  errorTips: 0,
  registerStep: 1,
  count: '',
  timer: null,
  show: true,
  isSubmit: false,
  showSuccess: false,
  checkRegisterSmsFlag: '',
  second: 3,
  isEdit: false,
  passwordTip: '',
  // 网站配置信息
  configuration: {}
})

const { dataForm, valPassword, errorTips, registerStep, count, show, showSuccess, second, isEdit, passwordTip, configuration } = toRefs(Data)

onLoad((options) => {
  if (options.edit) {
    Data.registerStep = 2
    Data.isEdit = true
    uni.setNavigationBarTitle({
      title: $t('sheZhiMiMa-0')
    })
  }
})

onShow(() => {
// 请求后台配置信息
  getWebConfig()
  uni.setNavigationBarTitle({
    title: $t('xiuGaiMiMa')
  })
})

/**
* 获取后台商家端配置信息
*/
const getWebConfig = () => {
  http.request({
    url: '/sys/webConfig/getActivity',
    method: 'GET'
  }).then(({ data }) => {
    data.bsTitleContentCn = data.bsTitleContentCn || $t('lanHaiShangJiaDuan')
    data.bsTitleContentEn = data.bsTitleContentEn || 'LANHAI-Shop'
    Data.configuration = data
  })
}

/**
* 触发提交表单
*/
const calibration = (isvCode = true) => {
  if (Data.registerStep === 1) {
    if (Data.dataForm.mobile.trim() === '') {
      Data.errorTips = 1
      return false
    } else if (!isMobile(Data.dataForm.mobile)) {
      Data.errorTips = 2
      return false
    } else if (Data.dataForm.validCode.trim() === '' && isvCode) {
      Data.errorTips = 3
      return false
    } else {
      Data.errorTips = 0
      // Data.$refs.verify.show()
      return true
    }
  } else {
    if (Data.dataForm.oldpassword.trim() === '' && Data.isEdit) {
      Data.errorTips = 4
      return false
    } else if (Data.dataForm.password.trim() !== Data.valPassword.trim()) {
      Data.errorTips = 2
      return false
    } else if (Data.dataForm.password.trim() === '') {
      Data.errorTips = 1
      return false
    } else {
      Data.errorTips = 0
      if (passwordVerify()) return false
      return true
    }
  }
}

const passwordVerify = () => {
  if (!validPassword(Data.valPassword)) {
    Data.errorTips = 7
    Data.passwordTip = $t('miMaYouZiMuShuZiHeTeShuFuHaoSanZhongZiFuZuCheng_820WeiBanJiaoZiFuQuFenDaXiaoXie')
    return true
  }
  return false
}
const verifyRef = ref(null)
const showCheck = () => {
  if (calibration(false)) {
    verifyRef.value?.show()
  }
}
/**
* 获取验证码
*/
const getCode = (verifyResult) => {
  Data.MobileEmpty = false
  http.request({
    url: '/shop/shopUserRegister/sendUpdatePwdCode',
    method: 'post',
    data: {
      mobile: Data.dataForm.mobile,
      shopAccount: 1, // 是否店铺账号： 1是
      captchaVerification: verifyResult.captchaVerification
    }
  }).then(() => {
    const timeCount = 60
    if (!Data.timer) {
      Data.count = timeCount
      Data.show = false
      Data.timer = setInterval(() => {
        if (Data.count > 0 && Data.count <= timeCount) {
          Data.count--
        } else {
          clearInterval(Data.timer)
          Data.timer = null
          Data.show = true
        }
      }, 1000)
    }
  })
}

/**
* 校验验证码
*/
const checkValidCode = () => {
  if (calibration()) {
    // 校验验证码
    http.request({
      url: '/shop/shopUserRegister/checkUpdatePwdSms',
      method: 'put',
      data: {
        mobile: Data.dataForm.mobile,
        validCode: Data.dataForm.validCode,
        shopAccount: 1
      }
    }).then(({ data }) => {
      Data.checkRegisterSmsFlag = data
      Data.dataForm.password = ''
      Data.valPassword = ''
      Data.registerStep = 2
    })
  }
}

// 提交表单
const dataFormSubmit = () => {
  if (calibration(false)) {
    if (Data.isSubmit) {
      return
    }
    Data.isSubmit = true
    http.request({
      url: '/shop/shopUserRegister/updatePwd',
      method: 'put',
      data: {
        password: encrypt(Data.dataForm.password),
        mobile: Data.dataForm.mobile,
        validCode: Data.dataForm.validCode,
        checkRegisterSmsFlag: Data.checkRegisterSmsFlag,
        shopAccount: 1
      }
    }).then(() => {
      Data.showSuccess = true
      const t = setInterval(() => {
        Data.second--
        if (Data.second === 0) {
          Data.showSuccess = false
          clearInterval(t)
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }, 1000)
      Data.isSubmit = false
    }).catch(err => {
      uni.showToast({
        title: err.data.data || err.data.msg,
        icon: 'none'
      })
      Data.isSubmit = false
    })
  }
}

// 修改密码
const editPassword = () => {
  if (calibration(false)) {
    if (Data.isSubmit) {
      return
    }
    Data.isSubmit = true
    http.request({
      url: '/sys/shopEmployee/password',
      method: 'post',
      data: {
        newPassword: encrypt(Data.dataForm.password),
        password: encrypt(Data.dataForm.oldpassword)
      }
    }).then(() => {
      Data.showSuccess = true
      const t = setInterval(() => {
        Data.second--
        if (Data.second === 0) {
          Data.showSuccess = false
          clearInterval(t)
          uni.navigateTo({
            url: '/pages/login/login'
          })
        }
      }, 1000)
      Data.isSubmit = false
    }).catch(err => {
      uni.showToast({
        title: err?.msg,
        icon: 'none'
      })
      Data.isSubmit = false
    })
  }
}

const submit = () => {
  if (Data.registerStep === 1) {
    checkValidCode()
  } else if (Data.registerStep === 2) {
    if (Data.isEdit) {
      editPassword()
    } else {
      dataFormSubmit()
    }
  }
}

// 去登录
const toLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

const handleInpFocus = (i) => {
  if (Data.registerStep === 1) {
    if (Data.errorTips === i || (i === 1 && Data.errorTips === 2)) {
      Data.errorTips = 0
    }
  } else if (Data.registerStep === 2) {
    if (Data.errorTips === i) {
      Data.errorTips = 0
    }
  }
}
</script>

<style lang="scss" scoped>
@use "find-pwd";
</style>
