import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import ProjectItem from './item'
import Banner from './banner'
import Newsbanner from './newsbanner'
import Activity from './activity'
import BannerTwo from './swiper'
import ready from '@/utils/ready'
import { savePoint, updatePoint, queryExtContents, queryIndexIcons } from '@/services/common'
import { queryHelpGroup } from '@/services/news'
import { getIndexShare } from '@/services/user'
import { dispatchCitySelected } from '@/actions/city'
import { SET_SCREEN_SHOWED } from '@/constants/project'
import { getStore, connect } from '@tarojs/redux'
import * as actions from '@/actions/project'
import { transferImage } from '@/utils/tools'
import Notice from '@/components/Notice'
import NavIcons from './NavIcons'

@connect(
  state => ({ ...state.project, ...state.city, ...state.user, system: state.system }),
  { ...actions, dispatchCitySelected }
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: ''
  }
  state = {
    maskVisible: false,
    keywords: '',
    loaded: false,
    maskBanner: '',
    shareImg: '',
    imgDocument: '',
    // adImage: advImageOfApp,
    bannerList: [],
    helpGroupList: [],
    activityList: [],
    recordId: null,
    visBanner: false,
    visPropagandaBanner: false,
    indicatorDots: false,
    vertical: true,
    achieve: false,
    propagandaBanner: [],
    newsShow: false,
    city: null,
    iconList: [],
  }

  componentWillMount() {

    Taro.hideTabBar()

    ready.queue(() => {

      Taro.setNavigationBarTitle({ title: `${this.props.userInfo.miniApp.name}欢迎你` })
      const city = this.state.city || this.props.curCity
      this.loadData({ curCity: city })

      this.getIndexShareInfo()

      savePoint({
        event: 'index',
        eventType: 'main',
        propertyName: '进入首页',
        data: '{}'
      }).then(res => {
        this.setState({
          recordId: res.recordId
        })
        console.log('进入首页')
      })
    })
  }

  getIndexIcons() {
    queryIndexIcons().then(res => {
      if (res && res.length) {
        this.setState({ iconList: res })
      }
    })
  }

  getIndexShareInfo() {
    getIndexShare().then(res => {

      const shareInfo = (res || []).filter(item => item.imgType === 'index')[0]
      this.setState({
        shareImg: (shareInfo || {}).imgUrl,
        imgDocument: (shareInfo || {}).imgDocument,
      })
      console.log(shareInfo, '首页分享信息')
    })
  }

  toChatList() {
    // const { dispatch } = getStore()
    // dispatch({ type: DECREASE_UNREADNUM })
    Taro.navigateTo({
      url: '/pages/im/list/index'
    })
  }
  componentDidShow() {
    // this.getIndexShareInfo()

    const city = this.state.city || this.props.curCity
    if (city && city.id) {
      ready.queue(() => {
        // Taro.hideTabBar()
        this.loadData({ curCity: city })
      })
    }
  }

  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  loadData(props = {}) {
    this.loadHelpGroupList(props)
    this.loadList(props)
    this.loadExtContents(props)
    this.getIndexIcons()
  }

  loadExtContents(props) {
    const curCity = this.state.city || props.curCity

    this.setState({
      visBanner: false,
      visPropagandaBanner: false
    })

    queryExtContents({ cityId: curCity.id }).then(res => {
      // 开屏广告
      const maskBanner = (res || []).filter(x => x.showType === 'screen')[0] || {}
      const maskVisible = maskBanner.contentId && this.props.screenShow !== maskBanner.contentId

      // 首页 banner
      const bannerList = (res || []).filter(x => x.showType === 'banner' && x.showPosition === 'index')

      // 首页 宣传位
      const propagandaBanner = (res || []).filter(x => x.showType === 'propaganda')

      this.setState({
        maskVisible,
        visBanner: true,
        visPropagandaBanner: true,
        maskBanner,
        bannerList,
        propagandaBanner,
      }, () => {
        if (Taro.getStorageSync('firstLoading') != '8') {
          const { dispatch } = getStore()
          dispatch({ type: SET_SCREEN_SHOWED, payload: maskBanner.contentId })
        } else {
          Taro.setStorageSync('firstLoading', '6')
        }
        if (maskVisible) {
          Taro.hideTabBar()
        }
      })
    })
  }

  loadHelpGroupList(props) {
    const curCity = this.state.city || props.curCity

    queryHelpGroup({ cityId: curCity.id, buildingId: '' }).then(res => {
      this.setState({
        helpGroupList: res || []
      })
    })
  }


  loadList(props) {
    const { keywords } = this.state
    const curCity = this.state.city || props.curCity

    const payload = {
      name: keywords,
      pageSize: 10,
    }
    if (curCity.id) {
      payload.cityId = curCity.id
    }
    Taro.showLoading()

    this.props.dispatchIndexProjects(payload).then(res => {
      if (!this.state.loaded && res.records.length <= 0) {
        // let city = {
        //   name: '南京市',
        //   id: 320100
        // }
        // this.updateCity(city)
        // return
        Taro.showToast({
          title: '当前城市暂无楼盘',
          icon: 'none'
        })
      }
      Taro.hideLoading()
      this.setState({
        loaded: true
      })
      if (!this.state.maskVisible) {
        Taro.showTabBar()
      }
    })

  }

  //   转发
  onShareAppMessage = () => {
    const {
      userInfo: { person: { personId } }
    } = this.props

    savePoint({
      event: 'share',
      eventType: 'main',
      propertyName: '首页分享',
      data: '{}'
    }).then(res => {
      console.log('首页分享')
    })
    return {
      title: this.state.imgDocument || ` 精准获客—上${this.props.userInfo.miniApp.name || '橙蕉'}，买好房`,//分享内容
      path: `/pages/project/index?from=share&recommender=${personId}`,//分享地址
      imageUrl: this.state.shareImg || 'https://njcj.oss-cn-shanghai.aliyuncs.com/miniapp/upload/images/1574145199853-97feda7895c65be33aa234a7b81b37f.jpg',
    }
  }

  onViewDetail(item) {
    Taro.navigateTo({
      url: `/pages/project/detail/index?id=${item.buildingId}`
    })
  }

  handlePropagandaClick = (item) => {
    if (item.contentType && item.contentType != "nothing") {
      this.redirectTo(item)
    } else {
      console.log(item, "item")
    }
  }
  handleBannerClick = (item) => {
    if (item.contentType && item.contentType != "nothing") {
      this.redirectTo(item)
    } else {
      console.log(item, "item")
    }
  }

  redirectTo({ targetId, contentType, buildingId } = {}) {
    switch (contentType) {
      // 项目
      case 'project':
        Taro.navigateTo({
          url: '/pages/project/detail/index?id=' + buildingId
        })
        return;

      // 活动
      case 'activity':
        Taro.navigateTo({
          url: '/pages/activity/detail/index?id=' + targetId
        })
        return;

      // 助力
      case 'help':
        Taro.navigateTo({
          url: '/pages/activity/detail/assistance?id=' + targetId
        })
        return;

      // 拼团
      case 'group':
        Taro.navigateTo({
          url: '/pages/activity/detail/assemble?id=' + targetId
        })
        return;

      // 资讯
      case 'news':
        Taro.navigateTo({
          url: '/pages/news/detail/index?id=' + targetId
        })
        return;
      // h5
      case 'h5':
        Taro.navigateTo({
          url: '/pages/project/h5Page?id=' + targetId
        })
        return;
      // live
      case 'live':
        Taro.navigateTo({
          url: '/onlineSelling/pages/live/index?id=' + targetId
        })
        return;
      // salesBatch
      case 'salesBatch':
        Taro.navigateTo({
          url: `/onlineSelling/pages/houseList/index?id=${targetId}`
        })
        return;

      // 其他
      case 'others':
      default:
        this.handleMaskClose()
        return;
    }
  }

  handleHelpGroupClick(item) {
    if (item.type == 1) {
      Taro.navigateTo({
        url: '/pages/activity/detail/assistance?id=' + item.activityId
      })
    } else {
      Taro.navigateTo({
        url: '/pages/activity/detail/assemble?id=' + item.activityId
      })
    }
  }

  handleMaskClose() {
    this.setState({
      maskVisible: false
    })
    Taro.showTabBar()
  }

  makePhoneCall = () => {
    // App.zhuge.track('点击电话咨询')
    Taro.makePhoneCall({
      phoneNumber: '0772-6861111'
    })

    savePoint({
      event: 'phone',
      eventType: 'main',
      propertyName: '点击电话咨询',
      data: '{}'
    }).then(res => {
      console.log('点击电话咨询')
    })
  }

  handleMaskBannerClick(data) {
    this.redirectTo(data)
  }

  handleLocationClick() {
    Taro.navigateTo({
      url: `/pages/city/index`
    })
  }

  handleToHouseList() {
    Taro.navigateTo({
      url: '/pages/project/list/index'
    })
  }

  handleProItemClick() {
    Taro.navigateTo({
      url: '/pages/project/list/index'
    })
  }
  // CONSULTANT: 'Realty Consultant', // 置业顾问
  // ESTATE_AGENT: 'estate agent', // 独立经纪人
  // CHANNEL_AGENT: 'channel agent', // 渠道经纪人
  // DRIFT: 'drift', // 游客
  // CUSTOMER: 'customer' // 客户
  toRecomonedPage() {

    Taro.navigateTo({
      url: `/useless/pages/agent/recommend/index?type=index&cityId=` + this.props.curCity.id
    })

  }
  toMapHouse() {
    Taro.navigateTo({
      url: `/pages/project/map/index`
    })
  }

  handleAuthPhoneSuccess(curCity) {

    console.log(curCity, 'curCity')

    Taro.navigateTo({
      url: `/useless/pages/agent/recommend/index?type=index&cityId=` + curCity.id
    })
  }


  renderProjectList() {
    const { proList: { records = [] } } = this.props

    const list = records.filter(item => item.isMain === 1)
    // console.log(records, 'proList')
    return (
      <Block>
        {
          list.length > 0 && (
            < View className="houses" >
              <View className="section-head">
                <View style="display:flex;align-items:center">
                  <Text className="section-head__title" onClick={this.handleProItemClick}>推荐楼盘
                </Text>
                  <Image src={require('@/assets/index/inspection.png')} onClick={this.toMapHouse} className='map-img'></Image>
                  {/* <Image src={require('@/assets/index/map.png')} onClick={this.toMapHouse} className='map-img'></Image>
                  <Text className='map-txt' onClick={this.toMapHouse}>地图看房</Text> */}
                </View>
                <View className="section-head__more" onClick={this.handleProItemClick}>
                  查看更多<Text className="iconfont icon-more"></Text>
                </View>
              </View>
              <View className="section-content">
                {list.map((item, index) => (
                  <ProjectItem
                    key={index + 'buildingId'}
                    onClick={this.onViewDetail.bind(this, item)}
                    data={item}
                  />
                ))}
              </View>
            </View >
          )
        }

        <View className="last-text">已经到底了~</View>
      </Block>
    )
  }

  renderMaskBanner() {
    const { maskBanner = {} } = this.state
    return (
      <View className="mask-banner">
        <View className="content">
          <Image
            mode="widthFix"
            className="img"
            src={transferImage(maskBanner.image)}
            onClick={this.handleMaskBannerClick.bind(this, maskBanner)}>
          </Image>
          <Icon className="iconfont close icon-buoumaotubiao20" onClick={this.handleMaskClose}></Icon>
        </View>
      </View>
    )
  }
  changeCurrent(event) {
    const current = event.detail.current
    this.props.onChange && this.props.onChange(current)
  }

  handleNoticeClick = (item) => {
    Taro.navigateTo({
      url: '/pages/news/detail/index?id=' + item.newsId
    })
  }
  toNewsList() {
    Taro.getApp().props.projectIndex = 1
    Taro.switchTab({
      url: `/pages/activity/activity`,
      fail: res => {
        Taro.getApp().props.projectIndex = 0
      }
    })
  }
  toShopMallPage() {
    Taro.switchTab({
      url: `/pages/shop/index`
    })
  }
  toPolicyPage() {
    Taro.navigateTo({
      url: '/pages/policy/index?from=mine',
    })
  }

  handleNewsbannerShow = (visiable) => {
    this.setState({
      newsShow: visiable
    })
  }
  render() {
    const { achieve, helpGroupList, propagandaBanner, newsShow, iconList } = this.state
    const { curCity, unReadNum, userInfo: { person } } = this.props

    return (
      <Block>
        {this.state.loaded && (
          <View className="page">
            <Notice></Notice>
            {!achieve && <ScrollView
              scrollY
              className='home'>
              {/* 搜索框 */}
              <View className="top-box">
                <View className="search" onClick={this.handleToHouseList}>
                  <Image className="search-icon" src={require('@/assets/index/search.png')} />
                  <Input className="search-input" placeholder-style="color:#B8B8B8" placeholder="输入你想查询的楼盘"></Input>
                </View>
                <View className="location" onClick={this.handleLocationClick}>
                  <Image className="location-icon" src={require('@/assets/index/location.png')} />
                  <Text className="location-text">{curCity.id ? curCity.shortname : '正在定位'}</Text>
                  <View class="arrow_down"></View>
                </View>
              </View>
              {/* 头部轮播图 */}
              <View className="section section-top" style={{ marginTop: 0, paddingTop: 0 }}>
                <View
                  style={{
                    height: '464rpx', position: 'relative'
                  }}>
                  {
                    this.state.visBanner && (
                      <Banner
                        style={{
                          height: '464rpx'
                        }}
                        indicatorDots={false}
                        list={this.state.bannerList}
                        onClick={this.handleBannerClick}
                        onChange={() => (1)}
                      >
                      </Banner>
                    )
                  }
                </View>
              </View>
              {/* 菜单栏 */}
              <NavIcons city={curCity} person={person} iconList={iconList} ></NavIcons>
              {/* <View style={propagandaBanner.length > 0 ? "border-bottom:20rpx solid #f5f5f5" : ''}> */}
              <View style={(newsShow || propagandaBanner.length > 0) ? "border-bottom:20rpx solid #f5f5f5" : ''}>
                {/* 展示位轮播图 */}
                {
                  this.state.visPropagandaBanner && propagandaBanner.length > 0 &&
                  <View
                    style={{
                      position: 'relative', padding: '20px 15px 0 15px'
                    }}>
                    <BannerTwo
                      style={{
                        borderRadius: '6px',
                        height: '172rpx'
                      }}
                      // forwardShow={true}
                      indicatorDots={false}
                      list={propagandaBanner}
                      onClick={this.handlePropagandaClick}>
                    </BannerTwo>
                  </View>
                }
                {/* 资讯 */}
                <Newsbanner showNesBox={this.handleNewsbannerShow} cityId={curCity.id} onClick={this.handleNoticeClick} onClickMore={this.toNewsList} />
              </View >
              {/* 参加活动*/}
              {
                helpGroupList && helpGroupList.length &&
                (<Activity helpGroupList={helpGroupList} cityId={curCity.id} />)
              }
              {/* 推荐楼盘 */}
              {this.renderProjectList()}
            </ScrollView>}
            {this.state.maskVisible && this.renderMaskBanner()}
            <View className="chat-box" onClick={this.toChatList}>
              {unReadNum > 0 && <View className="red-dot"></View >}
              <Image className='chat-img' src={require('@/assets/person/communicate.png')}></Image>
            </View >
          </View >
        )}
      </Block>
    )
  }
}
