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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j page-login login-con">
    <view class="welcome">
      {{ $t('huanYingDengLu') }}
    </view>
    <view class="shop-name">
      {{ configuration.bsTitleContent }}
    </view>
    <view class="form">
      <uni-forms ref="loginFormRef">
        <uni-forms-item name="userName">
          <uni-easyinput
            v-model="dataForm.userName"
            class="form-item"
            :class="errorTips === 1 ? 'error-border' : ''"
            type="text"
            :placeholder="$t('yongHuMingShouJiHao')"
            place
            @focus="handleInpFocus(1)"
          />
          <view
            v-if="errorTips === 1"
            class="error-text"
          >
            {{ $t('qingShuRuYongHuMingShouJiHao') }}
          </view>
        </uni-forms-item>
        <uni-forms-item name="password">
          <uni-easyinput
            v-model="dataForm.password"
            class="form-item"
            :class="errorTips === 2 ? 'error-border' : ''"
            type="password"
            :placeholder="$t('miMa')"
            @focus="handleInpFocus(2)"
            @confirm="submit()"
          />
          <view
            v-if="errorTips === 2"
            class="error-text"
          >
            {{ $t('qingShuRuMiMa') }}
          </view>
        </uni-forms-item>
      </uni-forms>
    </view>
    <button
      class="login-btn"
      type="default"
      hover-class="none"
      @tap="submit()"
    >
      {{ $t('dengLu') }}
    </button>
    <view
      class="find-pwd"
      @tap="findPwd()"
    >
      {{ $t('wangJiMiMa') }}
    </view>
    <view class="footer">
      <view class="copy-right">
        {{ $t('zhuCeShangJiaZhangHaoQingQianWangPcDuanZhuCe') }}
      </view>
      <view class="copy-right">
        {{ merchantPlatformUrl }}
      </view>
    </view>

    <verify
      ref="verifyRef"
      :mode="'pop'"
      captcha-type="blockPuzzle"
      :v-space="15"
      :img-size="{ width: '320px', height: '160px' }"
      @success="login"
    />
  </view>
</template>

<script setup>
import { encrypt } from '@/utils/crypto'

const { getWuKongIm, clearLoginInfo } = util
const userStore = useUserStore()
// 商家端PC域名
const merchantPlatformUrl = ref(null)
const dataForm = reactive({
  userName: '',
  password: '',
  uuid: '',
  captcha: ''
})
const errorTips = ref(0)
// 网站配置信息
const configuration = ref({})
onShow(() => {
  // 请求后台配置信息
  getWebConfig()
  uni.setNavigationBarTitle({
    title: $t('dengLu')
  })
})
onMounted(() => {
  merchantPlatformUrl.value = import.meta.env.VITE_APP_MERCHANT_PKATFORM_URL
})
/**
 * 获取后台商家端配置信息
 */
const getWebConfig = () => {
  const params = {
    url: '/sys/webConfig/getActivity',
    method: 'GET'
  }
  http.request(params).then(({ data: res }) => {
    res.bsTitleContentCn = res.bsTitleContentCn || $t('lanHaiShangJiaDuan')
    res.bsTitleContentEn = res.bsTitleContentEn || 'LANHAI-Shop'
    configuration.value = res
  })
}
const verifyRef = ref(null)
/**
 * 触发提交表单
 */
const submit = () => {
  if (dataForm.userName.trim() === '') {
    errorTips.value = 1
  } else if (dataForm.password.trim() === '') {
    errorTips.value = 2
  } else {
    errorTips.value = 0
    verifyRef.value?.show()
  }
}

/**
 * 输入框聚焦
 */
const handleInpFocus = (i) => {
  if (errorTips.value === i) {
    errorTips.value = 0
  }
}

/**
 * 找回密码
 */
const findPwd = () => {
  uni.navigateTo({
    url: '/package-settings/pages/find-pwd/find-pwd'
  })
}

const loginFormRef = ref(null)
/**
 * 登录
 */
const login = (verifyResult) => {
  loginFormRef.value?.validate().then(() => {
    // uni.showLoading()
    const params = {
      url: '/shopLogin',
      method: 'POST',
      data: {
        captchaVerification: verifyResult.captchaVerification,
        passWord: encrypt(dataForm.password),
        userName: dataForm.userName,
        shopLoginType: 0
      }
    }
    http.request(params).then(async (data) => {
      uni.hideLoading()
      if (data.code !== '00000') {
        uni.showToast({
          title: data.msg,
          icon: 'none',
          duration: 1500
        })
        return
      }
      const { data: res } = data
      uni.setStorageSync('bbcToken_us', res.accessToken)
      uni.setStorageSync('bbcLoginResult', res) // 保存整个登录数据
      let user
      try {
        user = await userStore.login()
        getWuKongIm()
        // user = await $store.dispatch('user/login')
        // 重置菜单路由
        // router.options.isAddDynamicMenuRoutes = false
      } catch (error) {
        return
      }
      if (user.shopStatus === 4 || user.shopStatus === 5 || user.isPassShop === 0) {
        // 未开店，跳转申请开店
        // await $router.replace({name: 'shopProcess'})
        clearLoginInfo()
        uni.showModal({
          title: $t('tiShi'),
          content: $t('qingZaiPcDuanXianWanChengKaiDianShenQing'),
          showCancel: false,
          success (res) {
            if (res.confirm) {
              clearLoginInfo()
            }
          }
        })
      } else {
        const payTypeParams = {
          url: '/sys/config/paySettlementType',
          method: 'get'
        }
        http.request(payTypeParams).then(({ data }) => {
          if (data) {
            const paySettlementType = JSON.parse(data).paySettlementType
            uni.setStorageSync('bbcPaySettlementType', paySettlementType)
          }
          // 已开店，跳转首页
          uni.switchTab({
            url: '../index/index'
          })
        })
      }
    })
  })
}
</script>

<style lang="scss" scoped>
@use './login.scss';
</style>
