<template>
  <section class="market-container">
    <!-- 模板 -->
    <div class="market">
      <search v-model:value="searchValue" @search="fetchTemplate"></search>
      <van-tabs
        v-model:active="active"
        style="margin-top: 15px"
        class="px-1"
        shrink
        duration="0"
        color="#6fb937"
        @change="handleChangeTab"
      >
        <section>
          <van-tab v-for="(item, index) in marketList" :key="item.title" :title="item.h5Title">
            <template #title>
              <!-- <el-icon><el-img :src="item.h5Image" /></el-icon> -->
              <div
                style="
                  display: flex;
                  align-items: center;
                  gap: 5px;
                  padding: 5px 10px;
                  border-radius: 10px;
                "
                :style="{ background: active === index ? '#6fb937' : '' }"
              >
                <!-- 当标签不是处于激活状态的时候，取消图片展示 -->
                <img v-if="active === index" width="15px" height="15px" :src="imgMap(item.code)" />
                <section :style="{ color: active === index ? '#fff' : '#000000' }">
                  {{ item.h5Title }}
                </section>
              </div>
            </template>
          </van-tab>
        </section>
      </van-tabs>
    </div>
    <section v-infinite-scroll="loadData">
      <market-item :info="marketInfo" :marketItem="marketItem" />
    </section>
    <div class="more">
      <p v-if="marketInfo.length === 0 && searchValue">无符合要求结果</p>
      <p v-else>-更多模板期待您的探索-</p>
    </div>
  </section>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue';
import MarketItem from '@/components/MarketItem/MarketItem.vue';
import { getListScene, getSurveyTemplates } from '@/api/home';
import Search from '@/components/Search/Index.vue';
import { imgMap } from '@/utils/imgMap';
import { throttle } from '@/utils/utils';
import { functionsIn } from 'lodash';

const searchParm = {
  index: 1
};
const marketList = ref([]);
const active = ref(null);
const marketIndex = ref(0);
const marketInfo = ref<any[]>([]);
// 当前激活的 item 信息
const marketItem = ref();
// 当前的搜索指
const searchValue = ref('');
let keyword = '';

let loadDataSingle = false;
/**
 * 如果这个搜索框没有值，默认清空 keyword, 然后重新加载列表
 */
watch(searchValue, (value) => {
  if (!value) {
    keyword = '';
    fetchTemplate();
  }
});

const getTableList = async () => {
  const res = await getListScene();
  // 将 tabs 数据存放到 sessionStorage 中
  sessionStorage.setItem('marketList', JSON.stringify(res.data.data));

  if (res.data.code === 0) {
    marketList.value = res.data.data;
  }
};

watch(active, () => {
  console.log(`active change`, active.value);
});

// 开始请求所有 table 的数据
getTableList();

const getMarketInfo = async (item: string | number, title?: string) => {
  marketIndex.value = item as number;

  const data = marketList.value[active.value];

  if (data) {
    const params = {
      page: searchParm.index,
      // 此字段无法脱离组件使用
      keyword,
      per_page: 10,
      group_id: 0,
      is_public: 1,
      scene_code_info: data.code,
      sort: 'quote_nums, desc'
    };

    // 获取相应的 Info 信息
    const res = await getSurveyTemplates(params);
    console.log(`template market res`, res);
    const meta = res.data.meta;
    const { current_page, last_page } = meta;

    if (res.data.code === 0) {
      // marketInfo.value = res.data.data;
      marketInfo.value = [...marketInfo.value, ...res.data.data];
    }
    // 获取对应的 item 信息
    marketItem.value = marketList.value.find((item) => item.h5Title === title);

    // 后置处理. 解构出当前和最后一页内容,然后判断是否相等,如果相等,则取消数据加载
    if (current_page === last_page) {
      loadDataSingle = false;
    } else {
      searchParm.index++;
      loadDataSingle = true;
    }
  }
};

/**
 * 当 table 切换的时候, 重置当前的参数数据
 */
function handleChangeTab() {
  searchParm.index = 1;
  marketInfo.value = [];
  searchData();
}
/**
 * 搜索模板
 * @param keyword 搜索关键词
 */
function fetchTemplate() {
  // 当点击搜索的时候, 重置当前的参数数据
  keyword = searchValue.value;
  handleChangeTab();
}
/**
 * 这个函数负责调用搜索
 */
function searchData() {
  getMarketInfo(marketIndex.value);
}
const debounceFn = throttle(searchData, 500);
function loadData() {
  if (!loadDataSingle) return;
  debounceFn();
}
</script>

<style scoped>
:deep(.van-tabs__line) {
  display: none !important;
}

:deep(.van-tab--active) {
  color: #000;
  font-size: 13px;
}

:deep (.van-row) {
  justify-content: space-between;
}

.market-container {
  .market {
    padding: 20px;
    border-radius: 0 0 16px 16px;
    background-color: #fff;

    .market_title {
      margin-bottom: 5px;
      color: #000;
      font-size: 15px;
    }

    & > :first-child {
      span {
        color: grey;
        font-size: 10px;
      }
    }

    .market_table {
      display: flex;
      flex-flow: row nowrap;
      overflow: scroll;
      height: 20px;
      font-size: 13px;

      /* padding: 10px 0; */

      & > div {
        padding: 0 20px;
        text-wrap: nowrap;
      }
    }
  }
}

.more {
  margin: 20px;
  color: #919191;
  font-weight: 400;
  font-size: 13px;
  text-align: center;
}
</style>
