SearchComponent.ets 12.5 KB
import router from '@ohos.router'
import { NetworkUtil, StringUtils, ToastUtils } from 'wdKit'
import SearcherAboutDataModel from '../../model/SearcherAboutDataModel'
import { SearchHistoryItem } from '../../viewmodel/SearchHistoryItem'
import { SearchRelatedItem } from '../../viewmodel/SearchRelatedItem'
import { EmptyComponent } from '../view/EmptyComponent'
import { SearchHistoryComponent } from './SearchHistoryComponent'
import { SearchHotsComponent } from './SearchHotsComponent'
import { SearchRelatedComponent } from './SearchRelatedComponent'
import { SearchResultComponent } from './SearchResultComponent'

const TAG = "SearchComponent"

@Component
export struct SearchComponent {
  @State searchTextData: string[] = []
  @State hasNoSearchTextData: boolean = false
  @State curHintSearchData: string = ""
  @State hasInputContent: boolean = false
  @State hasChooseSearch: boolean = false
  @State isClickedHistorySearch: boolean = false
  @State isClickedHotSearch: boolean = false
  @State isClickedRelatedSearch: boolean = false
  @State isClickedInputSearch: boolean = false
  @State isClickedHintSearch: boolean = false
  private swiperController: SwiperController = new SwiperController()
  @State searchText: string = ''
  controller: SearchController = new SearchController()
  @State searchHistoryData: SearchHistoryItem[] = []
  @State relatedSearchContentsData: SearchRelatedItem[] = []
  scroller: Scroller = new Scroller()
  @State count:string[] = []
  @State isGetRequest:boolean = false;

  aboutToAppear() {
    //获取提示滚动
    this.getSearchHint()
    //清除缓存
    SearcherAboutDataModel.searchHistoryData = []
    //获取搜索历史
    this.getSearchHistoryData()

    let intervalID = setInterval(() => {
      sendEventByKey("searchId", 10, "")
      clearInterval(intervalID);
    }, 1000);
  }

  getRelatedSearchContent() {
    if(StringUtils.isNotEmpty(this.searchText)){
      SearcherAboutDataModel.getRelatedSearchContentData(encodeURI(this.searchText),getContext(this)).then((value) => {
        if (value != null) {
          this.relatedSearchContentsData = []
          value.forEach(item=>{
            let tempValue:string = item
            let tempArr: string[] = []
            if (tempValue.indexOf(this.searchText) === -1) {
              tempArr.push(item)
              this.relatedSearchContentsData.push(new SearchRelatedItem(item,tempArr))
            }else {
              while (tempValue.indexOf(this.searchText) != -1){
                let index = tempValue.indexOf(this.searchText)
                if(index === 0){
                  try {
                    tempArr.push(this.searchText)
                    tempValue = tempValue.substring(this.searchText.length,tempValue.length)
                  } catch (e) {
                  }
                }else {
                  try {
                    tempArr.push(tempValue.substring(0,index))
                    tempArr.push(this.searchText)
                    tempValue = tempValue.substring(index+this.searchText.length,tempValue.length)
                  } catch (e) {
                  }
                }
              }
              if(StringUtils.isNotEmpty(tempValue)){
                tempArr.push(tempValue)
              }
              this.relatedSearchContentsData.push(new SearchRelatedItem(item,tempArr))
            }
          })
        }
      }).catch((err: Error) => {
        console.log(TAG, JSON.stringify(err))
      })
    }
  }

  getSearchHint() {
    SearcherAboutDataModel.getSearchHintData(getContext(this)).then((value) => {
      if (value != null) {
        this.searchTextData = value
      }
      this.setDefaultHitData()
    }).catch((err: Error) => {
      console.log(TAG, JSON.stringify(err))
      this.setDefaultHitData()
    })
  }
  setDefaultHitData(){
    if(this.searchTextData.length === 0){
      this.hasNoSearchTextData = true
      this.searchTextData.push("搜索感兴趣的内容")
    }
  }

  getSearchHistoryData() {
    this.searchHistoryData = SearcherAboutDataModel.getSearchHistoryData()
  }

  stopInput(){
    this.controller.stopEditing()
  }

  build() {
    Column() {
      this.searchInputComponent()
      if (!this.hasInputContent) {
        Scroll(this.scroller) {
          Column() {
            if(this.searchHistoryData!=null && this.searchHistoryData.length>0){
              SearchHistoryComponent({ searchHistoryData: $searchHistoryData, onDelHistory: (): void => this.getSearchHistoryData(),onGetSearchRes: (item,index): void => this.getSearchHistoryResData(item,index),onCloseInput : (): void => this.stopInput() })
            }

            if(this.searchHistoryData.length>0){
              //分隔符
              Divider()
                .width('100%')
                .height('1lpx')
                .color($r('app.color.color_EDEDED'))
                .strokeWidth('1lpx')
            }

            SearchHotsComponent({onGetSearchRes: (item): void => this.getSearchHotResData(item)})
          }
        }
        .scrollable(ScrollDirection.Vertical)
        .scrollBar(BarState.Off)
        .width('100%')
        .height('100%')
        .padding({ left: '31lpx', right: '31lpx' })
      } else {
        if (this.hasChooseSearch) {
          //搜索结果
          SearchResultComponent({count:this.count,searchText:this.searchText,isGetRequest:this.isGetRequest,onClickTryAgain: (): void => {
            if(StringUtils.isNotEmpty(this.searchText)){
              SearcherAboutDataModel.putSearchHistoryData(this.searchText)
              this.getSearchHistoryData()
              this.getSearchInputResData(this.searchText)
            }
          }})
        } else {
          //联想搜索
          SearchRelatedComponent({relatedSearchContentData:$relatedSearchContentsData,onGetSearchRes: (item): void => this.getSearchRelatedResData(item),searchText:this.searchText})
        }
      }
    }.height('100%')
    .width('100%')
  }

  /**
   * 点击搜索记录列表回调
   * @param content
   */
  getSearchHistoryResData(content:string,index:number){
    //删除单条记录
    SearcherAboutDataModel.delSearchSingleHistoryData(index)
    this.isClickedHistorySearch = true
    this.searchResData(content)
  }

  searchResData(content:string){
    //赋值
    this.searchText = content
    //保存搜索记录
    SearcherAboutDataModel.putSearchHistoryData(this.searchText)
    //获取搜索记录
    this.getSearchHistoryData()
    //清空 联想记录
    this.relatedSearchContentsData = []

    //查询 操作 TODO
    this.hasChooseSearch = true
    this.getSearchResultCountData()
    this.controller.stopEditing()
  }

  /**
   * 点击hint搜索列表回调
   * @param content
   */
  getSearchHintResData(content:string){
    this.isClickedHintSearch = true
    this.searchResData(content)
  }

  /**
   * 点击联想搜索列表回调
   * @param content
   */
  getSearchRelatedResData(content:string){
    this.isClickedRelatedSearch = true
    this.searchResData(content)
  }

  /**
   * 点击热词搜索列表回调
   * @param content
   */
  getSearchHotResData(content:string){
    this.isClickedHotSearch = true
    this.searchResData(content)
  }

  /**
   * 点击输入法搜索搜索列表回调
   * @param content
   */
  getSearchInputResData(content:string){
    this.isClickedInputSearch = true
    this.searchResData(content)
  }

  //搜索框
  @Builder searchInputComponent() {
    Row() {
      //左
      Stack({ alignContent: Alignment.Start }) {
        if (this.searchTextData != null && this.searchTextData.length > 0 && !this.hasInputContent) {
          Swiper(this.swiperController) {
            ForEach(this.searchTextData, (item: string, index: number) => {
              Text(item)
                .fontWeight('400lpx')
                .fontSize('25lpx')
                .fontColor($r('app.color.color_666666'))
                .lineHeight('35lpx')
                .textAlign(TextAlign.Start)
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Clip })
                .margin({ left: '40lpx' })
            })
          }
          .loop(true)
          .autoPlay(true)
          .interval(3000)
          .indicator(false)
          .vertical(true)
          .enabled(false)
          .focusable(false)
          .onChange((index: number) => {
            this.curHintSearchData = this.searchTextData[index]
          })
        }
        Row(){
          Search({ value: this.searchText, placeholder: '', controller: this.controller})
            .layoutWeight(1)
            .height('69lpx')
            .backgroundColor($r('app.color.color_transparent'))
            .textFont({ size: "27lpx", weight: "400lpx" })
            // .defaultFocus(true)
            .id("searchId")
            .searchIcon({
              size:0
            })
            .cancelButton({
              style:CancelButtonStyle.INVISIBLE
            })
            .caretStyle({color:Color.Pink})
            .onSubmit((value: string) => {
              if(StringUtils.isNotEmpty(this.searchText)){
                SearcherAboutDataModel.putSearchHistoryData(this.searchText)
                this.getSearchHistoryData()
                this.getSearchInputResData(this.searchText)
              }else{
                if(!this.hasNoSearchTextData){
                  if(StringUtils.isEmpty(this.curHintSearchData)){
                    this.curHintSearchData =  this.searchTextData[0]
                  }
                  this.getSearchHintResData(this.curHintSearchData)
                }else{
                  ToastUtils.shortToast("请输入搜索关键词")
                }
              }
            })
            .onChange((value: string) => {
              this.searchText = value
              if(this.isClickedHistorySearch || this.isClickedHotSearch || this.isClickedRelatedSearch || this.isClickedInputSearch|| this.isClickedHintSearch){
                this.hasChooseSearch = true
              }else{
                this.hasChooseSearch = false
              }

              if (this.searchText.length > 0) {
                this.hasInputContent = true
              } else {
                this.hasInputContent = false
              }

              if(this.isClickedHistorySearch || this.isClickedHotSearch || this.isClickedRelatedSearch || this.isClickedInputSearch|| this.isClickedHintSearch){
                this.resetSearch()
              }else{
                if(this.hasInputContent){
                  this.getRelatedSearchContent()
                }
              }
            })
        }.padding({right:'70lpx'})
        .layoutWeight(1)

        Image($r('app.media.search_input_del_icon'))
          .width("31lpx")
          .height("31lpx")
          .objectFit(ImageFit.Auto)
          .interpolation(ImageInterpolation.Medium)
          .margin({left:"495lpx"})
          .onClick(()=>{
            this.searchText = ""
          })
          .visibility(StringUtils.isEmpty(this.searchText) ? Visibility.Hidden : Visibility.Visible)

      }
      .backgroundImage($r('app.media.search_page_input_bg'))
      .backgroundImageSize(ImageSize.Cover)
      .layoutWeight(1)
      .height('69lpx')

      //TODO 需要修改输入法  换行
      //右
      Text("取消")
        .textAlign(TextAlign.Center)
        .fontWeight('400lpx')
        .fontSize('31lpx')
        .lineHeight('58lpx')
        .fontColor($r('app.color.color_222222'))
        .width('125lpx')
        .height('58lpx')
        .onClick(() => {
          router.back()
        })
    }
    .height('85lpx')
    .padding({ left: '31lpx' })
    .alignItems(VerticalAlign.Center)
  }


  getSearchResultCountData() {
    SearcherAboutDataModel.getSearchResultCountData(encodeURI(this.searchText),getContext(this)).then((value) => {
      if (value != null) {
        this.count = []
        if(value.allTotal!=0){
          this.count.push("全部")
        }
        if(value.cmsTotal!=0){
          this.count.push("精选")
        }
        if(value.rmhTotal!=0){
          this.count.push("人民号")
        }
        if(value.videoTotal!=0){
          this.count.push("视频")
        }
        //屏蔽活动
        // if(value.activityTotal!=0){
        //   this.count.push("活动")
        // }
      }
      this.isGetRequest = true
      this.resetSearch()
    }).catch((err: Error) => {
      console.log(TAG, JSON.stringify(err))
      this.isGetRequest = true
      this.resetSearch()
    })
  }

  resetSearch(){
    this.isClickedHistorySearch = false
    this.isClickedHotSearch = false
    this.isClickedRelatedSearch = false
    this.isClickedInputSearch = false
    this.isClickedHintSearch = false
  }
}