import Taro, { Component } from '@tarojs/taro'
import { View, Map, Image, Swiper, SwiperItem, Button } from '@tarojs/components'
import { arrToObj } from '@utils'
import LoginPopup from '@/c/login/Popup'
import Comment from './components/indexDtl/comment'
import ListMore from '@/c/pageDataList/listMore'
import News from './components/indexDtl/news'
import './indexDtl.scss'

class Index extends Component {
  onShareAppMessage() {
    const { curId, curObj } = this.state
    return {
      title: `${curObj.estate_name}-找房`,
      path: `/pagesHouse/indexDtl?id=${curId}`,
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }
  
  constructor (props) {
    super(props)
    const {id: curId} = this.$router.params
    this.state = {
      curId,
      curObj: {},
      curImgIndex: 0,
      isLoginPopupShow: false,
      token: '',
      userInfo: '',
      photoList: [],
    }
  }

  config = {
    navigationBarTitleText: '楼盘详情',
  }

  componentDidMount () {
    this.getDtl(() => {
      const { curId, curObj } = this.state
      let historyRecordArr = Taro.getStorageSync('APP_historyRecord') || []
      let cIndex = -1
      historyRecordArr.forEach((item, index) => {
        if (String(item.id) === String(curId)) {
          cIndex = index
        }
      })
      if (cIndex !== -1) historyRecordArr.splice(cIndex, 1)
      if (historyRecordArr.length > 19) historyRecordArr.splice(19, 1)
      historyRecordArr.unshift(curObj)
      Taro.setStorageSync('APP_historyRecord', historyRecordArr)
      Taro.api.house.estatephotolist({estate_id: curId}).then(res => {
        const cArr = res.data ? JSON.parse(res.data) : []
        this.setState({
          photoList: cArr
        })
      })
    })
  }

  getDtl = (bc) => {
    const { fromViews } = this.$router.params
    const { curId } = this.state
    this.setState({
      token: Taro.getStorageSync('APP_token') || ''
    })
    let params = {
      id: curId
    }
    if (fromViews) params.from = fromViews
    Taro.api.house.admestatedetail(params).then(res => {
      let curObj = res || {}
      curObj.longitude = Number(curObj.longitude)
      curObj.latitude = Number(curObj.latitude)
      this.subComment.getData(curObj || {})
      this.subNews.getData(curObj.information_list || [])
      this.setState({
        curObj
      }, () => {
        if (bc) bc()
      })
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  renderHeader () {
    const { curImgIndex, curObj, photoList } = this.state
    let morePhoto = []
    photoList.forEach(item => {
      item.urls.forEach(url => {
        morePhoto.push({img_url: `${url}`})
      })
    })
    if (morePhoto.length > 0) morePhoto.shift()
    const imgArr = [{img_url: `${curObj.pri_image}`}, ...morePhoto]
    const iconShare = require('@img/images/icon_g_share.png')
    return (
      <View className="dtl-header">
        <Swiper
          circular
          current={curImgIndex}
          onChange={this.headerImgChange.bind(this)}
          className='dh-swiper'>
            {
              imgArr.map((item, index) => {
                return (
                  <SwiperItem key={index}>
                    <View className='dh-item'>
                      <Image src={item.img_url ? item.img_url + '_white' : ''} className="img" onClick={this.previewImageHandle.bind(this, item.img_url, imgArr)} />
                    </View>
                  </SwiperItem>
                )
              })
            }
        </Swiper>
        <View className="dh-pk" onClick={this.pkHandle.bind(this)}>
          <View className="bg"></View>
          <View className="t">PK</View>
        </View>
        <Button className="dh-icon-share btn-to-div" openType="share">
          <Image className="img" src={iconShare} />
        </Button>
        <View className="dh-count">
          <View className="bg"></View>
          <View className="num">{curImgIndex + 1}/{imgArr.length}</View>
        </View>
      </View>
    )
  }
  pkHandle () {
    const { curId } = this.state
    let oldPkList = Taro.getStorageSync('APP_pkList') || []
    let addFalg = true
    oldPkList.forEach(item => {
      if (String(item.id) === String(curId)) {
        addFalg = false
      }
    })
    if (addFalg) {
      Taro.api.house.admestatesimple({id: curId}).then(res => {
        oldPkList.unshift(res)
        if (oldPkList.length > 19) oldPkList.splice(19, 1)
        Taro.setStorageSync('APP_pkList', oldPkList)
        Taro.navigateTo({
          url: '/pagesHouse/pkList'
        })
      })
    } else {
      Taro.navigateTo({
        url: '/pagesHouse/pkList'
      })
    }
  }
  headerImgChange (e) {
    this.setState({
      curImgIndex: e.detail.current || 0
    })
  }
  previewImageHandle (cur, arr) {
    const current = `${cur}_plus`
    const urls = arr.map(item => {
      return `${item.img_url}_plus`
    })
    Taro.previewImage({
      current,
      urls
    })
  }


  renderInfo () {
    const { curId, curObj, token } = this.state
    const iconPos = require('@img/i_g_pos.png')
    const iconHeart = require('@img/i_g_heart.png')
    const iconHeart2 = require('@img/i_g_heart2.png')
    const cTagStr = curObj.custom_tag || ''
    const tagViews = cTagStr.split(',').map((tag, tagIndex) => {
      return (
        <View className="s" key={tagIndex}>{tag}</View>
      )
    })
    return (
      <View className="dtl-info">
        <View className="di-title">{curObj.estate_name}</View>
        <View className="di-sign">
          {
            curObj.estate_tag === '售罄'
            ? <View className="s t4">{curObj.estate_tag}</View>
            : curObj.estate_tag === '待售'
            ? <View className="s t3">{curObj.estate_tag}</View>
            : <View className="s t2">{curObj.estate_tag}</View>
          }
          {tagViews}
        </View>
        <Navigator url={'/pagesHouse/indexDtlAround?id=' + curId + '&name=' + curObj.estate_name} className="di-addr">
          <Image className="i" src={iconPos} />
          {curObj.address}
        </Navigator>
          {
            curObj.is_follow
            ?
            <View className="di-r cur" onClick={this.followHandle.bind(this, 'apiestateunfollow')}>
              <Image className="i" src={iconHeart2} />
              <View className="t">已关注</View>
            </View>
            :
            <View className="di-r" onClick={this.followHandle.bind(this, 'apiestatefollow')}>
              <Image className="i" src={iconHeart} />
              <View className="t">关注楼盘</View>
            </View>
          }
      </View>
    )
  }
  followHandle (apiStr) {
    const { curId, curObj } = this.state
    Taro.api.house[apiStr]({estate_id: curId}).then(res => {
      Taro.$msgConfirm(apiStr === 'apiestatefollow' ? '已关注' + curObj.estate_name : '已取消关注' + curObj.estate_name)
      this.getDtl()
    })
  }

  renderEntry () {
    const { curId, curObj } = this.state
    const icon1 = require('./img/dtl/1.png')
    const icon2 = require('./img/dtl/2.png')
    const icon3 = require('./img/dtl/3.png')
    const icon4 = require('./img/dtl/4.png')
    const icon5 = require('./img/dtl/5.png')
    const icon6 = require('./img/dtl/6.png')
    const icon7 = require('./img/dtl/7.png')
    const icon8 = require('./img/dtl/8.png')
    const icon9 = require('./img/dtl/9.png')
    const icon10 = require('./img/dtl/10.png')
    const icon10s = require('./img/dtl/10s.png')
    return (
      <View className="dtl-entry">
        <Navigator url={'/pagesHouse/produceType?id=' + curId + '&name=' + curObj.estate_name}  className="de-op">
          <Image className="i" src={icon1} />
          <View className="t">户型图</View>
        </Navigator>
        <Navigator url={'/pagesHouse/news?id=' + curId + '&name=' + curObj.estate_name} className="de-op">
          <Image className="i" src={icon2} />
          <View className="t">楼盘动态</View>
        </Navigator>
        <Navigator url={'/pagesHouse/indexDtlMore?id=' + curId + '&name=' + curObj.estate_name} className="de-op">
          <Image className="i" src={icon3} />
          <View className="t">楼盘详情</View>
        </Navigator>
        <Navigator url={'/pagesHouse/indexDtlAround?id=' + curId + '&name=' + curObj.estate_name} className="de-op">
          <Image className="i" src={icon4} />
          <View className="t">周边配套</View>
        </Navigator>
        <Navigator url={'/pagesHouse/photo?id=' + curId + '&name=' + curObj.estate_name} className="de-op">
          <Image className="i" src={icon5} />
          <View className="t">楼盘相册</View>
        </Navigator>
        {
          curObj.estate_tag === '二手'
          ?
          <Navigator url={`/pagesHouse/price?id=${curId}&name=${curObj.estate_name}`} className="de-op">
            <Image className="i" src={icon10s} />
            <View className="t">历史成交</View>
          </Navigator>
          :
          <Navigator url={`/pagesPlan/apply?eId=${curId}`} className="de-op">
            <Image className="i" src={icon10} />
            <View className="t">购房优惠</View>
          </Navigator>
        }
        <Navigator url={'/pagesMore/comment/list?id=' + curId + '&name=' + curObj.estate_name} className="de-op">
          <Image className="i" src={icon6} />
          <View className="t">楼盘评论</View>
        </Navigator>
        <Navigator url={'/pagesMore/news/list?type=lppc&name=楼盘测评'} className="de-op">
          <Image className="i" src={icon7} />
          <View className="t">楼盘测评</View>
        </Navigator>
        <Navigator url="/pagesMore/center/group" className="de-op">
          <Image className="i" src={icon8} />
          <View className="t">房友群</View>
        </Navigator>
        <Navigator url={'/pagesMore/center/loanCalc'} className="de-op">
          <Image className="i" src={icon9} />
          <View className="t">房贷计算</View>
        </Navigator>
      </View>
    )
  }

  renderOptionsDkSchool () {
    const { curObj } = this.state
    return (
      <View className="dtl-options scoped-school">
        <View className="do-title">
          <View className="t">对口学校</View>
          <View className="r2">注:目前该楼盘在此学区中</View>
        </View>
        {this.renderDkSchool()}
      </View>
    )
  }
  renderDkSchool () {
    const { curObj } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const arr = curObj.school_list.duikou || []
    const curItems = arr.map((item, index) => {
      return (
        <Navigator url={'/pagesSchool/indexDtl?id=' + item.id} className="lb-item" key={index}>
          <View className="lb-img">
            <Image className="img" src={item.pri_image + '_xs'} />
          </View>
          <View className="lb-info">
            <View className="lb-p1">{item.school_name}</View>
            <View className="lb-p2">{item.address}</View>
            <View className="lb-tag">
              <View className="t t1">{arrToObj(dictData.school_attrib)[item.school_attrib]}</View>
              <View className="t t4">{arrToObj(dictData.school_type)[item.school_type]}</View>
            </View>
          </View>
        </Navigator>
      )
    })
    return (
      <View className="l-list-box t2">
        {curItems}
      </View>
    )
  }

  renderOptionsGhSchool () {
    const { curObj } = this.state
    return (
      <View className="dtl-options scoped-school">
        <View className="do-title">
          <View className="t">可能就读</View>
          <View className="r2">注:未来该楼盘有可能划入该学校</View>
        </View>
        {this.renderGhSchool()}
      </View>
    )
  }
  renderGhSchool () {
    const { curObj } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const arr = curObj.school_list.guihua || []
    const curItems = arr.map((item, index) => {
      return (
        <Navigator url={'/pagesSchool/indexDtl?id=' + item.id} className="lb-item" key={index}>
          <View className="lb-img">
            <Image className="img" src={item.pri_image + '_xs'} />
          </View>
          <View className="lb-info">
            <View className="lb-p1">{item.school_name}</View>
            <View className="lb-p2">{item.address}</View>
            <View className="lb-tag">
              <View className="t t1">{arrToObj(dictData.school_attrib)[item.school_attrib]}</View>
              <View className="t t4">{arrToObj(dictData.school_type)[item.school_type]}</View>
            </View>
          </View>
        </Navigator>
      )
    })
    return (
      <View className="l-list-box t2">
        {curItems}
      </View>
    )
  }


  renderQrcode () {
    const qrcodeImg = 'http://icon.honglounews.com/miniqrcode.jpg'
    return (
      <Image src={qrcodeImg} className="g-img-qrcode"  onClick={this.previewQrcodeImageHandle.bind(this, qrcodeImg, [qrcodeImg])} />
    )
  }
  previewQrcodeImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }


  renderOptionsInfo () {
    const dictData = Taro.getStorageSync('dictData')
    const { curObj, curId } = this.state
    const product_type = curObj.product_type || ''
    const productTypeArr = product_type.split(',').map(v => {
      return arrToObj(dictData.product_type)[v]
    })
    return (
      <View className="dtl-options">
        {this.renderQrcode()}
        <View className="do-title">
          <View className="t">基本信息</View>
          <Navigator url={'/pagesHouse/indexDtlMore?id=' + curId + '&name=' + curObj.estate_name} className="r">更多楼盘详细信息{' >'}</Navigator>
        </View>
        <View className="do-content">
          <View className="do-p">
            <View className="k">所属区域</View>
            <View className="v">{arrToObj(dictData.area_type)[curObj.area_type]}</View>
          </View>
          <View className="do-p">
            <View className="k">产品类型</View>
            <View className="v">{productTypeArr.length > 0 ? `${productTypeArr.join('/')}` : ''}</View>
          </View>
          <View className="do-p">
            <View className="k">参考价格</View>
            <View className="v">{curObj.price_range}/㎡</View>
          </View>
          <View className="do-p">
            <View className="k">户型面积</View>
            <View className="v">{curObj.built_area}㎡</View>
          </View>
          <View className="do-p">
            <View className="k">总户数</View>
            <View className="v">{curObj.household || '未知'}</View>
          </View>
          <View className="do-p">
            <View className="k">车位数</View>
            <View className="v">{curObj.parking || '未知'}</View>
          </View>
          <View className="do-p">
            <View className="k">绿化率</View>
            <View className="v">{curObj.green_rate || '未知'}%</View>
          </View>
          <View className="do-p">
            <View className="k">初次交付</View>
            <View className="v">{curObj.deliver_time || '未知'}</View>
          </View>
        </View>
      </View>
    )
  }

  renderDesc () {
    const { curObj } = this.state
    return (
      <View className="dtl-options">
        <View className="do-title">
          <View className="t">洪楼简评</View>
        </View>
        <View className="do-content">
          <View className="scoped-desc">{curObj.remarked}</View>
        </View>
      </View>
    )
  }

  renderProductType () {
    const { curObj } = this.state
    const aData = curObj.area_data || []
    const dictData = Taro.getStorageSync('dictData')
    const ptObj = arrToObj(dictData.product_type)
    const htObj = arrToObj(dictData.house_type)
    let ptArr = []
    if (aData) {
      aData.map(one =>{
        one.house_type_list.map(two => {
          two.area_list.map(three => {
            ptArr.push({
              imgUrl: three.img_url + '_xs',
              area: three.area + '㎡',
              ptName: ptObj[one.product_type_val],
              htName: htObj[two.house_type_val],
            })
          })
        })
      })
    }
    const pt3Arr = ptArr.slice(0, 3)
    return (
      <View className="dtl-options" onClick={this.morePtLink.bind(this)}>
        <View className="do-title">
          <View className="t">户型图</View>
          <View className="r">全部户型图{'>>'}</View>
        </View>
        <View className="do-content">
          <View className="scoped-pt">
            <View className="sp-wrap">
              {
                pt3Arr.map((item, index) => {
                  return (
                    <View className="sp-item" key={index}>
                      <View className="w">
                        <Image className="img" src={item.imgUrl} />
                        <View className="p1">
                          <View className="bg"></View>
                          <View className="t">{item.area}({item.ptName})</View>
                        </View>
                      </View>
                      <View className="p2">{item.htName}</View>
                    </View>
                  )
                })
              }
            </View>
            {
              ptArr.length > 2
              &&
              <View className="sp-more">点击查看更多</View>
            }
          </View>
          {
            aData.length === 0
            &&
            <ListMore isOther={true} text="户型图整理中"/>
          }
        </View>
      </View>
    )
  }
  morePtLink () {
    const { curObj } = this.state
    Taro.navigateTo({
      url: '/pagesHouse/produceType?id=' + curObj.id + '&name=' + curObj.estate_name
    })
  }

  renderPos () {
    const { curObj } = this.state
    const markers = [{
      longitude: curObj.longitude,
      latitude: curObj.latitude,
      // iconPath: require('@img/images/icon_g_pos.png'),
      // width: '20px',
      // height: '20px',
      // zIndex: 9999,
      label: {
        content: curObj.estate_name,
        color: '#333',
        fontSize: 12,
        // anchorX: -(0.5 * (5 * 24))/2,
        anchorY: -50,
        textAlign: 'center',
        bgColor: '#fff',
        padding: 5,
        borderRadius: 5,
        borderColor: '#f2f2f2',
        borderWidth: 1,
      }
    }]
    return (
      <View className="dtl-options" onClick={this.posHandle.bind(this)}>
        <View className="do-title">
          <View className="t">楼盘位置</View>
          {/* <View className="s">[详情]</View> */}
        </View>
        <View className="l-list-box scoped-list-map">
          <Map
            className="m"
            longitude={curObj.longitude}
            latitude={curObj.latitude}
            scale="14"
            markers={markers}
          />
        </View>
      </View>
    )
  }
  posHandle () {
    const { curObj } = this.state
    const key = '5WFBZ-LCZ3J-D5AFM-KNUUL-BTT46-45BWB'
    const referer = '洪楼Plus'
    const location = JSON.stringify({
      latitude: curObj.latitude,
      longitude: curObj.longitude
    })
    const category = '地铁公交,医院,购物美食'
    Taro.navigateTo({
      url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location + '&category=' + category
    })
  }


  renderOptionsNews () {
    return (
      <View className="dtl-options">
        <View className="do-title">
          <View className="t">洪楼观点</View>
        </View>
        <News onRef={this.refNews} />
      </View>
    )
  }
  refNews = (ref) => {
    this.subNews = ref
  }


  renderComment () {
    const { curObj } = this.state
    return (
      <View className="dtl-options">
        <View className="do-title">
          <View className="t">大家怎么看</View>
          <Navigator url={'/pagesMore/comment/list?id=' + curObj.id + '&name=' + curObj.estate_name} className="r">查看更多{' >'}</Navigator>
        </View>
        <Comment onRef={this.refComment} getDtl={this.getDtl.bind(this)} />
      </View>
    )
  }
  refComment = (ref) => {
    this.subComment = ref
  }


  

  openLoginPopup (obj) {
    this.setState({
      isLoginPopupShow: true
    })
  }
  closeLoginPopup (str) {
    this.setState({
      isLoginPopupShow: false
    })
    if (str && str === 'success') {
      this.getDtl()
    }
  }

  getUserProfile (e) {
    wx.getUserProfile({
      desc: '用于完善头像和昵称资料',
      success: (res) => {
        const dtlObj = res || {}
        this.setState({
          userInfo: dtlObj.userInfo
        })
        Taro.setStorageSync('APP_userInfo', dtlObj.userInfo)
        Taro.$msgConfirm(`登录成功~有任何建议或者反馈，可以进个人中心给我们反馈哦`, () => {}, () => {})
      }
    })
  }

  linkHome () {
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
  renderGoHome () {
    const icon = require('@img/images/icon_go_home.png')
    return (
      <Image className="g-go-home" src={icon} onClick={this.linkHome.bind(this)}/>
    )
  }

  linkPlan () {
    const {id} = this.$router.params
    Taro.navigateTo({
      url: `/pagesPlan/apply?eId=${id}`
    })
  }
  renderPlan () {
    const footerBanner = require('./img/dtl/footer_banner.png')
    return (
      <View className="scoped-footer">
        <Image src={footerBanner} className="img" onClick={this.linkPlan.bind(this)}></Image>
      </View>
    )
  }

  renderYH () {
    const { curObj } = this.state
    const lotteryObj = curObj.estate_lottery || {}
    let houseImg = []
    if (lotteryObj.house_img) houseImg = lotteryObj.house_img.split(',')
    let lotteryImg = []
    if (lotteryObj.lottery_img) lotteryImg = lotteryObj.lottery_img.split(',')
    let infoImg = []
    if (lotteryObj.info_img) infoImg = lotteryObj.info_img.split(',')
    return (
      <View className="scoped-yh">
        <View className="sy-wrap">
          {
            lotteryObj.result && lotteryImg.length > 0
            &&
            <View>
              <View className="sy-p">{lotteryObj.result}</View>
              <View className="sy-op">
                <View className="l">摇号结果表</View>
                <View className="r">
                  {
                    lotteryImg.map((hImg, hi) => {
                      return (
                        <View className="o" key={hi} onClick={this.YHImageHandle.bind(this, hImg, lotteryImg)}>
                          <Image src={hImg + '_xs'} className="img" />
                          <View className="tips">
                            <View className="bg"></View>
                            <View className="t">查看大图</View>
                          </View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            </View>
          }
          {
            lotteryObj.under_way && houseImg.length > 0
            &&
            <View>
              <View className="sy-p">{lotteryObj.under_way}</View>
              <View className="sy-op">
                <View className="l">一房一价表</View>
                <View className="r">
                  {
                    houseImg.map((hImg, hi) => {
                      return (
                        <View className="o" key={hi} onClick={this.YHImageHandle.bind(this, hImg, houseImg)}>
                          <Image src={hImg + '_xs'} className="img" />
                          <View className="tips">
                            <View className="bg"></View>
                            <View className="t">查看大图</View>
                          </View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            </View>
          }
          {
            infoImg.length > 0
            &&
            <View>
              <View className="sy-op">
                <View className="l">项目公示表</View>
                <View className="r">
                  {
                    infoImg.map((hImg, hi) => {
                      return (
                        <View className="o" key={hi} onClick={this.YHImageHandle.bind(this, hImg, houseImg)}>
                          <Image src={hImg + '_xs'} className="img" />
                          <View className="tips">
                            <View className="bg"></View>
                            <View className="t">查看大图</View>
                          </View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            </View>
          }
        </View>
      </View>
    )
  }
  YHImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }

  render () {
    const { userInfo, token, curObj } = this.state
    const uInfo = userInfo || Taro.getStorageSync('APP_userInfo')
    const { isLoginPopupShow } = this.state
    const pages = getCurrentPages()
    const pagesLength = pages.length
    const schoolList = curObj.school_list || {}
    const { YH } = this.$router.params
    return (
      <View className="l-box">
        {
          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>
        }
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
        {this.renderHeader()}
        {this.renderInfo()}
        {
          YH
          &&
          this.renderYH()
        }
        {this.renderEntry()}
        {this.renderOptionsInfo()}
        {
          curObj.remarked
          &&
          this.renderDesc()
        }
        {this.renderProductType()}
        {this.renderOptionsNews()}
        {
          schoolList.duikou && schoolList.duikou.length > 0
          &&
          this.renderOptionsDkSchool()
        }
        {
          schoolList.guihua && schoolList.guihua.length > 0
          &&
          this.renderOptionsGhSchool()
        }
        {this.renderComment()}
        {this.renderPos()}
        {pagesLength < 3 && this.renderGoHome()}
        {/* {this.renderPlan()} */}
      </View>
    )
  }
}

export default Index
