<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useTagsViewStore } from "@/store/modules/tags-view"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import { getToken } from "@/utils/cache/cookies"

const route = useRoute()
const tagsViewStore = useTagsViewStore()
const router = useRouter()
const user = useUserStore()
const storeInformation = ref<{ name: string; phone: string }>({ name: "", phone: "00000000000" })
const storeInformationForm = ref<FormInstance>()
const need = ref<boolean>(false)
const waiting = ref<boolean>(false)

const key = computed(() => {
  return route.path
})
const valueRules: FormRules = {
  name: [
    { required: true, message: "请输入店铺名", trigger: "blur" },
    { min: 3, max: 25, message: "长度在 3 到 25 个字符", trigger: "blur" },
    { pattern: "[A-Za-z0-9_-一-龥]+", message: "店铺名不符合要求" }
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { len: 11, message: "手机号长度为11", trigger: "blur" }
  ]
}
const upload = () => {
  if (!storeInformationForm.value?.validate()) {
    ElMessage.error("数据存在错误！")
    return
  }
  webSocket.value?.send(
    JSON.stringify({
      type: "addVerifyInfo",
      verifyName: storeInformation.value.name,
      verifyPhone: storeInformation.value.phone
    })
  )
  ElMessage.warning("正在上传，请稍后...")
}
const webSocket = ref<WebSocket>()
const timerId = ref<number>()
onMounted(() => {
  if (user.roleId === 5) {
    webSocket.value = new WebSocket(
      import.meta.env.VITE_BASE_API.replace("http", "ws").replace("https", "wss") + "/api/auth/websocket/" + getToken()
    )
    webSocket.value.onclose = () => {
      ElMessage.error("WebSocket连接被顿开，已登出，请尝试重新登录或联系网站管理员！")
      user.logout()
      router.push("/login")
    }
    webSocket.value.onmessage = (evt: MessageEvent) => {
      const data = JSON.parse(evt.data)
      console.log(data)
      if (data.data.info == "pong") {
        if (data.data.time == -2) {
          if (!need.value) {
            ElMessage.warning("请提交店铺消息！")
            need.value = true
          }
        }
      }
      if (data.data.info == "验证信息添加成功,请耐心等待管理员审核") {
        ElMessage.success(data.data.info)
        waiting.value = true
      }
      if (data.data.info == "管理员未同意你的验证信息,你可以重新进行验证") {
        ElMessage.error(data.data.info)
        waiting.value = false
      }
    }
    webSocket.value.onerror = (evt) => {
      console.log(evt)
      ElMessage.error("WebSocket连接出现错误，已自动断开并登出，请尝试重新登录或联系网站管理员！")
      if (!webSocket.value?.CLOSING) {
        webSocket.value?.close()
      }
    }
    timerId.value = window.setInterval(() => {
      webSocket.value?.send(JSON.stringify({ type: "ping" }))
      webSocket.value?.send(JSON.stringify({ type: "getTime" }))
    }, 1000)
  }
})
onUnmounted(() => {
  if (!webSocket.value?.CLOSING) {
    webSocket.value?.close()
  }
  if (timerId.value) {
    window.clearInterval(timerId.value)
  }
})
</script>

<template>
  <section class="app-main">
    <div v-if="user.roleId === 5 && need && false" style="margin: 10px 10px 10px 10px">
      <div style="width: 30%; margin-top: 10px">
        <el-form :model="storeInformation" :rules="valueRules" title="店铺信息" ref="storeInformationForm">
          <el-form-item prop="name" label="店铺名称">
            <el-input v-model="storeInformation.name" />
          </el-form-item>
          <el-form-item prop="phone" label="手机号">
            <el-input v-model="storeInformation.phone" />
          </el-form-item>
        </el-form>
      </div>
      <el-button type="success" :disabled="waiting" @click="upload">提交</el-button>
    </div>
    <router-view v-slot="{ Component }" v-else>
      <transition name="fade-transform" mode="out-in">
        <keep-alive :include="tagsViewStore.cachedViews">
          <component :is="Component" :key="key" />
        </keep-alive>
      </transition>
    </router-view>
  </section>
</template>

<style lang="scss" scoped>
.app-main {
  min-height: calc(100vh - var(--v3-navigationbar-height));
  width: 100%;
  position: relative;
  overflow: hidden;
  background-color: var(--v3-body-bg-color);
}

.fixed-header + .app-main {
  padding-top: var(--v3-navigationbar-height);
  height: 100vh;
  overflow: auto;
}

.hasTagsView {
  .app-main {
    min-height: calc(100vh - var(--v3-header-height));
  }
  .fixed-header + .app-main {
    padding-top: var(--v3-header-height);
  }
}
</style>
