<script setup>
import { fetchSurveys } from '@/hooks/request/useSurvey';
import CreateSurvey from './components/CreateSurvey/Index.vue';
import NewSurvey from './components/NewSurvey/index.vue';
import { onMounted, ref } from 'vue';
import utils from '@/assets/js/common';
import { getUserInfo } from '@/api/common/index.js';
import { showFailToast } from 'vant';
import appBridge from '@/assets/js/appBridge';
import ImageSlider from './components/ImageSlider/Index.vue';
import SearchBar from '@/components/Search/Index.vue';
import Navigation from '@/components/Navigation/Index.vue';
import HomeRecommend from './components/HomeRecommend/Index.vue';
import MineTask from '@/views/Home/components/MineTask/Index.vue';
import router from '@/router';

const contentShow = ref(false);
// 获取我的问卷数据
const { surveys } = fetchSurveys();
const keyword = ref('');
onMounted(async () => {
  if (appBridge.isInReactNative()) {
    const appToken = utils.getSessionStorage('xToken');
    getUserInfo(appToken)
      .then((res) => {
        if (res.data) {
          contentShow.value = true;
          const token = res.data.data.token;
          localStorage.setItem('plantToken', token);
          utils.setSessionStorage('userInfo', res.data.data);
        } else {
          contentShow.value = false;
          showFailToast(
            error.response.data?.message || error.data?.message || error.message || '服务器错误'
          );
        }
      })
      .catch((error) => {
        contentShow.value = false;
        showFailToast(error?.response?.data?.message || error?.message || '服务器错误');
      });
  } else {
    utils.setSessionStorage('xToken', 'f74ba36d7fc3468480648dedba5672ff');
    contentShow.value = true;
  }
});

function handleSearchClick() {
  router.push({ name: 'search' });
}
</script>

<template>
  <div v-if="contentShow" class="container-home">
    <div class="container-body">
      <!-- 搜索栏 -->
      <section class="search">
        <search-bar placeholder="请输入关键词" :value="keyword" @click="handleSearchClick" />
      </section>
      <!-- 首页轮播图 -->
      <section class="slider">
        <image-slider />
      </section>
      <create-survey :createdNewPage="false" />
      <!-- 最新问卷 -->
      <!--<last-survey/>-->
      <!-- 模板市场 -->
      <!-- <Market/> -->
      <!--底部新建问卷-->
      <NewSurvey />

      <!-- 我的问卷 部分， 当问卷不存在时，显示推荐内容 -->
      <mine-task v-if="surveys?.length > 0" :surveys="surveys" />
      <home-recommend v-else class="home_recommend" />
      <navigation />
    </div>
  </div>
</template>

<style scoped lang="scss">
@use '@/assets/css/theme';

.container-body {
  padding: 0 10px 80px;
}

.search {
  margin: 0 -10px 0 -10px;
  padding: 10px;
  @extend %search-gradient;
}

.slider {
  overflow: hidden;
  border-radius: theme.$card-radius;
}

.home_recommend {
  margin: theme.$gap 0;
}
</style>
