<template>
  <div class="member">
    <div class="center clear">
      <div class="container">
        <!-- 标题 -->
        <BigTitleComVue :bigTitle="titleInfo.title" :subTitle="titleInfo.subTitle" text-align="left">
        </BigTitleComVue>
      </div>
      <div class="container" style="padding-bottom: 20px">
        <research-search-com
          :select-nav="BtnText"
          :topic-id="topicId"
          :author-id="authorId"
          @select="onChangeActive"
        ></research-search-com>
      </div>
      <!-- 分割线 -->
      <LineComVue></LineComVue>
      <!-- <div class="btns container">
        <div class="btn-topic">
          <div class="search_type">Topics</div>
          <div class="btn_list">
            <div class="contents" ref="topicList">
              <div v-for="(item,index) in BtnText.topic" style="cursor: pointer" @click="changeActive('topic_id',item.id, index)" :key="item.id"
                   :class="params.topic_id.includes(item.id)  ? 'btn active' : 'btn'">
                {{ item.title }}
              </div>
            </div>
          </div>
          <div class="change">
            <change-prev style="cursor:pointer;" color="black" :opacity="isClickChangeTopic?'0.5':'0.1'" @click="changeTopic(0)" />
            <change-next style="cursor:pointer;"  color="black" :opacity="isClickChangeTopic?'0.5':'0.1'" @click="changeTopic(1)" />
          </div>
        </div>
        <div class="btn-authors">
          <div class="search_type">Author</div>
          <div class="btn_list">
            <div class="contents" ref="authorList">
              <div v-for="(item,index) in BtnText.authors" style="cursor: pointer; display: flex; align-items: center" @click="changeActive('author_id', item.id, index)" :key="item.id"
                   :class="params.author_id.includes(item.id)? 'btn active' : 'btn'">
                <img :src="item.avatar" alt="" class="avatar"/>
                <span style="white-space: nowrap">{{ item.name }}</span>
              </div>
            </div>
          </div>
          <div class="change">
            <change-prev style="cursor:pointer;" color="black" :opacity="isClickChangeAuthor?'0.5':'0.1'" @click="changeAuthor(0)" />
            <change-next style="cursor:pointer;"  color="black" :opacity="isClickChangeAuthor?'0.5':'0.1'" @click="changeAuthor(1)" />
          </div>
        </div>
      </div> -->
      <!-- 卡片 -->
      <div class="container">
        <template v-for="item in dataList" :key="item.id">
          <div class="backGauge" @click="ContentPages(item.id)">
            <ResearchComVue :data="item" :type="'research'" :isMid="isMid" :isSma="isSma" />
          </div>
        </template>
      </div>

      <div class="pagination container">
        <PaginationComVue :page="page" @changePage="changePage" :total="total" :per="per" />
      </div>
    </div>
  </div>
</template>
<script setup>
import BigTitleComVue from "../components/BigTitleCom.vue";
import ResearchComVue from "../components/ResearchCom.vue";
import PaginationComVue from "../components/PaginationCom.vue";
import LineComVue from "../components/LineCom.vue";
import {ref, watch, onMounted, reactive} from "vue";
import { useRoute, useRouter } from "vue-router";
import {getResearch, getResearchAuthorApi, getResearchType} from "../api/research.js";
import {transformDate} from "../utils/tools.js";
import useTitleInfo from "../utils/useTitleInfo.js";
import ChangeNext from "../components/ChangeNext.vue";
import ChangePrev from "../components/ChangePrev.vue";
const emits = defineEmits(['backTop'])
const titleInfo = useTitleInfo()
const topicList = ref(null)
const authorList = ref(null)
const isClickChangeTopic = ref(true)
const isClickChangeAuthor = ref(true)
//  按钮名称
const BtnText = reactive({
  topic:[
    {id: -1, title: "All"},
  ],
  authors:[
    {id: -1, name: "All"},
  ]
});
// 按钮点击
// const changeActive = (flag,id, index) => {
//   console.log(flag, 'index>>>>>', index)
//   // if (flag === 'topic_id') {
//   //   if (params[flag].length) {
//   //     params[flag] = params[flag].filter(it=> it === -1 ? undefined : it)
//   //   }
//   // }

//   params[flag][index] = params[flag][index] ? undefined : id;
//   if (flag === 'topic_id' && params[flag].length > 1) {
//     params[flag][params[flag].findIndex(it=> it === -1)] = undefined
//   }
//   if (flag === 'topic_id' && id === -1) {
//     params[flag] = [id]
//   }
//   page.value = 1;
//   getData()
// };

const onChangeActive = ({ type, item, index }) => {
  // const flag = type === 'topics' ? 'topic_id' : 'author_id'

  if (type === 'topics') {
    topicId.value = topicId.value === item.id ? '' : item.id
  } else {
    authorId.value = authorId.value === item.id ? '' : item.id
  }

  // params[flag][index] = params[flag][index] ? undefined : item.id;
  // if (flag === 'topic_id' && params[flag].length > 1) {
  //   params[flag][params[flag].findIndex(it=> it === -1)] = undefined
  // }
  // if (flag === 'topic_id' && item.id === -1) {
  //   params[flag] = [item.id]
  // }
  // console.log('params', params)
  page.value = 1;
  getData()
}

const router = useRouter();
const route = useRoute();

// const changeTopic = (flag)=>{
//   const left = topicList.value.parentElement.scrollLeft
//   if (isClickChangeTopic.value) {
//     if (flag === 1) {
//       topicList.value.parentElement.scrollTo({top:0, left: left + 100, behavior: 'smooth'})
//     } else {
//       topicList.value.parentElement.scrollTo({top:0, left: left - 100, behavior: 'smooth'})
//     }
//   }

// }

// const changeAuthor = (flag)=>{
//   const left = authorList.value.parentElement.scrollLeft
//   if (isClickChangeAuthor.value) {
//     if (flag === 1) {
//       authorList.value.parentElement.scrollTo({top:0, left: left + 100, behavior: 'smooth'})
//     } else {
//       authorList.value.parentElement.scrollTo({top:0, left: left - 100, behavior: 'smooth'})
//     }
//   }

// }


// 是否为中等屏幕 或 小屏幕
const isMid = ref(false);
const isSma = ref(false);

// 按钮高亮
const active = ref(-1);

const topicId = ref('')
const authorId = ref('')

// const params = reactive({
//   topic_id: [-1],
//   author_id: [],
// })

// 数据总数 Total databases count
let total = ref(0);
// 页码 page number
let page = ref(1);
// 每页显示数量  displays the number per page
let per = ref(10);
// 数据列表
let dataList = ref([]);


// 获取数据
const getData = () => {
  dataList.value = [];
  // const p = {
  //   ...params
  // }
  // if (p.author_id.length === 0) {
  //   delete p.author_id
  // } else {
  //   p.author_id = p.author_id.filter(it=> it !== undefined).join()
  // }
  // if (p.topic_id.length === 1 && p.topic_id[0] === -1) {
  //   delete  p.topic_id
  // } else {
  //   p.topic_id = p.topic_id.filter(it=> it !== undefined && it !== -1).join()
  // }

  let params = {
    page: page.value,
    limit: per.value
  }

  if (topicId.value && topicId.value !== -1) {
    params.topic_id = topicId.value
  }

  if (authorId.value && authorId.value !== -1) {
    params.author_id = authorId.value
  }

  getResearch(params).then(({data})=>{
    if (data) {
      total.value = data.total;
      per.value = data.per_page;
      page.value = data.current_page;
      dataList.value = data.data.map(it=> ({...it, date: transformDate(it.publishedtime)}))
    }
  })

  total.value = dataList.value.length;

  // 获取数据渲染
  dataList.value = dataList.value.slice(
    (page.value - 1) * per.value,
    page.value * per.value
  );
  emits('backTop')
};
// 内容页面
const ContentPages = (id) => {
  router.push({
    path: "/ContentPages",
    query: { contentId: id },
  });
};
// 换页 changePage
const changePage = (data) => {
  console.log('data', data)
  page.value = data;
  getData();
};


const getBtnList = async ()=>{
  const [{data:topic}, {data: authors}] = await Promise.all([getResearchType(),getResearchAuthorApi()]);
  if (topic && authors) {
    BtnText.topic.push(...topic)
    BtnText.authors.push(...authors)
    setTimeout(()=>{
      isClickChangeTopic.value = getStyle(topicList.value, 'width').replace('px', '')*1 >= getStyle(topicList.value.parentElement, 'width').replace('px', '') * 1;
      isClickChangeAuthor.value = getStyle(authorList.value, 'width').replace('px', '') * 1 >= getStyle(authorList.value.parentElement, 'width').replace('px', '') * 1;
    },200)
  }
}
const getStyle = (selector, prop)=> {
  return window.getComputedStyle(selector).getPropertyValue(prop)
}


// 监听屏幕尺寸变化
onMounted(() => {
  // 窗口大小改变时触发
  function changeSize() {
    const pageSize = window.innerWidth;
    if (pageSize >= 1440) {
      isSma.value = false;
      isMid.value = false;
    } else if (pageSize > 430 && pageSize < 1440) {
      isSma.value = false;
      isMid.value = true;
    } else if (pageSize <= 430) {
      isSma.value = true;
      isMid.value = false;
    }
  }
  changeSize();
  window.onresize = changeSize;
  getBtnList()
  getData();
  });

  watch(
	() => route.query,
	(newVal, oldVal) => {
    if (newVal.authorId) {
      authorId.value = newVal.authorId
      getData();
    }
	}, {
    immediate: true,
    deep: true
  }
);
</script>
<style lang="scss" scoped>
$margub: 24px;


.member {
  max-width: 1000px;
  margin: 0 auto;
}

.backGauge {
  margin-left: 7px;
  margin-right: 7px;
}

.btns {
  width: 100%;
  display: flex;
  font-family: 'Raleway';
  font-style: normal;
  flex-wrap: wrap;
  justify-content: flex-start;
  flex-direction: column;
  .btn-authors,.btn-topic {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    .btn_list {
      width: 88%;
      overflow-x:hidden;
      .contents {
        display: flex;
        width: fit-content;
      }
    }
    .search_type  {
      font-size: 14px;
      line-height: 21px;
      color: rgba(0,0,0,.5);
      width: 80px;
      flex-shrink: 0;
    }
    .avatar {
      width:26px;
      height: 26px;
      border-radius: 50%;
      background: #fff;
      border: 2px solid #fff;
      box-sizing: border-box;
    }
    span {
      margin-left: 12px;
      user-select: none;
    }
    .active {
      font-family: Raleway-Semibold;
    }
  }
  .change {
    flex-shrink: 0;
  }
  .btn {
    //min-width: 71px;
    padding: 0 20px;
    background-color: #fff;
    font-size: 14Px;
    line-height: 32px;
    margin: 10px 6px;
    text-align: center;
    user-select: none;
  }

  .active {
    color: #fff;
    background-color: #ff6d00;
    font-weight: 700;
  }

  @media screen and (min-width: 0Px) and (max-width: 431Px) {
    .btn {
      //width: 70px !important;
      font-size: 10px !important;
      margin: 5px 4px;
    }

    justify-content: flex-start;
    padding-top: 0 !important;
    padding-bottom: 0 !important;
    margin: -15px 0 -25px !important;
  }

  @media screen and (min-width: 1440Px) and (max-width: 100vw) {
    padding-top: 0 !important;
    padding-bottom: 0 !important;

    .btn {
      //width: 80px !important;
      font-size: 14Px !important;
    }
  }
}

@media screen and (min-width: 1440Px) and (max-width: 100vw) {

  .cardMarg {
    margin-left: 50px;
    margin-top: 40px;
    margin-bottom: 90px;
  }

}

@media screen and (min-width: 431Px) and (max-width: 1440Px) {
  .dividerPadding {
    padding-right: 40px;
  }

}

@media screen and (min-width: 0Px) and (max-width: 431Px) {
  .divider {
    margin-top: -20px;
  }

}

.pagination {
  float: right;
  margin: 20px 0px 20px;

  @media screen and (min-width:1440Px) and (max-width: 100vw) {
    padding-top: 0 !important;
    margin: 0px 0px 36px !important;
  }

  @media screen and (min-width:0Px) and (max-width: 431Px) {
    padding-top: 0px !important;
    margin: 0 0 20px !important;
  }
}
</style>
