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 './index.scss'
import { arrToObj } from '@utils'

class Index extends Component {
  onShareAppMessage(res) {
    const target = res.target || {}
    if (res.from === 'button') {
      const cItem = target.dataset.value || {}
      if (cItem.question_cont) {
        return {
          title: cItem.question_cont,
          path: `/pagesQa/dtl?id=${cItem.id}`
        }
      }
    } else {
      return {
        title: '让买房，更省心',
      }
    }
  }
  onShareTimeline () {
    return {
      title: '南昌楼市问答交流解惑，来洪楼圈~',
    }
  }

  constructor (props) {
    super(props)
    this.state = {
      curNav: 1,
      searchKey: '',          
      page_size: 10,
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
      userInfo: '',
      token: '',
      isLoginPopupShow: false,
      qaQt: '',
    }
  }

  config = {
    navigationBarTitleText: '南昌楼市交流解惑',
  }

  componentWillMount () {
    Taro.removeStorageSync('APP_newsDot')
    this.getDtl()
    this.getDataList()
  }

  getDtl () {
    const userInfo = Taro.getStorageSync('APP_userInfo') || ''
    if (userInfo) {
      this.setState({
        userInfo
      })
    }
    this.setState({
      token: Taro.getStorageSync('APP_token') || ''
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  navClick (value) {
    if (value === 1) {
      this.setState({
        searchKey: '',
        page: 1,
        isListEnd: false,
        isListLoading: false,
        isListEmpty: false,
        dataList: [],
        qaQt: '',
      }, () => {
        this.getDataList()
      })
    } else {
      Taro.reLaunch({
        url: `/pagesMore/news/index?nav=${value}`
      })
    }
  }

  renderSearch () {
    const { searchKey } = this.state
    let 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()
    })
  }


  getDataList () {
    const { qaQt } = this.state
    let { page_size, page, dataList, isListEmpty } = this.state
    const { 
      searchKey,
    } = this.state
    let apiStr = 'apiquestionlist'
    let params = {
      page,
      page_size,
      question_cont: searchKey,
      question_tag: qaQt
    }
    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()
      })
    }
  }

  renderTopQA () {
    const n1 = require('./img/bg_news_t1.png')
    const n2 = require('./img/bg_news_t2.png')
    return (
      <View className="scoped-top-qa">
        <Navigator url="/pagesQa/list" className="stq-item">
          <Image className="img" src={n1} />
        </Navigator>
        <Navigator url="/pagesMore/center/sxf" className="stq-item">
          <Image className="img" src={n2} />
        </Navigator>
      </View>
    )
  }
  renderSearchQA () {
    const { qaQt } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const qtArr = dictData.question_tag || []
    const curItems = qtArr.map((item, index) => {
      return (
        <View className={qaQt === item.val ? 'ssq-item cur' : 'ssq-item'} key={index} onClick={this.qtHandle.bind(this, item.val)}>{item.key}</View>
      )
    })
    return (
      <View className="scoped-search-qa">
        <View className={qaQt ? 'ssq-item' : 'ssq-item cur'} onClick={this.qtHandle.bind(this, 'all')}>全部</View>
        {curItems}
      </View>
    )
  }
  qtHandle (str) {
    if (str === 'all') {
      this.setState({
        qaQt: '',
        dataList: [],
        page: 1,
        isListEnd: false,
        isListLoading: false,
        isListEmpty: false,
      }, () => {
        this.getDataList()
      })
    } else {
      this.setState({
        qaQt: str,
        dataList: [],
        page: 1,
        isListEnd: false,
        isListLoading: false,
        isListEmpty: false,
      }, () => {
        this.getDataList()
      })
    }
  }

  renderList () {
    const { dataList } = this.state
    const iconQ = require('@img/qa_q.png')
    const HideMan = require('@img/icon_hide_man.png')
    const btnShare = require('./img/btn_share2.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 > 62 ? item.question_cont.substring(0, 62) + '...' : item.question_cont
      const qt = item.question_tag || ''
      const signItems = qt.split(',').map((tag, tIndex) => {
        return (
          <View className="sign" key={tIndex}>{qtObj[tag] || '提问'}</View>
        )
      })
      let imgArr = []
      if (item.question_img) imgArr = item.question_img.split(',')
      const imgItems = imgArr.map((src, srcIndex) => {
        return (
          <View className="op" key={srcIndex} onClick={this.previewImageHandle.bind(this, src, imgArr)}>
            <Image className="img" src={src} />
          </View>
        )
      })
      return (
        <View className="ql-item" key={index}>
          <View className="ql-header">
            {signItems}
          </View>
          <View className="ql-info">
            <Navigator url={'/pagesQa/dtl?id=' + item.id} className="ql-p1">
              <Image className="ql-icon-qa" src={iconQ} />
              {qCont}
            </Navigator>
            {
              imgArr.length > 0
              &&
              <View className="ql-img">
                {imgItems}
              </View>
            }
          </View>
          {
            item.is_anon === '1'
            ?
            <View className="ql-footer">
              <Image className="img" src={HideMan} />
              <View className="t">匿名粉丝</View>
              <View className="s">{item.create_at.substring(0, 10)}</View>
            </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={'/pagesQa/dtl?id=' + item.id} className="ql-r1">查看全部{item.answer_count}个回答{'>'}</Navigator>
          }
          <Navigator url={'/pagesQa/dtl?id=' + item.id} className="ql-r2">我要回答</Navigator>
          <Button className="ql-r2s btn-to-div" openType="share" data-value={item}>
            <Image className="i" src={btnShare} />
          </Button>
        </View>
      )
    })
    return (
      <View className="q-list">
        {itemsList}
      </View>
    )
  }
  previewImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }




  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={'/pagesQa/add'} className="scoped-fix-q2 t2">
        <Image className="img" src={iconGif} />
      </Navigator>
    )
  }
  renderShare () {
    const iconShare = require('@img/images/icon_g_share6.png')
    return (
      <Button className="g-icon-share btn-to-div" openType="share" data-value={'qa'}>
        <Image className="img" src={iconShare} />
      </Button>
    )
  }

  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 } = this.state
    return (
      <View className="l-box has-footer">
        {
          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)}>
        </AtTabs>
        <ScrollView
          className='l-scroll-view'
          scrollY
          scrollWithAnimation
          scrollTop="0"
          lowerThreshold="30"
          onScrollToLower={this.onScrollToLower.bind(this)}
        >
          {this.renderTopQA()}
          {this.renderSearchQA()}
          {this.renderSearch()}
          {this.renderList()}
          <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} />
        </ScrollView>
        {this.renderQaAdd()}
        {this.renderShare()}
        <Footer current={2} />
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
      </View>
    )
  }
}

export default Index
