<template>
  <div class="w-full min-h-screen bg-white font-['PingFang-SC']">
    <div class="w-full min-h-[180px] relative flex items-center md:h-[380px]">
      <div
        class="w-full h-full bg-[url('/src/assets/images/top_bg.png')] bg-no-repeat bg-center bg-cover absolute left-0 top-0 z-0"
      ></div>
      <div class="relative z-1 p-4 w-full md:w-[780px] m-auto">
        <div
          class="font-['PingFang-Heavy'] px-3 font-semibold text-xl md:text-[32px] md:leading-tight"
        >
          工具数字化展示
        </div>
        <div class="w-full md:w-[600px]">
          <van-search
            class="font-semibold"
            v-model="searchValueRef"
            placeholder="搜索工具名称"
            background="transparent"
            input-align="left"
            left-icon=""
            right-icon="search"
            @search="
              () => {
                handleSearch()
              }
            "
            @clear="handleClear"
            @click-right-icon="
              () => {
                handleSearch()
              }
            "
          />
        </div>
        <div class="w-full text-xs px-4 flex">
          <div class="flex items-start font-semibold">
            <img src="/src/assets/images/huore.png" alt="" />
            <span class="ml-1">常用工具：</span>
          </div>
          <div class="flex-1 flex flex-wrap">
            <div
              class="ml-2 mb-2 font-semibold md:ml-4 md:cursor-pointer md:hover:text-[#004EA2]"
              v-for="tool in hotToolsRef"
              :key="tool.id"
              @click="handleKeySearch(tool.toolName)"
            >
              {{ tool.toolName }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="w-full px-4 py-2 md:py-6">
      <div class="w-full p-2 min-h-[42px] m-auto md:max-w-[1440px] md:min-h-[52px]">
        <van-sticky :offset-top="0">
          <div v-if="device === 'phone'" class="w-full">
            <van-dropdown-menu class="font-semibold">
              <van-dropdown-item
                v-model="type1ValueRef"
                :options="dropdownTypeOptions1"
                :title="type1DropMenuTextRef === '全部' ? '一级分类' : type1DropMenuTextRef"
                @change="handleChangeDropdownOfType1"
              />
              <van-dropdown-item
                v-model="type2ValueRef"
                :options="dropdownTypeOptions2"
                :title="type2DropMenuTextRef === '全部' ? '二级分类' : type2DropMenuTextRef"
                @change="handleChangeDropdownOfType2"
              />
            </van-dropdown-menu>
          </div>
          <div
            class="border shadow-sm rounded-sm text-xs text-[#181819] font-semibold bg-white"
            v-else
          >
            <div class="menu-box border-b-[1px]">
              <div>一级分类：</div>
              <div class="menu-content">
                <div
                  class="menu-item"
                  :class="[typeItem.id === type1ValueRef ? 'active' : '']"
                  v-for="typeItem in typeOptions1Ref"
                  :key="typeItem.id"
                  @click="handleChangeDropdownOfType1(typeItem.id)"
                >
                  {{ typeItem.toolName }}
                </div>
              </div>
            </div>
            <div class="menu-box">
              <div>二级分类：</div>
              <div class="menu-content">
                <div
                  class="menu-item"
                  :class="[typeItem.id === type2ValueRef ? 'active' : '']"
                  v-for="typeItem in typeOptions2Ref"
                  :key="typeItem.id"
                  @click="handleChangeDropdownOfType2(typeItem.id)"
                >
                  {{ typeItem.toolName }}
                </div>
              </div>
            </div>
          </div>
        </van-sticky>
      </div>
    </div>
    <van-list
      v-model:loading="loadingRef"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div class="w-full px-4">
        <div class="tool-card-content w-full flex flex-wrap mx-auto md:max-w-[1440px]">
          <div
            class="tool-card"
            v-for="item in toolsListRef"
            :key="item"
            @click="handleDetail(item)"
          >
            <el-image class="tool-img" :src="`${devPath + item.picturePath}`" fit="contain">
              <template #error>
                <div class="w-full h-full flex items-center justify-center">
                  <van-icon name="photo-fail" color="#dcdee0" size="32" />
                </div>
              </template>
            </el-image>
            <div class="px-3 pt-2 flex-1 flex flex-col">
              <div class="font-[PingFang-Heavy] truncate">{{ item.toolName }}</div>
              <div class="text-[#585F66] text-xs mt-1 line-clamp-2 break-all">
                {{ item.describe }}
              </div>
              <div class="flex-1 flex items-center justify-end" v-if="+item.toolNum">
                <span class="text-2xl font-['DIN'] font-semibold text-[#004EA2]">{{
                  item.toolNum
                }}</span>
                <span class="text-sm font-['PingFang-Heavy'] font-semibold ml-1 text-[#004EA2]"
                  >件</span
                >
              </div>
            </div>
          </div>
          <div class="tool-card-none" v-for="item in noneCardNum" :key="item"></div>
        </div>
      </div>
    </van-list>
    <van-back-top />
  </div>
</template>

<script setup name="HomeView">
import { ref, computed } from 'vue'
import useAppStore from '@/stores/app.js'
import { getFillNums } from '@/utils'
import { listTools, setCommonTool, getCommonTool } from '@/api/index.js'
import { useRoute, useRouter } from 'vue-router'

const devPath = import.meta.env.VITE_APP_BASE_API
const router = useRouter()
const route = useRoute()

const appStore = useAppStore()
// 当前设备类型
const device = computed(() => {
  return appStore.device
})
// 搜索内容
const searchValueRef = ref('')
const pageNum = ref(1)
const pageSize = ref(20)
// 热门工具列表
const hotToolsRef = ref([])

const type1ValueRef = ref('')
const type2ValueRef = ref('')
// 下拉选择的文本
const type1DropMenuTextRef = ref('全部')
const type2DropMenuTextRef = ref('全部')
// 分类列表1级
const typeOptions1Ref = ref([])
// 分类列表2级
const typeOptions2Ref = ref([])
const dropdownTypeOptions1 = computed(() => {
  const list = typeOptions1Ref.value.map((item) => ({
    text: item.toolName,
    value: item.id
  }))
  list.unshift({
    text: '全部',
    value: ''
  })
  return list
})
const dropdownTypeOptions2 = computed(() => {
  const list = typeOptions2Ref.value.map((item) => ({
    text: item.toolName,
    value: item.id
  }))
  list.unshift({
    text: '全部',
    value: type1ValueRef.value
  })
  return list
})

const toolsListRef = ref([])
const loadingRef = ref(false)
const finished = ref(false)
// 末尾补齐的个数
const noneCardNum = ref(0)
const onLoad = (value) => {
  listTools({
    level: '3',
    // 优先级，指定的 parentId > 二级分类 id > 一级分类 id > null
    parentId: value || type2ValueRef.value || type1ValueRef.value || null,
    toolName: searchValueRef.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    delFlag: 0
  }).then((res) => {
    if (pageNum.value === 1) {
      toolsListRef.value = res.rows
      pageNum.value = 2
    } else {
      toolsListRef.value = toolsListRef.value.concat(res.rows)
      pageNum.value += 1
    }
    //  加载状态结束
    loadingRef.value = false
    if (res.rows.length < pageSize.value) finished.value = true
    else finished.value = false
    getFillNums('.tool-card-content', toolsListRef.value, device.value === 'pc' ? 220 : 165).then(
      (nums) => {
        // console.log('getFillNums', nums)
        noneCardNum.value = nums
      }
    )
  })
}
const getType2Tools = (value) => {
  listTools({
    level: '2',
    parentId: value,
    pageSize: 65535
  }).then((res) => {
    typeOptions2Ref.value = res.rows
  })
}

const init = () => {
  loadingRef.value = true
  // 一级分类
  listTools({
    level: '1',
    pageSize: 65535
  }).then((res) => {
    typeOptions1Ref.value = res.rows
  })
  type1ValueRef.value = route.query.id ? Number(route.query.id) : ''
  type2ValueRef.value = ''
  if (type1ValueRef.value) {
    getType2Tools(type1ValueRef.value)
  }
  onLoad(route.query.id)
  // 常用工具列表
  getCommonTool().then((res) => {
    hotToolsRef.value = res.data.data.length > 10 ? res.data.data.slice(0, 10) : res.data.data
  })
}

// 搜索
const handleSearch = (pId = '') => {
  if (loadingRef.value) return
  pageNum.value = 1
  // toolsListRef.value = []
  onLoad(pId)
  // 每次搜索时存一下搜索内容的次数，方便后台统计常用工具
  searchValueRef.value && setCommonTool({ toolName: searchValueRef.value })
}
// 点击热门关键字搜索
const handleKeySearch = (toolName) => {
  searchValueRef.value = toolName
  handleSearch()
}

// 点击一级菜单
const handleChangeDropdownOfType1 = (value) => {
  if (loadingRef.value) return
  // 取消勾选
  if (type1ValueRef.value === value && device.value === 'pc') {
    type1ValueRef.value = ''
    type2ValueRef.value = ''
    typeOptions2Ref.value = []
    handleSearch()
  } else {
    type1ValueRef.value = value
    if (device.value === 'phone') {
      type2DropMenuTextRef.value = '全部'
      const targetOfDropDownItem = dropdownTypeOptions1.value.find((item) => item.value == value)
      type1DropMenuTextRef.value = targetOfDropDownItem.text
    }
    listTools({
      level: '2',
      parentId: value,
      pageSize: 999
    }).then((res) => {
      typeOptions2Ref.value = res.rows
    })

    handleSearch(value)
  }
  type2ValueRef.value = value
}
// 点击二级菜单
const handleChangeDropdownOfType2 = (value) => {
  if (loadingRef.value) return
  // 取消勾选
  if (type2ValueRef.value === value && device.value === 'pc') {
    type2ValueRef.value = ''
    handleSearch(type1ValueRef.value)
  } else {
    if (device.value === 'phone') {
      const targetOfDropDownItem = dropdownTypeOptions2.value.find((item) => item.value == value)
      type2DropMenuTextRef.value = targetOfDropDownItem.text
    }
    type2ValueRef.value = value
    handleSearch(value)
  }
}

const handleClear = () => {
  searchValueRef.value = ''
  handleSearch()
}
const handleDetail = (row) => {
  router.push({ path: '/detail', query: { id: row.id } })
}

init()
</script>

<style lang="scss" scoped>
.menu-box {
  @apply min-h-[52px] flex items-center p-4 flex-wrap;
}
.menu-content {
  @apply flex-1 flex flex-wrap;
}
.menu-item {
  @apply pl-3 pr-3 py-1 cursor-pointer text-center font-semibold;
  &.active {
    color: #004ea2;
    background-color: #dee6ef;
    border: 1px solid #004ea2;
    border-radius: 4px;
  }
}

.tool-card {
  @apply w-[165px] h-[270px] mx-auto mb-2 flex flex-col border box-content shadow-sm rounded-sm md:w-[220px] md:h-[330px] cursor-pointer;
}
.tool-card-none {
  @apply w-[165px] h-[270px] mx-auto mb-2 flex flex-col box-content rounded-sm md:w-[220px] md:h-[330px];
}
.tool-img {
  @apply w-[165px] h-[165px] bg-no-repeat bg-contain border-b-[1px] bg-center md:w-[220px] md:h-[220px];
}
</style>
