import Taro, { Component } from '@tarojs/taro'
import { View, Image, Navigator } from '@tarojs/components'

import { AtSearchBar, AtTabs, AtTabsPane } from 'taro-ui'
import ListMore from '@/c/pageDataList/listMore'
import Footer from '@/c/footer'
import LoginPopup from '@/c/login/Popup'
import TpSelect from './components/TopSearch'
import './index.scss'
import { arrToObj } from '@utils'

class Index extends Component {
  onShareAppMessage(res) {
    let rObj = {
      title: '洪楼Plus-南昌楼市测评-动态资讯-学区地铁',
    }
    const exImg = require('@img/images/share_img.jpg')
    const target = res.target || {}
    if (res.from === 'button') {
      const cItem = target.dataset.value || {}
      let imageUrl = exImg
      if (cItem.information_category === 'hlzt') imageUrl = 'http://icon.honglounews.com/news_hlzt.jpg'
      if (cItem.information_category === 'hljy' || cItem.information_category === 'xqsc') imageUrl = 'http://icon.honglounews.com/news_hljy.jpg'
      if (cItem.information_category === 'bkfx') imageUrl = 'http://icon.honglounews.com/news_bkfx.jpg'
      if (cItem.information_category === 'lppc') imageUrl = 'http://icon.honglounews.com/news_lppc.jpg'
      if (cItem.information_category === 'lpwd') imageUrl = 'http://icon.honglounews.com/news_lpwd.jpg'
      if (cItem.information_category === 'hlpd') imageUrl= 'http://icon.honglounews.com/news_hlpd.jpg'
      if (cItem.information_category === 'lszt') imageUrl= 'http://icon.honglounews.com/news_lszt.jpg'
      if (cItem.information_category === 'zcjd') imageUrl= 'http://icon.honglounews.com/news_zcjd.jpg'
      if (cItem.information_category === 'esf') imageUrl= 'http://icon.honglounews.com/news_esf.jpg'
      if (cItem.information_category === 'lsdt') imageUrl= 'http://icon.honglounews.com/news_lsdt.jpg'
      if (cItem.information_category === 'scfx') imageUrl= 'http://icon.honglounews.com/news_scfx.jpg'
      return {
        title: cItem.title || '推荐这篇文章给你看看',
        path: `/pagesMore/news/indexDtl?id=${cItem.id}`,
        imageUrl
      }
    } else {
      return rObj
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }

  constructor (props) {
    super(props)
    this.state = {
      curNav: 0,
      searchKey: '',          
      page_size: 10,
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
      userInfo: '',
      token: '',
      isLoginPopupShow: false,
      newsCountObj: {},
      searchIndex: -1,
      area_type: [],
      searchText1: '',
      searchText2: '',
      formObj: {},
      tpSearchForm: {},
      isTpShow: false,
    }
  }

  config = {
    navigationBarTitleText: '洪楼Plus',
  }

  componentWillMount () {
    Taro.api.news.apiinformationcount().then(res => {
      const arr = res || {}
      let newsCountObj = {}
      arr.forEach(item => {
        newsCountObj[item.information_category] = item.total
      })
      this.setState({
        newsCountObj
      })
    })
    this.getDtl()
    const userInfo = Taro.getStorageSync('APP_userInfo') || ''
    if (userInfo) {
      this.setState({
        userInfo
      })
    }
    const { nav } = this.$router.params
    this.setState({
      curNav: nav ? Number(nav) : 0
    }, () => {
      this.getDataList()
    })
  }

  getDtl () {
    this.setState({
      token: Taro.getStorageSync('APP_token') || ''
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  navClick (value) {
    this.setState({
      curNav: value,
      searchKey: '',
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
    }, () => {
      this.getDataList()
    })
  }

  renderSearch () {
    const { searchKey } = this.state
    const { curNav } = this.state
    let placeholderText = '请输入关键字搜索'
    if (curNav === 0) placeholderText = '请输入文章标题搜索'
    if (curNav === 1) placeholderText = '请输入问题搜索'
    if (curNav === 2) placeholderText = '请输入竞得公司搜索'
    return (
      <View>
        <AtSearchBar
          value={searchKey}
          placeholder={placeholderText}
          onChange={this.onSeachChange.bind(this)}
          onClear={this.onClearHandle.bind(this)}
          onActionClick={this.onSelectActionClick.bind(this)}
        />
      </View>
    )
  }
  onSeachChange (value) {
    this.setState({
      searchKey: value
    })
  }
  onClearHandle () {
    this.setState({
      searchKey: '',
      page: 1
    }, () => {
      this.getDataList()
    })
  }
  onSelectActionClick () {
    this.setState({
      page: 1,
    }, () => {
      this.getDataList()
    })
  }
  renderHeader () {
    const icon1 = require('./img/icon01.png')
    const icon2 = require('./img/icon02.png')
    const icon3 = require('./img/icon03.png')
    const icon4 = require('./img/icon04.png')
    const icon5 = require('./img/icon05.png')
    const { newsCountObj } = this.state
    return (
      <View className="index-entry">
        <Navigator url={'/pagesMore/news/list?type=scfx&name=市场分析'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon1}/>
            <View className="text">{newsCountObj.scfx || '0'}</View>
          </View>
          <View className="ie-text">市场分析</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=hlpd&name=洪楼盘点'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon2} />
            <View className="text">{newsCountObj.hlpd || '0'}</View>
          </View>
          <View className="ie-text">洪楼盘点</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=lszt&name=楼市杂谈'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon3} />
            <View className="text">{newsCountObj.lszt || '0'}</View>
          </View>
          <View className="ie-text">楼市杂谈</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=zcjd&name=政策解读'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon4} />
            <View className="text">{newsCountObj.zcjd || '0'}</View>
          </View>
          <View className="ie-text">政策解读</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=esf&name=带你买房'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon5} />
            <View className="text">{newsCountObj.esf || '0'}</View>
          </View>
          <View className="ie-text">带你买房</View>
        </Navigator>
      </View>
    ) 
  }


  getDataList () {
    const { curNav, tpSearchForm, area_type } = this.state
    let { page_size, page, dataList, isListEmpty } = this.state
    const { 
      searchKey,
    } = this.state
    let apiStr = 'adminformationlist'
    let params = {
      page,
      page_size,
      title: searchKey,
      hide_status: '1',
    }
    if (curNav === 1) {
      apiStr = 'apiquestionlist'
      params = {
        page,
        page_size,
        question_cont: searchKey,
      }
    }
    if (curNav === 2) {
      apiStr = 'apilandlist'
      params = {
        page,
        page_size,
        company: searchKey,
        area_type: area_type,
        start_at: tpSearchForm.start_at,
        end_at: tpSearchForm.end_at,
      }
    }
    Taro.api.news[apiStr](params).then(res => {
      const curData = res.list || []
      let isListEnd = false
      if (curData.length > 0) {
        if (page === 1) {
          dataList = curData
        } else {
          dataList = dataList.concat(curData)
        }
        if (curData.length === page_size && res.total !== curData.length) {
          isListEnd = false
        } else {
          isListEnd = true
        }
      }
      if (curData.length === 0 && page === 1) {
        isListEmpty = true
        dataList = []
      } else {
        isListEmpty = false
      }
      this.setState({
        dataList,
        isListEnd,
        isListEmpty,
        isListLoading: false
      })
    })
  }
  onScrollToLower (e) {
    let { isListEnd, isListLoading, page } = this.state
    if (!isListEnd && !isListLoading) {
      page++
      this.setState({
        page,
        isListLoading: true
      }, () => {
        this.getDataList()
      })
    }
  }

  renderList () {
    const exImg = require('@img/images/ex_banner.jpg')
    const btnShare = require('./img/btn_share.png')
    const iconNews = require('./img/icon_new.png')
    const { dataList } = this.state
    const itemsList = dataList.map((item, index) => {
      const curImg = item.pri_image ? `${item.pri_image}_xs` : exImg
      return (
        <View className="lb-item" key={index}>
          <Navigator url={'/pagesMore/news/indexDtl?id=' + item.id} className="lb-img">
            <Image className="img" src={curImg} />
          </Navigator>
          <View className="lb-info">
            <Navigator url={'/pagesMore/news/indexDtl?id=' + item.id} className="lb-p1">{item.title}</Navigator>
            <View className="lb-p2">{item.create_at.substring(0, 10)}  {item.author || '洪楼News'}
            <Button className="scoped-share-btn btn-to-div" openType="share" id={item.id} data-value={item}>
              <Image className="img" src={btnShare} />
            </Button>
            </View>
          </View>
        </View>
      )
    })
    return (
      <View className="l-list-box tnews">
        <View className="scoped-header">
          <View className="t">最新文章</View>
          <Image className="i" src={iconNews} />
        </View>
        {itemsList}
      </View>
    )
  }



  renderQA () {
    const { dataList } = this.state
    const iconQ = require('@img/qa_q.png')
    const dictData = Taro.getStorageSync('dictData')
    const qtObj = arrToObj(dictData.question_tag)
    const itemsList = dataList.map((item, index) => {
      const qCont = item.question_cont && item.question_cont.length > 38 ? item.question_cont.substring(0, 38) + '......' : item.question_cont
      const qt = item.question_tag || ''
      const signItems = qt.split(',').map((tag, tIndex) => {
        return (
          <View className="sign" key={tIndex}>{qtObj[tag] || '提问'}</View>
        )
      })
      return (
        <View className="ql-item" key={index}>
          <View className="ql-header">
            {signItems}
          </View>
          <View className="ql-info">
            <Navigator url={'/pagesMore/qa/dtl?id=' + item.id} className="ql-p1">
              <Image className="ql-icon-qa" src={iconQ} />
              {qCont}
            </Navigator>
          </View>
          <View className="ql-footer">
            <Image className="img" src={item.avatar} />
            <View className="t">{item.nickname || '洪楼Plus'}</View>
            <View className="s">{item.create_at.substring(0, 10)}</View>
          </View>
          {
            item.answer_count &&  Number(item.answer_count) > 0
            &&
            <Navigator url={'/pagesMore/qa/dtl?id=' + item.id} className="ql-r1">查看全部{item.answer_count}个回答{'>'}</Navigator>
          }
          <Navigator url={'/pagesMore/qa/dtl?id=' + item.id} className="ql-r2">我要回答</Navigator>
        </View>
      )
    })
    return (
      <View className="q-list">
        {itemsList}
      </View>
    )
  }




















  searchIndex1Render () {
    const { area_type } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const edIcon = require('@img/images/icon_g_ed.png')
    const rangeViews = dictData.area_type.map(item =>{
      let curClassName = "stc-op"
      area_type.forEach(curVal =>{
        if (curVal === item.val) {
          curClassName = "stc-op cur"
        }
      })
      return (
        <View className={curClassName} key={item.val} onClick={this.comSelectHandle.bind(this, item, 'area_type')}>{item.key}
          <Image className="img" src={edIcon} />
        </View>
      )
    })
    let allClassName = area_type.length === 0 ? 'stc-op cur' : 'stc-op'
    return (
      <View className="stc-wrap">
        <View className="stc-item">
          <View className={allClassName} onClick={this.comSelectHandle.bind(this, 'all', 'area_type')}>不限</View>
          {rangeViews}
        </View>
      </View>
    )
  }
  renderTop () {
    const { searchIndex } = this.state
    const {
      searchText1,
      searchText2,
      formObj,
    } = this.state
    return (
      <View className="l-search-top scoped-tp-search">
        <View className="st-nav">
          <View className={(searchIndex === 1 || searchText1) ? 'stn-op col-3 cur' : 'stn-op col-3'} onClick={this.searchNavHandle.bind(this, 1)}>
            <View className="stn-label">{searchText1 || '区域'}</View>
            <View className="stn-sign"></View>
          </View>
          <View className={(searchIndex === 2 || searchText2) ? 'stn-op col-3s cur' : 'stn-op col-3s'} onClick={this.openTpPopup.bind(this)}>
            <View className="stn-label scoped-temp-w">{searchText2 || '开始时间-结束时间'}</View>
            <View className="stn-sign"></View>
          </View>
        </View>
        <View className={searchIndex > 0 ? 'st-content show' : 'st-content'}>
          {
            searchIndex === 1
            &&
            this.searchIndex1Render()
          }
          <View className="l-floor-footer t2">
            <View className="lff-flex">
              <View className="lff-btn t3" onClick={this.resetHandle.bind(this)} >重置</View>
              <View className="lff-btn" onClick={this.saveHandle.bind(this)}>搜索</View>
            </View>
          </View>
        </View>
      </View>
    )
  }
  
  baseFormChange (key, val) {
    let { formObj } = this.state
    formObj[key] = val
    this.setState({
      formObj
    })
  }
  searchNavHandle (index) {
    let { searchIndex } = this.state
    searchIndex = index === searchIndex ? -1 : index
    this.setState({
      searchIndex
    })
  }
  resetHandle () {
    const { searchIndex } = this.state
    // this.setState({
    //   searchIndex: -1,
    // })
    if (searchIndex === 1) {
      this.setState({
        area_type: [],
        searchText1: '',
      })
    }
  }
  comSelectHandle (curOp, str) {
    if (curOp === 'all') {
      this.setState({
        [str]: []
      })
    } else {
      const state = this.state
      let curStr = state[str]
      let ed = false
      let curI = 0
      curStr.forEach((item, index) => {
        if (curOp.val === item) {
          ed = true
          curI = index
        }
      })
      if (ed) {
        curStr.splice(curI, 1)
      } else {
        curStr.push(curOp.val)
      }
      this.setState({
        [str]: curStr
      })
    }
  }
  saveHandle () {
    const dictData = Taro.getStorageSync('dictData')
    const { searchIndex } = this.state
    const { 
      area_type,
    } = this.state
    if (searchIndex === 1) {
      let tagArr = []
      area_type.forEach(v => {
        tagArr.push(arrToObj(dictData.area_type)[v])
      })
      if (tagArr) {
        this.setState({
          searchText1: tagArr.join(',')
        })
      }
    }
    this.setState({
      page: 1,
      searchIndex: -1,
    }, () => {
      this.getDataList()
    })
  }
  
















  









  renderTupai () {
    const { dataList } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const atObj = arrToObj(dictData.area_type)
    const itemsList = dataList.map((item, index) => {
      return (
        <Navigator url={'/pagesMore/news/tpDtl?id=' + item.id} className="tl-item" key={index}>
          <View className="tl-no">{item.no}-{atObj[item.area_type]}</View>
          <View className="tl-price">成交楼盘价:<View className="n">{item.floor_price}元/㎡</View></View>
          <View className="tl-company"><View className="tl-dot"></View>竞得方：{item.company}</View>
          <View className="tl-addr"><View className="tl-dot t2"></View>土拍位置：{item.land_name}</View>
          <View className="tl-time">成交时间：{item.deal_time}</View>
          <View className="tl-r1">{item.purpose}</View>
          <View className="tl-r2">查看更多{'>'}</View>
        </Navigator>
      )
    })
    return (
      <View className="tupai-list">
        {itemsList}
      </View>
    )
  }


  bcTpPopup (tpSearchForm) {
    let searchText2 = ''
    if (tpSearchForm.end_at) {
      searchText2 = `${tpSearchForm.start_at}-${tpSearchForm.end_at}`
    }
    this.setState({
      page: 1,
      tpSearchForm,
      searchText2,
      isTpShow: false
    }, () => {
      this.getDataList()
    })
  }
  closeTpPopup () {
    this.setState({
      isTpShow: false
    })
  }
  openTpPopup () {
    this.setState({
      searchIndex: -1,
      isTpShow: true
    })
  }



  getUserProfile (e) {
    wx.getUserProfile({
      desc: '用于完善头像和昵称资料',
      success: (res) => {
        const dtlObj = res || {}
        this.setState({
          userInfo: dtlObj.userInfo
        })
        Taro.setStorageSync('APP_userInfo', dtlObj.userInfo)
      }
    })
  }
  openLoginPopup (obj) {
    this.setState({
      isLoginPopupShow: true
    })
  }
  closeLoginPopup (str) {
    this.setState({
      isLoginPopupShow: false
    })
    if (str && str === 'success') {
      this.getDtl()
    }
  }



  renderQaAdd () {
    const iconGif = require('@img/icon_g_qa.gif')
    return (
      <Navigator url={'/pagesMore/qa/add'} className="scoped-fix-q2">
        <Image className="img" src={iconGif} />
      </Navigator>
    )
  }

  render () {
    const { curNav } = this.state
    const { isListEnd, isListLoading, isListEmpty } = this.state
    const tabList = [{ title: '文章' }, { title: '问答' }, { title: '土拍' }]
    const { userInfo, token } = this.state
    const uInfo = userInfo || Taro.getStorageSync('APP_userInfo')
    const { isLoginPopupShow, isTpShow, tpSearchForm } = this.state
    return (
      <View className="l-box has-footer">
        {
          curNav === 1
          ?
          uInfo
          ? token || isLoginPopupShow
          ? ''
          : <Button className="g-u-btn" onClick={this.openLoginPopup.bind(this)}></Button>
          : <Button className="g-u-btn" onClick={this.getUserProfile.bind(this)}></Button>
          : ''
        }
        <AtTabs className="scoped-fixed" current={curNav} tabList={tabList} onClick={this.navClick.bind(this)}>
          <AtTabsPane current={curNav} index={0} >
            <ScrollView
              className='l-scroll-view'
              scrollY
              scrollWithAnimation
              scrollTop="0"
              lowerThreshold="30"
              onScrollToLower={this.onScrollToLower.bind(this)}
            >
              <View>
                {this.renderSearch()}
                {this.renderHeader()}
                {this.renderList()}
              </View>
              <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} />
            </ScrollView>
          </AtTabsPane>
          <AtTabsPane current={curNav} index={1}>
            <ScrollView
              className='l-scroll-view'
              scrollY
              scrollWithAnimation
              scrollTop="0"
              lowerThreshold="30"
              onScrollToLower={this.onScrollToLower.bind(this)}
            >
              {this.renderSearch()}
              {this.renderQA()}
              <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} />
            </ScrollView>
          </AtTabsPane>
          <AtTabsPane current={curNav} index={2}>
            <ScrollView
              className='l-scroll-view'
              scrollY
              scrollWithAnimation
              scrollTop="0"
              lowerThreshold="30"
              onScrollToLower={this.onScrollToLower.bind(this)}
              >
              <View className="scoped-tp-box">
                {this.renderSearch()}
                {this.renderTop()}
                {this.renderTupai()}
              </View>
              <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} />
            </ScrollView>
          </AtTabsPane>
        </AtTabs>
        {
          curNav === 1
          &&
          // <Navigator url={'/pagesMore/qa/add'} className="scoped-fix-q">
          //   <View className="sfq-bg"></View>
          //   <View className="sfq-main">
          //     <Image className="img" src={iconQ} />
          //     <View className="t">提问</View>
          //   </View>
          // </Navigator>
          this.renderQaAdd()
        }
        <Footer current={2} />
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
        <TpSelect show={isTpShow} curObj={tpSearchForm} bc={this.bcTpPopup.bind(this)} close={this.closeTpPopup.bind(this)}/>
      </View>
    )
  }
}

export default Index
