import Taro, { Component } from '@tarojs/taro'
import { View, Image, Input, Swiper, SwiperItem, ScrollView } from '@tarojs/components'
import ListMore from '@/c/pageDataList/listMore'
import LoginPopup from '@/c/login/Popup'
import './dtl.scss'
import { strTrim } from '@utils'

class Index extends Component {
  onShareAppMessage() {
    const { id } = this.$router.params
    return {
      title: `来谈谈你的见解？`,
      path: `/pagesQa/dtl?id=${id}`,
    }
  }
  onShareTimeline () {
    const { id } = this.$router.params
    const { curObj } = this.state
    return {
      title: `${curObj.question_cont}`,
      path: `/pagesQa/dtl?id=${id}`,
    }
  }


  constructor (props) {
    super(props)
    this.state = {
      page_size: 10,
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
      curObj: {},
      commentVal: '',
      tempObj: {},
      userInfo: '',
      token: '',
      isLoginPopupShow: false,
      isAnswerHide: false,
      adBannerList: {}
    }
  }

  config = {
    navigationBarTitleText: '问答详情',
  }

  componentWillMount () {
    Taro.$AHU(this)
    const { name } = this.$router.params
    Taro.setNavigationBarTitle({
      title: name || '问答详情'
    })
    this.getDataList()
    this.getDtl()
    this.getBannerAd()
  }
  
  getDtl () {
    const userInfo = Taro.getStorageSync('APP_userInfo') || ''
    if (userInfo) {
      this.setState({
        userInfo
      })
    }
    this.setState({
      token: Taro.getStorageSync('APP_token') || ''
    })
  }

  componentDidShow () { }

  componentDidHide () { }


  renderTop () {
    const { curObj } = this.state
    const HideMan = require('@img/icon_hide_man.png')
    const btnBack = require('./img/bg_bc_list.png')
    let imgArr = []
    if (curObj.question_img) imgArr = curObj.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 + '_xs'} mode="aspectFill" />
        </View>
      )
    })
    const voteOps = curObj.vote && curObj.vote.vote_cont ? curObj.vote.vote_cont :  []
    return (
      <View className="l-comment-box">
        <View className="lcb-top">
          <View className="lt-content" onClick={this.sendChangeHandle.bind(this, curObj)}>
            <View className="lb-img">
              <Image className="img" src={curObj.is_anon === '1' ? HideMan : curObj.avatar} />
            </View>
            <View className="lb-info">
              <View className="lb-p1 t2">
                {curObj.nickname || '洪楼Plus'}
                <Image onClick={this.linkDtl.bind(this)} className="b" src={btnBack}></Image>
              </View>
              <View className="lb-time">{curObj.create_at}</View>
            </View>
          </View>
          <View className="lt-content-more" onClick={this.sendChangeHandle.bind(this, curObj)}>
            <View className="lb-p2">{curObj.question_cont}</View>
            {
              imgArr.length > 0
              &&
              <View className="scoped-img">
                {imgItems}
              </View>
            }
          </View>
          {voteOps.length === 2 && this.renderVs(curObj)}
          {voteOps.length > 2 && this.renderVote(curObj)}
        </View>
      </View>
    )
  }
  previewImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }

  linkDtl () {
    Taro.redirectTo({url: '/pagesQa/index'})
  }

  zanHandle (answer_id, flag) {
    let apiStr = flag ? 'apianswerunzan' : 'apianswerzan'
    Taro.api.news[apiStr]({
      answer_id
    }).then(res => {
      this.getDataList()
    })
  }











  renderVs (item) {
    const bg = require('./img/index/vsbg.png')
    const edIcon = require('./img/index/rightblue.png')
    const edIcon2 = require('./img/index/rightred.png')
    const vsbg2 = require('./img/index/vsbg2.png')
    const vsbg3 = require('./img/index/vsbg3.png')
    const voteOps = item.vote.vote_cont || []
    const voteUser = item.vote.vote_user || {}
    const totalNum = item.vote.vote_count_sum || 0
    const curItems = voteOps.map((op, i) => {
      return (
        <View className="op" key={i} onClick={this.voteHandle.bind(this, op)}>{op.vote_cont}</View>
      )
    })
    const edBgItems = voteOps.map((op, i) => {
      const per = parseInt(op.vote_count / totalNum * 100)
      return (
        <View className={op.id === voteUser.vote_id ? 'op cur' : 'op'} style={`width:${per + 10}%`} key={i}>
          <View className="bg"></View>
          <View className="v">{op.vote_count}</View>
          { op.id === voteUser.vote_id && i === 0 && <Image className="i" src={vsbg2}></Image> }
          { op.id === voteUser.vote_id && i === 1 && <Image className="i" src={vsbg3}></Image> }
        </View>
      )
    })
    const edItems = voteOps.map((op, i) => {
      return (
        <View className='op' key={i}>
          <View className={op.id === voteUser.vote_id && i === 0 ? 'cur t' : 't'}>{op.vote_cont}
            { op.id === voteUser.vote_id && i === 0 && <Image className="i" src={edIcon2}></Image> }
            { op.id === voteUser.vote_id && i === 1 && <Image className="i" src={edIcon}></Image> }
          </View>
        </View>
      )
    })
    return (
      <View className="ql-vs">
        {
          voteUser.is_vote
          ?
          <View className="qv-ed">
            <View className="qve-bg">
              {edBgItems}
            </View>
            <View className="qve-content">
              {edItems}
            </View>
          </View>
          :
          <View className="qv-un">
            <Image className="bg" src={bg}></Image>
            <View className="content">
              {curItems}
            </View>
          </View>
        }
      </View>
    )
  }


  renderVote (item) {
    const edIcon = require('./img/index/rightblue.png')
    const voteOps = item.vote.vote_cont || []
    const voteUser = item.vote.vote_user || {}
    const totalNum = item.vote.vote_count_sum || 0
    const curItems = voteOps.map((op, i) => {
      return (
        <View className="op" key={i} onClick={this.voteHandle.bind(this, op)}>{op.vote_cont}</View>
      )
    })
    const edItems = voteOps.map((op, i) => {
      const per = parseInt(op.vote_count / totalNum * 100)
      return (
        <View className={op.id === voteUser.vote_id ? 'op cur' : 'op'} key={i}>
          <View className="bg" style={`width:${per}%`}></View>
          <View className="t">{op.vote_cont}
            {
              op.id === voteUser.vote_id
              &&
              <Image className="i" src={edIcon}></Image>
            }
          </View>
          <View className="v">{op.vote_count}</View>
        </View>
      )
    })
    return (
      <View className="ql-vote">
        {
          voteUser.is_vote
          ?
          <View className="qv-ed">
            {edItems}
          </View>
          :
          <View className="qv-un">
            {curItems}
          </View>
        }
      </View>
    )
  }
  voteHandle (op) {
    Taro.api.news.apiuservoteadd({
      question_id: op.question_id,
      vote_id: op.id
    }).then(() => {
      Taro.$msg('投票成功')
      this.getDataList()
    })
  }









  getDataList () {
    const HideMan = require('@img/icon_hide_man.png')
    let { page_size, page, dataList, isListEmpty } = this.state
    const { id: question_id } = this.$router.params
    Taro.api.news.apianswerlist2({
      page,
      page_size,
      question_id,
    }).then(res => {
      let curObj = res.question || {}
      if (curObj.is_anon === '1') curObj.nickname = '洪楼粉丝'
      let curData = res.answer_list.list || []
      let isListEnd = false
      if (curData.length > 0) {
        if (page === 1) {
          dataList = curData
        } else {
          dataList = dataList.concat(curData)
        }
        if (curData.length === page_size && res.answer_list.total !== curData.length) {
          isListEnd = false
        } else {
          isListEnd = true
        }
      }
      if (curData.length === 0 && page === 1) {
        isListEmpty = true
        dataList = []
        isListEnd = true
      } else {
        isListEmpty = false
      }
      dataList.map(item => {
        if (item.is_anon === '1') {
          item.nickname = '洪楼粉丝'
          item.avatar = HideMan
        }
        if (item.child && item.child.length > 0) {
          let child = item.child
          child.map(sub => {
            if (sub.is_anon === '1') {
              sub.nickname = '洪楼粉丝'
              sub.avatar = HideMan
            }
          })
        }
      })
      this.setState({
        curObj,
        tempObj: curObj,
        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 { dataList, isListEnd, isListLoading, isListEmpty } = this.state
    const zan1Icon = require('@img/i_g_zan.png')
    const zan2Icon = require('@img/i_g_zan2.png')
    let newArr = []
    const userCurInfo = Taro.getStorageSync('APP_userInfo')
    dataList.forEach(item => {
      if (item.hide_status === "2") {
        if (userCurInfo.user_id === item.user_id) {
          newArr.push(item)
        }
      } else {
        newArr.push(item)
      }
    })
    const curItems = newArr.map((item, index) => {
      const lvIcon = Taro.$getLvIcon(item.integral)
      const oldList = JSON.parse(JSON.stringify(item.child))
      let subList = item.isMoreAllShow ? [...oldList] : oldList.splice(0, 2)
      return (
        <View className="lcb-item" key={index}>
          <View className="lb-img" onClick={this.sendChangeHandle.bind(this, item)} >
            <Image className="img" src={item.avatar} />
          </View>
          <View className="lb-info">
            <View>
              <Navigator url="/pagesOther/index" className="lb-p1">{item.nickname}
                <Image className="i" src={lvIcon}></Image>
              </Navigator>
              <View onClick={this.dtlLink.bind(this, item)} className="lb-time">{item.create_at}</View>
              <View onClick={this.dtlLink.bind(this, item)} className="lb-p2">{item.answer_cont}</View>
            </View>
            <View className="lb-zan" onClick={this.zanHandle.bind(this, item.answer_id, item.is_zan)}>
              {
                item.is_zan
                ?
                <Image className="i" src={zan2Icon}/>
                :
                <Image className="i" src={zan1Icon}/>
              }
              <View className={item.is_zan ? 'n cur' : 'n'}>{item.zan_count}</View>
            </View>
            <View className="lb-sub">
              <View>
                {
                  subList.map((sub, subIndex) => {
                    const lvSubIcon = Taro.$getLvIcon(sub.integral)
                    return (
                      <View className="lcb-item" key={subIndex}>
                        <View className="lb-img" onClick={this.sendChangeHandle.bind(this, sub)}>
                          <Image className="img" src={sub.avatar} />
                        </View>
                        <View className="lb-info">
                          <Navigator url="/pagesOther/index" className="lb-p1">{sub.nickname}
                            <Image className="i" src={lvSubIcon}></Image>
                          </Navigator>
                          <View className="lb-time">{sub.create_at}</View>
                          {
                            sub.parent_id === item.answer_id
                            ?
                            <View onClick={this.dtlLink.bind(this, item)} className="lb-p2">{sub.answer_cont}</View>
                            :
                            <View onClick={this.dtlLink.bind(this, item)} className="lb-p2">回复:<View className="link">{sub.parent_user_name}</View>{sub.answer_cont}</View>
                          }
                        </View>
                      </View>
                    )
                  })
                }
              </View>
              {
                item.child.length > 2
                ?
                item.isMoreAllShow
                ?
                <View className="lb-more t2" onClick={this.commentMoreHandle.bind(this, index)}>收起
                  <View className="sign"></View>
                </View>
                :
                <View className="lb-more" onClick={this.commentMoreHandle.bind(this, index)}>-展开回复({item.child.length - 2}条)
                  <View className="sign"></View>
                </View>
                : ''
              }
            </View>
          </View>
        </View>
      )
    })
    return (
      <View>
        <View className="l-comment-box pb200">
          {curItems}
        </View>
        <ListMore isListEnd={isListEnd} isListLoading={isListLoading} isListEmpty={isListEmpty} />
      </View>
    )
  }

  dtlLink (item) {
    Taro.navigateTo({
      url: `/pagesQa/dtlSub?id=${item.answer_id}`
    })
  }

  commentMoreHandle (index) {
    const { dataList } = this.state
    let mList = dataList || []
    mList.map((item, i) => {
      if (index === i) item.isMoreAllShow = !item.isMoreAllShow
    })
    this.setState({
      dataList: [...mList]
    })
  }





  sendChangeHandle (tempObj) {
    this.setState({
      commentVal: '',
      tempObj
    })
  }

  sendHandle () {
    const { commentVal, tempObj, isAnswerHide } = this.state
    const { id } = this.$router.params
    if (commentVal) {
      let params = {
        question_id: Number(id),
        answer_cont: commentVal,
      }
      if (tempObj.user_id) {
        params = {
          question_id: Number(id),
          answer_cont: commentVal,
          parent_id: tempObj.id || tempObj.answer_id || '',
          parent_user_id: tempObj.user_id || '',
          parent_user_name: tempObj.nickname || '',
        }
      }
      if (isAnswerHide) {
        params.is_anon = '1'
      }
      Taro.api.news.apiansweradd(params).then(res => {
        Taro.$msg('回答成功~')
        this.setState({
          commentVal: ''
        })
        this.getDataList()
      })
    } else {
      Taro.$msg('请输入你的回答')
    }
  }

  changeInput (e) {
    const val = strTrim(e.target.value)
    this.setState({
      commentVal: val
    })
  }


  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">
        <Image className="img" src={iconShare} />
      </Button>
    )
  }


  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()
    }
  }

  answerHideChange () {
    let { isAnswerHide } = this.state
    isAnswerHide = !isAnswerHide
    this.setState({
      isAnswerHide
    })
  }








  renderBanner () {
    const { adBannerList } = this.state
    const adItems = adBannerList.map((item, index) => {
      return (
        <SwiperItem key={index}>
          <View className='ad-img' onClick={this.bannerHandle.bind(this, item)} >
            <Image src={item.images} className="img" />
          </View>
        </SwiperItem>
      )
    })
    return (
      <View className="index-banner">
        <Swiper
          className='test-h'
          indicatorColor='#999'
          indicatorActiveColor='#fff'
          circular
          indicatorDots
          autoplay>
          {adItems}
        </Swiper>
      </View>
    )
  }
  bannerHandle (item) {
    if (item.ad_link_type) {
      if (item.ad_link_type === 'estate') {
        Taro.navigateTo({
          url: `/pagesHouse/indexDtl?id=${item.link_type_value}`
        })
      }
      if (item.ad_link_type === 'news') {
        Taro.navigateTo({
          url: `/pagesMore/news/indexDtl?id=${item.link_type_value}`
        })
      }
      if (item.ad_link_type === 'page') {
        Taro.navigateTo({
          url: `${item.link_type_value}`
        })
      }
    }
  }
  getBannerAd () {
    const testImg1 = 'http://icon.honglounews.com/ex_banner.jpg'
    Taro.api.house.apiadvertslist({ad_position: 'qa_dtl_banner'}).then(res => {
      const adList = res.qa_dtl_banner || []
      // if (adList.length === 0) {
      //   adList.push({images: testImg1})
      // }
      this.setState({
        adBannerList: adList
      })
    })
  }



  loginJudge () {
    const { userInfo, token } = this.state
    const uInfo = userInfo || Taro.getStorageSync('APP_userInfo')
    const { isLoginPopupShow } = this.state
    return (
      <View style={uInfo && uInfo.avatarUrl && token ? '' : 'position: absolute;height: 100%;width: 100%;'}>
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
        {
          uInfo && uInfo.avatarUrl
          ? token || isLoginPopupShow
          ? ''
          : <Button className="g-u-btn t2" onClick={this.openLoginPopup.bind(this)}></Button>
          : <Button className="g-u-btn t2" onClick={this.getUserProfile.bind(this)}></Button>
        }
      </View>
    )
  }





  renderScrollBody () {
    const { tempObj, commentVal, curObj, isAnswerHide, adBannerList } = this.state
    const hideN = require('@img/icon_hide2.png')
    const hideY = require('@img/icon_hide3.png')
    return (
      <ScrollView
        className='l-scroll-view'
        scrollY
        scrollWithAnimation
        scrollTop="0"
        lowerThreshold="100"
        onScrollToLower={this.onScrollToLower.bind(this)}
      >
        <View style="position:relative;">
          {this.loginJudge()}
          {this.renderTop()}
          {adBannerList.length > 0  && this.renderBanner()}
          <View className="scoped-main">
            <View className="sm-title">
              全部回答
              <View className="t">({curObj.answer_count}条)</View>
            </View>
            {this.renderList()}
          </View>
          <View className="l-floor-footer">
            <View className="scoped-footer">
              <View className="sf-input">
              {/* focus */}
                {/* <Input className="input" placeholder={`我来回答`} value={commentVal}  onInput={this.changeInput.bind(this)} /> */}
                <Input className="input" placeholder={`回复:${tempObj.nickname}(点头像切换)`} value={commentVal}  onInput={this.changeInput.bind(this)} />
                <View className="more" onClick={this.answerHideChange.bind(this)}>
                  {
                    isAnswerHide
                    ? 
                    <Image className="i" src={hideY} />
                    :
                    <Image className="i" src={hideN} />
                  }
                </View>
                <View className="btn" onClick={this.sendHandle.bind(this)}>发送</View>
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
      
    )
  }



  render () {
    return (
      <View className="l-box has-footer">
        {this.renderQaAdd()}
        {this.renderShare()}
        {this.renderScrollBody()}
      </View>
    )
  }
}

export default Index
