<template>
  <div class="search-platform container-height">
    <div v-if="!isChildRoute">
      <Breadcrumb />
      <div class="search-platform-top bg_color_fff border_radius_16 box_shadow_card">
        <!-- 搜索与创建区域 -->
        <div class="search-create-bar"> 
          <div class="search-input-container flex_1">
            <input
              type="text"
              v-model="searchFom.title"
              :placeholder="$t('common.qingshuruyaosousuodegongzuoliu')"
              class="search-input"
            />
            <button class="search-btn bg_color_primary gradient" @click.stop.prevent="getList('init')">
              <img :src="searchIcon" alt="" class="icon-search">
              {{$t('common.shousuo')}}
            </button>
          </div>
          <button class="create-btn bg_color_primary gradient" @click.stop.prevent="goWorkflowAdd">
            <img :src="addIcon" alt="" class="icon-add">
            {{$t('common.fabuxuqiu')}}
          </button>
        </div>
        <div class="typeList flex-between typeborder">
          <div class="gray font_size14 typeName">{{$t('common.platform')}}：</div>
          <div class="flex_1 gap10"> 
            <div class="font_size14 typeItem"  :class="{'active':searchFom.categoryId1 === ''}"
            @click="searchFom.categoryId1 = ''; getList('init');"
            :key="-1">
              {{$t('common.all')}}
            </div>
            <div class="font_size14 typeItem"  :class="{'active':item.categoryId === searchFom.categoryId1}"
            @click="searchFom.categoryId1 = item.categoryId; getList('init');"
            v-for="item in CategoryList" :key="item.categoryId">
              {{item.categoryName}}
            </div>
          </div>
        </div>
        <div class="typeList flex-between typeborder">
          <div class="gray font_size14 typeName">{{$t('common.demandStatus')}}：</div>
          <div class="flex_1 gap10">
            <div class="font_size14 typeItem" 
             :class="{'active':searchFom.applyStatus == ''}"
             @click="searchFom.applyStatus = ''; getList('init');"
             :key="-1">
              {{$t('common.all')}}
            </div>
            <div class="font_size14 typeItem"
             :class="{'active':key === searchFom.applyStatus}"
             @click="searchFom.applyStatus = key; getList('init');"
             v-for="(value,key) in {'1': $t('workflowTrade.demandStatusSignUping'), '2': $t('workflowTrade.demandStatusEnded')}" :key="key">
              {{value}}
            </div>
          </div>
        </div>
        <div class="typeList flex-between">
          <div class="gray font_size14 typeName">{{$t('common.publishTime')}}：</div>
          <div class="flex_1">
            <div style="width: 320px">
              <el-date-picker
                size="large"
                v-model="publishTime"
                type="daterange"
                placeholder="选择日期范围"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="time => time.getTime() > Date.now()"
                @change="getList('init')"
              />
            </div>
          </div>
        </div>
      </div>
      <!-- 列表 -->
      <div class="course-list mt20">
        <div class="font_size20 bold mb10">
          {{$t('common.total')}} <span class="color_theme">{{listTotal}}</span> {{$t('common.demandCount')}}
        </div>
        <div class="padding16 bg_color_fff border_radius_16 mb20 box_shadow_card list_item_animation" 
          v-for="item in list" :key="item.questId"
        >
          <div  @click="goworkflowTradeDetail(item)" class="cursor-pointer">
            <div class="flex-between">
              <div class="gap10">
                <!-- <el-button 
                :type="item.applyStatus == 2 ? 'danger' : 'primary'" 
                v-if="applyStatusInfo[item.applyStatus]">
                  {{item.applyStatus === '1' ? $t('workflowTrade.demandStatusSignUping') : $t('workflowTrade.demandStatusEnded')}}
                </el-button> -->
                <div class="tag"
                :class="{ 'tag_red': item.applyStatus == 2 || item.applyStatus == null }">{{
                  item.applyStatus == 1 ? $t('workflowTrade.demandStatusSignUping') :
                    $t('workflowTrade.demandStatusEnded') }}</div>
                <div class="bold font_size30">{{item.title}}</div>
              </div>
              <div class="font_size24 color_price bold">￥{{item.budgetMin}}-{{item.budgetMax}}</div>
            </div>
            <div class="gap10 mt10">
              <el-button type="primary" plain size="small">{{item.categoryName1}}</el-button>
              <el-button type="primary" plain size="small">{{item.categoryName2}}</el-button>
              <el-button type="primary" plain size="small">{{item.categoryName3}}</el-button>
              <div class="gap5">
                <img :src="yuangong" alt="" style="width: 16px; height: 16px;">
                <span class="font_size14">{{item.questApplyCount || 0}} {{$t('common.renbaoming')}}</span>
              </div>
              <div class="gap5">
                <img :src="riliIcon" alt="" style="width: 16px; height: 16px;">
                <span class="font_size14">{{$t('common.signUpDeadline')}}：{{item.deadline}}</span>
              </div>
            </div>
            <div class="font_size16 gray mt10 line3">{{item.background || ''}}</div>
          </div>
          <div class="mt20">
            <div class="flex-between">
              <div class="gap10">
                <el-avatar :size="32" :src="appStore.avatar" />
                <div class="font_size16 bold">{{item.nickName}}</div>
                <div class="font_size14 gray mt2">{{item.createTime}} {{$t('common.publish')}}</div>
              </div>
              <el-button type="primary" size="large" class="gradient"
              v-if="item.applyStatus === '1'"
              @click="isLogin({callback: openLoginDialog,t}) && submitSignUp({questId: item.questId,questUserId: item.questUserId},t)">
                <img :src="zaixianbaomingIcon" alt="" class="mr10" style="width: 16px; height: 16px;">
                <span class="font_size14">{{$t('common.zaixianbaoming')}}</span>
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <!-- 替换原有的分页代码 -->
      <Pagination 
        :total="listTotal"
        :page-size="searchFom.pageSize"
        :current-page="searchFom.pageNum"
        @page-change="handlePageChange"
      />
    </div>
    <router-view />
  </div>
</template>

<script setup>
  import searchIcon from '@/assets/imgs/search.png'
  import addIcon from '@/assets/imgs/add.png'
  import yuangong from '@/assets/imgs/yuangong.png'
  import riliIcon from '@/assets/imgs/rili.png'
  import shiyongIcon from '@/assets/imgs/shiyong.png'
  import yunIcon from '@/assets/imgs/yun.png'
  import biaoqianIcon from '@/assets/imgs/biaoqian.png'
  import zaixianbaomingIcon from '@/assets/imgs/zaixianbaoming.png'
  import { submitSignUp,isLogin,openFullScreenLoading } from '@/utils/util.js'

  import Pagination from '@/components/Pagination.vue'
  import { getQuestList } from '@/api/workflowTrade.js'
  import { getCategoryList } from '@/api/category.js'
  


  import { useI18n } from 'vue-i18n' 
  const { t } = useI18n()
  import { useRouter, useRoute } from 'vue-router'
  const router = useRouter()
  const route = useRoute()
  console.log(router,route)
  import { ref, computed, reactive, onMounted, inject, watch } from 'vue'
  import { useAppStore } from '@/pinia/appStore'
  const appStore = useAppStore();
  const openLoginDialog = inject('openLoginDialog')
  //获取参数
  const query = route.query;
  //获取当前路由路径
  // const currentPath = ref(router.currentRoute.value.path)
  const isChildRoute = computed(() => {
    return route.matched.length > 1
  });
  const applyStatusInfo = {
    '1': t('workflowTrade.demandStatusSignUping'),
    '2': t('workflowTrade.demandStatusEnded'),
  }
  // 一级分类列表
  const CategoryList = ref([]);

  // 添加分页相关数据
  const list = ref([]);
  const listTotal = ref(0);
  const publishTime = ref(['', '']);
  const searchFom = reactive({
    categoryId1: '',
    title: '',
    applyStatus: '',//1：报名中，2：已结束
    publishTimeBegin: '',
    publishTimeEnd: '',
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'questId',
    isAsc: 'desc'
  })

  //新增返回后，刷新列表
  // 监听路由变化，当从子路由返回到父路由时刷新列表
  watch(
    () => route.matched.length,
    (newLength, oldLength) => {
      // 当路由从子路由（长度>1）返回到父路由（长度=1）时刷新列表
      if (oldLength > 1 && newLength === 1) {
        getList('init');
      }
    }
  )


  onMounted(() => {
    getList('init');
    getCategoryListFn();
  })
  const handlePageChange = (page, pageSize) => {
    searchFom.pageNum = page
    // 这里可以添加获取数据的逻辑
    if(pageSize)searchFom.pageSize = pageSize;
    console.log('当前页:', page);
    getList();
  }
  // 查询寻找工作流列表
  const getList = async (type) => {
    if(type === 'init'){
      searchFom.pageNum = 1
    }
    searchFom.publishTimeBegin = publishTime.value && publishTime.value[0] ? publishTime.value[0] : '';
    searchFom.publishTimeEnd = publishTime.value && publishTime.value[1] ? publishTime.value[1] : '';
    // 打开loading
    const loading = openFullScreenLoading();
    const res = await getQuestList(searchFom)
    // 关闭loading
    loading.close();
    if(res.code === 200){
      listTotal.value = res.total
      list.value = res.rows
    }
  }

  const goworkflowTradeDetail = (item={}) => {
    if(!isLogin({callback: openLoginDialog,t})){
      return
    }
    //增加参数名称
    router.push({
      path: `/workflow-trade/workflow-trade-detail`,
      query: {
        questId: item.questId,
        metaTitle: item.title || '详情'
      }
    })
  };
  const goWorkflowAdd = () => {
    if(!isLogin({callback: openLoginDialog,t})){
      return
    }
    //增加参数名称
    router.push({
      path: `/workflow-trade/workflow-trade-add`,
      query: {
      }
    })
  };
  const getCategoryListFn = async () => {
    console.log('获取一级分类列表')
    const res =  await getCategoryList({categoryLevel:1})
    if(res.code === 200){
      console.log('一级分类列表',res.data)
      CategoryList.value = res.rows || []
    }
  };
</script>

<style scoped lang="scss">
  // 2. 混合器：按钮通用样式
@mixin btn-style() {
  padding: 0 16px;
  color: #ffffff;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap:8px;
  font-size: 18px;
  
  &:hover {
    opacity: 0.9;
  }
}
.search-platform {
  .search-platform-top{
    padding: 12px 12px 0 12px;
  }
 
  // 搜索创建栏嵌套
  .search-create-bar {
    display: flex;
    align-items: center;
    gap: 8px;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 10px;

    .search-input {
      flex: 1;
      height: 60px;
      padding: 0 12px;
      outline: none;
      font-size: 18px;
      border-radius:7px;
      border: none;
      width: 100%;
      //占位符的颜色
      ::placeholder {
        color: #999;
      }
    }

    .search-btn {
      height: 50px;
      @include btn-style();
    }

    .create-btn {
      height: 56px;
      @include btn-style();
    }
    .search-input-container{
      position: relative;
      border-radius: 8px;
      border:2px solid $primary-color;
      .search-btn{
        position: absolute;
        top: 6px;
        right: 6px;
      }
    }
  }
  .typeList{
    padding: 10px 0;
    &.typeborder{
      border-bottom: 1px dashed #DCDFE6;
    }
    .typeName{
      margin-top: 6px;
      min-width: 80px;
      white-space: nowrap;
    }
    .typeItem{
      margin: 0 8px;
      cursor: pointer;
      padding: 4px 8px;
      &.active{
        background: rgba(45,113,255,0.1);
        border-radius: 4px 4px 4px 4px;
        color: $primary-color;
        font-weight: 600;
      }
    }
  }
  .tag {
    padding: 0 12px;
    line-height: 30px;
    color: #FFFFFF;
    font-size: 14px;
    background: #2D71FF;
    border-radius: 4px;
    margin-right: 8px;
  }

  .tag_red {
    background: #E43434;
  }
}
</style>
