<import name="x-book" src="../../components/book/book.ux"></import>
<import name="x-loading" src="../../components/loading/loading.ux"></import>
<template>
  <div class="serch-wrap">
    <div class="search-top">
      <input
        type="text"
        id="search"
        class="serach-input"
        value="{{inputValue}}"
        @change="changeValue"
        enterkeytype="search"
        placeholder="请输入书名"
        @enterkeyclick="searchBook"
        style="placeholder-color:#D9D9D9"
      />
    </div>
    <div class="search-content" show="{{showHistory}}">
      <div class="top-wrap">
        <text>热门搜索</text>
        <div @click="nextHot">
          <text class="changed">换一换</text>
          <image
            src="../../assets/imgs/change_other.png"
            @click="changed"
          ></image>
        </div>
      </div>
      <div class="history-list" if="{{hotlist.length}}">
        <text
          class="history-item"
          for="{{hotlist}}"
          @click="serachItem($item.keyword)"
        >
          {{ $item.keyword }}
        </text>
      </div>
    </div>
    <div class="search-content" show="{{showHistory}}">
      <div class="top-wrap">
        <text>搜索历史</text>
        <image
          src="../../assets/imgs/delete.png"
          @click="deleteHistory"
        ></image>
      </div>
      <div class="history-list" if="{{historyList.length}}">
        <text
          class="history-item"
          for="{{historyList}}"
          @click="serachItem($item)"
        >
          {{ $item }}
        </text>
      </div>
    </div>
    <div class="search-content" if="{{!list.length&&!showHistory}}">
      <text class="isempty">{{ loadingText }}</text>
    </div>
    <list
      class="list-content"
      @scrollbottom="onReachBottom"
      if="{{list.length&&!showHistory}}"
      id="list"
    >
      <list-item type="reslut">
        <text class="reslut-title">为您搜索出以下内容</text>
      </list-item>
      <block for="list">
        <list-item
          type="books-item"
          class="books-item__wrap {{$idx === 0 ? 'book-item__wrap--first' : ''}}"
        >
          <x-book multi="{{true}}" width="{{150}}" book="{{$item}}">
            <div class="book-info">
              <text class="name">{{ $item.book_name }}</text>
              <text class="intro">{{ $item.book_summary }}</text>
            </div>
          </x-book>
        </list-item>
      </block>
    </list>
  </div>
</template>
<script>
import { getBooksList, getHotMain, getUserInfo } from "../../api";
import { pageLoad } from "../../helper";
import storage from '@system.storage';
import prompt from '@system.prompt';

export default {
	private: {
		inputValue: null,
		showHistory: true,
		meta: {},
		hotlist: [],
		empty: false,
		list: [],
		historyList: [],
		loadingText: "努力搜索ing...",
		uid: '',
		filter: {
			key: "",
			page_size: 100,
			page: 1,
			status: 1,
		},
	},
	computed: {

	},
	nextHot() {
		if (this.meta.last_page == 1) {
			return;
		}
		if (this.meta.current_page == this.meta.last_page) {
			this.getData();
		} else {
			this.getData(this.meta.current_page + 1);
		}
	},
	async onInit() {
		let user = await getUserInfo();
		this.uid = user.id
		this.getData();
		let list = (await storage.get({ key: "history" })).data;
		let sets = JSON.parse(list)
		if (sets) this.historyList = sets;

	},
	async getData(page = 1) {

		let data = await getHotMain(page);
		this.hotlist = data.list;
		this.meta = data.meta;
	},
	searchBook(iptValue) {
		if (!iptValue.value) {
			prompt.showToast({ message: "请输入书名" });
			return false;
		}
		this.filter.key = iptValue.value;
		this.getBooksArray(false);
		this.$element('search').focus({ focus: false });
		this.showHistory = false;
	},
	serachItem(key) {
		this.filter.key = key;
		this.inputValue = key;
		this.getBooksArray(false);
		this.showHistory = false;
	},
	deleteHistory() {
		let _self = this;
		prompt.showDialog({
			title: '重要提醒',
			message: '确认要删除历史记录吗~',
			buttons: [
				{
					text: '删除记录',
					color: '#EF5952'
				},
				{
					text: '我再想想',
					color: '#999'
				}
			],
			success: function (data) {
				if (data.index == 0) {
					storage.delete({
						key: 'history',
						success: function (data) {
							_self.historyList = [];
							prompt.showToast({ message: "删除成功" });
						},
					})
				}

			},
			cancel: function () {
				console.log('取消前往')
			},
		})
	},
	changeValue(text) {
		if (!text.value) {
			this.showHistory = true;
		}
	},
	async getBooksArray(isLoad = true) {
		this.empty = false;
		this.loadingText = "加载ing...";
		this.filter.page = (this.meta.current_page || 0) + 1;
		if (!isLoad) {
			this.filter.page = 1;
			this.meta = {};
		}
		let params = this.filter;
		params.uid = this.uid;
		console.log(params);
		pageLoad(this.meta, getBooksList, params).then(ret => {
			let newList = isLoad ? this.list : [];
			let dataList = ret.list;
			newList.push(...dataList);
			this.meta = ret.meta;
			this.list = newList;
			if (!this.list.length) this.loadingText = "没有更多内容了", this.empty = true;
			if (!isLoad) {
				this.$element('list') && this.$element('list').scrollTo({ index: 0 });
				if (this.filter.key && !this.historyList.includes(this.filter.key)) {
					this.historyList.push(this.filter.key);
					if (this.historyList.length > 10) {
						this.historyList.shift()
					}
					storage.set({
						key: 'history',
						value: JSON.stringify(this.historyList),
						success: function (data) {
							console.log('handling success')
						},
					})
				}
			}
		}).catch(e => {
			console.log("e", e);
		})
	},
	onReachBottom() {
		// 请求更多数据
		this.getBooksArray();
	},
}
</script>
<style lang="less">
@import '../../assets/less/serach.less';
</style>


