import Taro, { Component } from '@tarojs/taro'
import { View, Image, Navigator, Swiper, SwiperItem } from '@tarojs/components'
import ListMore from '@/c/pageDataList/listMore'

import Footer from '@/c/footer'
import SearchHouse from '@/c/searchHouse'
import NewsNews from './components/news'
import QA from './components/QA'
import './index.scss'
import { arrToObj } from '@utils'

class Index extends Component {
  onShareAppMessage() {
    return {
      title: '让买房，更省心！',
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }

  config = {
    navigationBarTitleText: '洪楼Plus',
    navigationStyle: 'custom',
    navigationBarTextStyle: 'white'
  }

  constructor (props) {
    super(props)
    this.state = {
      footerList: [],
      footerCurIndex: 0,
      hotRecommendList: [],
      adBannerList: [],
      newsCountObj: {},
      newsList: [],
      qaList: [],
      isFirstOpen: 'yes',
    }
  }

  componentWillMount () {
    const isFirstOpen = Taro.getStorageSync('APP_isFirstOpen')
    if (isFirstOpen) {
      this.setState({
        isFirstOpen
      })
    }
    Taro.api.base.apiindex().then(res => {
      const resObj = res || {}
      // console.log(resObj)
      // 轮播图广告
      if (resObj.adverts_list && resObj.adverts_list.index_banner && resObj.adverts_list.index_banner.length > 0) {
        this.setState({
          adBannerList: resObj.adverts_list.index_banner
        })
      } else {
        const adBannerEx = require('@img/images/ex_banner.jpg')
        this.setState({
          adBannerList: [{images: adBannerEx}]
        })
      }
      // 文章统计
      const countArr = resObj.information_category_count || []
      let newsCountObj = {}
      countArr.forEach(item => {
        newsCountObj[item.information_category] = item.total
      })
      this.setState({
        newsCountObj
      })
      // 最新文章
      this.subNews.getData(resObj.information_list || [])
      // 最新问答
      this.subQa.getData(resObj.qa_list || [])
      // 热门推荐
      this.setState({
        hotRecommendList: resObj.estate_module_list || []
      })
      // 最新楼盘
      this.setState({
        footerList: res.estate_list || []
      })
    })
    // this.getBannerAd()
    // this.getHotRecommend()
    // this.getFooterList()
    // Taro.api.news.apiinformationcount().then(res => {
    //   const arr = res || {}
    //   let newsCountObj = {}
    //   arr.forEach(item => {
    //     newsCountObj[item.information_category] = item.total
    //   })
    //   this.setState({
    //     newsCountObj
    //   })
    // })
  }

  onQaRef = (ref) => {
    this.subQa = ref
  }
  onNewsRef = (ref) => {
    this.subNews = ref
  }

  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}`
        })
      }
    }
  }
  getBannerAd () {
    const testImg1 = require('@img/images/ex_banner.jpg')
    Taro.api.house.apiadvertslist({ad_position: 'index_banner'}).then(res => {
      const adList = res.index_banner || []
      if (adList.length === 0) {
        adList.push({images: testImg1})
      }
      this.setState({
        adBannerList: adList
      })
    })
  }

  renderEntry () {
    const { newsCountObj } = this.state
    const icon1 = require('./img/i_1.png')
    const icon2 = require('./img/i_2.png')
    const icon3 = require('./img/i_3.png')
    const icon4 = require('./img/i_4.png')
    const icon5 = require('./img/i_5.png')
    const icon6 = require('./img/i_6.png')
    const icon7 = require('./img/i_7.png')
    const icon8 = require('./img/i_8.png')
    const icon9 = require('./img/i_9.png')
    const icon10 = require('./img/i_10.png')
    return (
      <View className="index-entry">
        <Navigator url={'/pagesHouse/list?type=hot&name=热门楼盘'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon1} />
          </View>
          <View className="ie-text">热门楼盘</View>
        </Navigator>
        <Navigator url={'/pagesHouse/list?type=pre_sale&name=即将开售'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon2} />
          </View>
          <View className="ie-text">即将开售</View>
        </Navigator>
        <Navigator url={'/pagesHouse/list?type=zzyh&name=正在摇号'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon3} />
          </View>
          <View className="ie-text">正在摇号</View>
        </Navigator>
        <Navigator url={'/pagesHouse/list?type=yhjg&name=摇号结果'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon4} />
          </View>
          <View className="ie-text">摇号结果</View>
        </Navigator>
        <Navigator url={'/pagesHouse/list?type=onsale&name=在售楼盘'} className="ie-op">
          <View className="ie-icon">
            <Image className="img" src={icon5} />
          </View>
          <View className="ie-text">在售楼盘</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=lppc&name=楼盘测评'} className="ie-op">
          <View className="ie-icon t2">
            <Image className="img" src={icon6} />
            <View className="text">{newsCountObj.lppc || '0'}</View>
          </View>
          <View className="ie-text">楼盘测评</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=lsdt&name=楼市动态'} className="ie-op">
          <View className="ie-icon t2">
            <Image className="img" src={icon7} />
            <View className="text">{newsCountObj.lsdt || '0'}</View>
          </View>
          <View className="ie-text">楼市动态</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=bkfx&name=板块解读'} className="ie-op">
          <View className="ie-icon t2">
            <Image className="img" src={icon8} />
            <View className="text">{newsCountObj.bkfx || '0'}</View>
          </View>
          <View className="ie-text">板块解读</View>
        </Navigator>
        <Navigator url={'/pagesMore/center/loanCalc'} className="ie-op">
          <View className="ie-icon t3">
            <Image className="img" src={icon9} />
          </View>
          <View className="ie-text">房贷计算</View>
        </Navigator>
        <Navigator url={'/pagesMore/center/queryBuyHouse'} className="ie-op">
          <View className="ie-icon t3">
            <Image className="img" src={icon10} />
          </View>
          <View className="ie-text">资格查询</View>
        </Navigator>
      </View>
    )
  }


  renderClass () {
    const bg1 = require('./img/e_1.png')
    const bg2 = require('./img/e_2.png')
    const bg3 = require('./img/e_3.png')
    return (
      <View className="index-class">
        <Navigator url={'/pagesSchool/class'} className="ic-item">
          <View className="ic-item-wrap">
            <View className="ic-t1">热门学区</View>
            <View className="ic-t2">热点学校</View>
            <View className="ic-t2">一网打尽</View>
          </View>
          <Image className="img" src={bg1} />
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=hljy&name=教育热文'} className="ic-item">
          <View className="ic-item-wrap">
            <View className="ic-t1">教育热文</View>
            <View className="ic-t2">宝爸宝妈</View>
            <View className="ic-t2">都在看</View>
          </View>
          <Image className="img" src={bg2} />
        </Navigator>
        <Navigator url={'/pagesHouse/list?type=metro&name=地铁房'} className="ic-item">
          <View className="ic-item-wrap">
            <View className="ic-t1">地铁房</View>
            <View className="ic-t2">地铁一通</View>
            <View className="ic-t2">上班不迟到</View>
          </View>
          <Image className="img" src={bg3} />
        </Navigator>
      </View>
    )
  }

  renderHotRecommend () {
    const dictData = Taro.getStorageSync('dictData')
    const { hotRecommendList } = this.state
    const exImg = require('@img/images/ex_banner.jpg')
    const oneObj = hotRecommendList[0] || {}
    const product_type1 = oneObj.product_type || ''
    const productTypeArr1 = product_type1.split(',').map(v => {
      return arrToObj(dictData.product_type)[v]
    })
    const cTagStr1 = oneObj.custom_tag || ''
    const tagViews1 = cTagStr1.split(',').map((tag, tagIndex) => {
      return (
        <View className="s" key={tagIndex}>{tag}</View>
      )
    })
    let twoList = []
    if (hotRecommendList.length > 3) twoList = [hotRecommendList[1], hotRecommendList[2], hotRecommendList[3]]
    const curItems = twoList.map((item, index) => {
      const product_type = item.product_type || ''
      const productTypeArr = product_type.split(',').map(v => {
        return arrToObj(dictData.product_type)[v]
      })
      const cTagStr = item.custom_tag || ''
      const tagViews = cTagStr.split(',').map((tag, tagIndex) => {
        return (
          <View className="s" key={tagIndex}>{tag}</View>
        )
      })
      return (
        <Navigator url={'/pagesHouse/indexDtl?id=' + item.estate_id} className="lhl-item" key={index}>
          <View className="lhl-img">
            <Image src={item.pri_image + '_xs'} className="img" />
          </View>
          <View className="lhl-info">
            <View className="lhl-p1">{item.estate_name}</View>
            <View className="lhl-p2">{item.price_range || "未知"}/㎡</View>
            <View className="lhl-p3">{arrToObj(dictData.area_type)[item.area_type]}  {productTypeArr.length > 0 ? `-${productTypeArr.join('/')}` : ''}</View>
            <View className="lhl-sign">
              {
                item.estate_tag === '售罄'
                ? <View className="s t4">{item.estate_tag}</View>
                : item.estate_tag === '待售'
                ? <View className="s t3">{item.estate_tag}</View>
                : <View className="s t2">{item.estate_tag}</View>
              }
              {tagViews}
            </View>
          </View>
        </Navigator>
      )
    })
    const iconHot = require('./img/i_hot.png')
    return (
      <View className="index-list">
        <View className="il-header">
          <View className="t">市场聚焦</View>
          <Image className="i" src={iconHot} />
          <Navigator url={'/pagesHouse/list?type=hot_recommend&name=市场聚焦'} className="r">查看更多{'>'}</Navigator>
        </View>
        <View className="l-house-list">
          <Navigator url={'/pagesHouse/indexDtl?id=' + oneObj.estate_id} className="lhl-item one">
            <View className="lhl-img">
              <Image src={oneObj.pri_image ? oneObj.pri_image + '_xs' : ''} className="img" />
            </View>
            <View className="lhl-info">
              <View className="lhl-p1">{oneObj.estate_name}</View>
              <View className="lhl-p2">{oneObj.price_range || "未知"}/㎡</View>
              <View className="lhl-p3">{arrToObj(dictData.area_type)[oneObj.area_type]}  {productTypeArr1.length > 0 ? `-${productTypeArr1.join('/')}` : ''}</View>
              <View className="lhl-sign">
                {
                  oneObj.estate_tag === '售罄'
                  ? <View className="s t4">{oneObj.estate_tag}</View>
                  : oneObj.estate_tag === '待售'
                  ? <View className="s t3">{oneObj.estate_tag}</View>
                  : <View className="s t2">{oneObj.estate_tag}</View>
                }
                {tagViews1}
              </View>
            </View>
          </Navigator>
          {curItems}

        </View>
      </View>
    )
  }
  getHotRecommend () {
    Taro.api.house.admestatemodulelist({
      module_type: 'hot_recommend'
    }).then(res => {
      this.setState({
        hotRecommendList: res.list || []
      })
    })
  }


  renderHouseList () {
    const dictData = Taro.getStorageSync('dictData')
    const { footerList } = this.state
    const curItems = footerList.map((item, index) => {
      const product_type = item.product_type || ''
      const productTypeArr = product_type.split(',').map(v => {
        return arrToObj(dictData.product_type)[v]
      })
      const cTagStr = item.custom_tag || ''
      const tagViews = cTagStr.split(',').map((tag, tagIndex) => {
        return (
          <View className="s" key={tagIndex}>{tag}</View>
        )
      })
      return (
        <Navigator url={'/pagesHouse/indexDtl?id=' + item.estate_id} className="lhl-item col-1" key={index}>
          <View className="lhl-img">
            <Image src={item.pri_image + '_xs'} className="img" />
          </View>
          <View className="lhl-info">
            <View className="lhl-p1">{item.estate_name}</View>
            <View className="lhl-p2">{item.price_range || "未知"}/㎡</View>
            <View className="lhl-p3">{arrToObj(dictData.area_type)[item.area_type]}  {productTypeArr.length > 0 ? `-${productTypeArr.join('/')}` : ''}</View>
            <View className="lhl-sign">
              {
                item.estate_tag === '售罄'
                ? <View className="s t4">{item.estate_tag}</View>
                : item.estate_tag === '待售'
                ? <View className="s t3">{item.estate_tag}</View>
                : <View className="s t2">{item.estate_tag}</View>
              }
              {tagViews}
            </View>
          </View>
        </Navigator>
      )
    })
    const navArr = ['最新楼盘', '我的关注', '本月预售']
    const { footerCurIndex } = this.state
    const navItems = navArr.map((text, tI) => {
      return (
        <View onClick={this.moreSelectHandle.bind(this, tI)} className={footerCurIndex === tI ? 'nt cur' : 'nt'} key={tI}>{text}</View>
      )
    })
    return (
      <View className="index-list">
        <View className="il-header">
          {navItems}
        </View>
        <View className="l-house-list">
          {curItems}
          {
            footerList.length === 0
            &&
            <View className="scoped-list-more">
              <ListMore isOther={true}/>
            </View>
          }
        </View>
      </View>
    )
  }
  moreSelectHandle (footerCurIndex) {
    this.setState({
      footerCurIndex
    }, () => {
      this.getFooterList()
    })
  }
  getFooterList () {
    const { footerCurIndex } = this.state
    let apiStr = 'admestatelist'
    let params = {
      page_size: 20
    }
    if (footerCurIndex === 0) apiStr = 'admestatelist'
    if (footerCurIndex === 1) apiStr = 'apiestatefollowlist'
    if (footerCurIndex === 2) {
      apiStr = 'admestatemodulelist'
      params.module_type = 'cur_month_pre_sale'
    }
    Taro.api.house[apiStr](params).then(res => {
      this.setState({
        footerList: res.list || []
      })
    })
  }

  renderQaAdd () {
    const iconGif = require('@img/icon_g_qa.gif')
    return (
      <Navigator url={'/pagesMore/qa/add'} className="scoped-fix-q2 t2">
        <Image className="img" src={iconGif} />
      </Navigator>
    )
  }
  
  closeTips () {
    this.setState({
      isFirstOpen: 'no'
    }, () => {
      Taro.setStorageSync('APP_isFirstOpen', 'no')
    })
  }

  render () {
    const iconShare = require('@img/images/icon_g_share3.png')
    const topBg = require('./img/toper_bg.jpg')
    const { isFirstOpen } = this.state
    return (
      <View className="l-box has-footer">
        {this.renderQaAdd()}
        <View className="scoped-top">
          <Image className="img" src={topBg} />
          <SearchHouse type="home" />
        </View>
        {this.renderBanner()}
        {this.renderEntry()}
        {this.renderClass()}
        <NewsNews onRef={this.onNewsRef} />
        <QA onRef={this.onQaRef} />
        {this.renderHotRecommend()}
        {this.renderHouseList()}
        <Button className="scoped-share btn-to-div" openType="share">
          <Image className="img" src={iconShare} />
        </Button>
        <Footer current={0} />
        {
          isFirstOpen === 'yes'
          &&
          <View className="scoped-open-tips" onClick={this.closeTips.bind(this)}>
            <Image className="img" src="http://icon.honglounews.com/tips_bg.png" />
            <View className="bg"></View>
          </View>
        }
      </View>
    )
  }
}

export default Index
