<template>
  <a-spin tip="Loading..." :spinning="spinningLoading">
    <div class="pro-layout">
      <Avatar @resetAll="resetAll" />
      <div class="content">
        <router-view v-if="!spinningLoading" />
      </div>
    </div>
  </a-spin>
</template>
<script>
import Avatar from "./components/Avatar.vue";
//import Top from './components/Top.vue';
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import UpdateUser from "./components/UpdateUser.vue";
import { computed, defineComponent, ref } from "vue";
import { jsonp } from "vue-jsonp";
import { loginIn } from "../Login/api.js";
import { jsonpUrl } from "../../config.js";
export default defineComponent({
  components: {
    Avatar,
    // UpdateUser,
  },
  setup() {
    const router = useRouter();
    const store = useStore();
    const pwdVisible = ref(false);
    function showPwd() {
      pwdVisible.value = true;
    }
    function changeVisible(val) {
      pwdVisible.value = val;
    }
    const token = computed(() => store.state.common.token);
    try {
      localStorage.setItem("plantIp", returnCitySN["cip"]);
    } catch (error) {
      localStorage.setItem("plantIp", "");
    }
    const spinningLoading = ref(false);
    const resetAll = () => {
      spinningLoading.value = true;
      setTimeout(() => {
        spinningLoading.value = false;
      }, 1000);
      const initHomeData = store.state.common.initHomeData;
      store.dispatch("common/initHomeData", !initHomeData);
      console.log(store.state.common.initHomeData);
    };
    const login = async () => {
      spinningLoading.value = true;
      try {
        const { data } = await loginIn();
        localStorage.setItem("plantUserInfo", JSON.stringify(data));
        localStorage.setItem("plantId", JSON.stringify(data.id));
        store.commit("common/M_COMMON_SET_USERINFO", JSON.stringify(data));
      } catch (error) {
        this.$message.error(
          error.data?.message || error.message || "服务器错误"
        );
      }
      spinningLoading.value = false;
    };
    const getToken = () => {
      spinningLoading.value = true;
      jsonp(jsonpUrl, {
        appId: "yls",
        remoteIp: returnCitySN["cip"],
        callbackQuery: "jsonpCallback",
      })
        .then((res) => {
          spinningLoading.value = false;
          localStorage.setItem("plantToken", res.data.tokenid);
          store.commit("common/M_COMMON_SET_TOKEN", res.data.tokenid);
          login();
        })
        .catch(() => {
          console.log("错误");
          spinningLoading.value = false;
        });
    };
    if (!router.options.history.state.back) {
      getToken();
    }
    return {
      spinningLoading,
      resetAll,
      showPwd,
      changeVisible,
      pwdVisible,
    };
  },
});
</script>
<style lang="scss" scoped>
.pro-layout {
  height: 100%;
  .content {
    padding: 24px;
  }
}
</style>
