<template>
  <div class="search-container">
    <search-input ref="search" @submit="doSearch" @recovery="doSearch"></search-input>
    <div class="search-result-container">
      <div class="sort-list">
        <span
          class="sort-item"
          v-for="(item, index) in sortTypeList"
          :key="index"
          @click="sortAndSearch(item, index)"
          :class="{ active: item.active, reverse: item.sort }"
        >
          <span class="sort-text">{{ item.label }}</span>
          <span class="sort-icon" :class="'el-icon-jy-' + (item.active ? 'down-blue' : 'down-grey')"></span>
        </span>
      </div>
      <div class="search-result-list" v-loading="listState.loading">
        <doc-card
          v-for="(item, index) in listState.list"
          :key="index"
          :title="item.docName"
          :desc="item.docSummary + '...'"
          :docType="item.docFileType"
          :price="item.price"
          :subInfo="calcSubInfo(item)"
          @onClick="toDocDetail(item)"
        />
        <no-data v-if="listState.list.length === 0 && listState.loaded"></no-data>
      </div>
      <div class="search-pagination">
        <el-pagination
          background
          layout="prev, pager, next, ->, total"
          :hide-on-single-page="true"
          :current-page="listState.pageNum"
          :page-size="listState.pageSize"
          :total="listState.total"
          @current-change="onPageChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { Icon, Pagination } from 'element-ui'
import SearchInput from '@/components/Search'
import DocCard from '@/components/doc-item-card/Card'
import NoData from '@/components/NoData'
import { getSearch } from '../api/modules/search'
import { formatSize, dateFormatter } from '@/utils/'
import { mixinBackground } from '@/utils/mixins'

export default {
  name: 'seach',
  mixins: [mixinBackground],
  components: {
    [Icon.name]: Icon,
    [Pagination.name]: Pagination,
    SearchInput,
    DocCard,
    NoData
  },
  data () {
    return {
      sortTypeList: [
        {
          type: 'tSort',
          label: '上传时间',
          sort: 0,
          active: true
        },
        {
          type: 'dSort',
          label: '下载次数',
          sort: 0,
          active: false
        },
        {
          type: 'vSort',
          label: '浏览人数',
          sort: 0,
          active: false
        }
      ],
      searchQuery: {
        type: '',
        text: ''
      },
      listState: {
        loaded: false, // 是否已经搜索过
        loading: false,
        pageNum: 1, // 当前页
        pageSize: 10, // 每页多少条数据
        total: 0, // 一共多少条数据
        list: [] // 查询请求返回的数据
      }
    }
  },
  computed: {
    activeSortList () {
      return this.sortTypeList.find(item => {
        return item.active
      })
    }
  },
  methods: {
    getLoginStatus: function () {
      console.log(loginflag)
    },
    // 恢复数据至第一次请求的状态(页码等)
    resetListState () {
      const state = {
        loaded: false,
        loading: false,
        pageNum: 1,
        total: 0,
        list: []
      }
      Object.assign(this.listState, state)
    },
    setUrlQuery: function () {
      const arr = []
      for (const key in this.searchQuery) {
        arr.push(this.searchQuery[key] === this.$route.query[key])
      }
      // 如果当前url和设置的url完全相同或者搜索值为空时候，则直接返回
      // 是否所有元素都为true
      const isSame = arr.every(item => item)
      if (isSame || !this.searchQuery.text) {
        return
      }
      this.$router.replace({
        name: 'search',
        query: {
          type: this.searchQuery.type,
          text: this.searchQuery.text
        }
      })
    },
    getSearchState: function (search) {
      if (search) {
        Object.assign(this.searchQuery, search)
      } else {
        this.searchQuery.type = this.$refs.search.type
        this.searchQuery.text = this.$refs.search.input.trim().replace(/\s+/g, ' ')
      }
    },
    doSearch (search) {
      this.getSearchState(search)
      if (!this.searchQuery.text) {
        if (search.events === 'onSubmit') {
          this.$router.push('/')
        }
        return
      }
      this.resetListState()
      this.getList(search)
    },
    async getList (search) {
      const query = {
        keyWord: this.searchQuery.text.trim().replace(/\s+/g, ' '),
        tag: this.searchQuery.type === '全部' ? '' : this.searchQuery.type,
        sort: this.activeSortList.type,
        num: this.listState.pageNum,
        size: this.listState.pageSize
      }

      console.log(query)
      // 设置url
      this.setUrlQuery()
      // 搜索内容去多余的空格并设置
      this.$refs.search.setSearchContent(query.keyWord)

      this.listState.loading = true
      this.listState.loaded = false
      const r = await getSearch(query)
      this.listState.loading = false
      this.listState.loaded = true

      const res = r.data
      if (res.error_code === 0) {
        this.listState.total = res.data.total
        this.listState.list = res.data.list || []
      } else {
        this.listState.total = 0
        this.listState.list = []
      }
    },
    sortAndSearch (item, index) {
      if (item.active) {
        // 改变sort
        // item.sort = item.sort ? 0 : 1
      } else {
        this.sortTypeList.forEach(s => {
          s.active = false
        })
        item.active = true
      }
      this.doSearch()
    },
    toDocDetail (item) {
      const { docId: id } = item
      window.open(`./content/${id}`) // 打开新窗口
      // this.$router.push({
      //   name: 'content',
      //   params: { id }
      // })
    },
    onPageChange (p) {
      this.listState.pageNum = p
      this.getList()
    },
    calcSubInfo (item) {
      const { docFileSize: size, downTimes, uploadDate, docPageSize } = item
      const subInfoArr = []
      if (uploadDate !== undefined) {
        const data = uploadDate.replace(/-/g, '/')
        subInfoArr.push(dateFormatter(data, 'yyyy/MM/dd'))
      }
      if (downTimes !== undefined) {
        subInfoArr.push(`${downTimes}次下载`)
      }
      if (docPageSize !== undefined) {
        subInfoArr.push(`共${docPageSize}页`)
      }
      if (size !== undefined) {
        subInfoArr.push(formatSize(size))
      }
      return subInfoArr
    }
  }
}
</script>
<style lang="scss" scoped>
@include diy-icon('down-grey', 18, 18);
@include diy-icon('down-blue', 18, 18);

.search-container {
  padding-top: 48px;
}
.search-result-container {
  margin: 0 auto;
  .sort-list {
    display: flex;
    align-items: center;
    margin: 18px;
    height: 48px;
    border-radius: 4px;
    background: #F5F6F7;
    .sort-item {
      display: flex;
      align-items: center;
      padding: 0 20px;
      height: 100%;
      font-size: 14px;
      color: #686868;
      cursor: pointer;
      .sort-text {
        margin-right: 4px;
      }
      .sort-icon {
        color: #aaa;
      }
      &.reverse {
        .sort-icon {
          transform: rotate(180deg);
        }
      }
      &.active {
        .sort-text,
        .sort-icon {
          color: $color-text--highlight;
        }
      }
      &:hover {
        .sort-text,
        .sort-icon {
          color: $color-text--highlight;
        }
      }
    }
  }
  .search-result-list {
    min-height: 500px;
  }
  .search-pagination {
    margin-top: 28px;
    padding-bottom: 60px;
    text-align: right;
  }
}
</style>
