import Taro, { Component } from '@tarojs/taro';
import FormIdCollector from '@components/formIdCollector'
import './index.scss'
import ProjectItem from './item'
import Banner from './banner'
import HelpGroupBanner from './swiper'
import ActivityItem from '../activity/item'


import ready from '@utils/ready'

import { queryBanners, savePoint, updatePoint } from '@services/common'
import { queryNewsList, queryHelpGroup } from '@services/news'
import { queryActivityList } from '@services/activity'
import { dispatchCitySelected } from '@actions/city'
import { ROLE_CODE } from '@constants/user'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/project'
import { getThumbnail } from '@utils/tools'
import QQMapWX from '@lib/qqmap-wx-jssdk.min'
import Notice from '@components/Notice'

const accountInfo = wx.getAccountInfoSync();

@connect(
  state => ({ ...state.project, ...state.city, ...state.user }),
  { ...actions, dispatchCitySelected }
)

export default class Index extends Component {
  config = {
    navigationBarTitleText: '橙蕉'
  }

  state = {
    maskVisible: false,
    keywords: '',
    loaded: false,
    maskBanner: '',
    shareImg: 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/upload/images/1565358322510-share.jpg',
    bannerList: [],
    helpGroupList: [],
    newsList: [],
    activityList: [],
    recordId: null,
    visBanner: false,
    indicatorDots: false,
    vertical: true
  }

  componentWillMount () {
    this.qqmapsdk = new QQMapWX({
      key: 'TIIBZ-ZJG33-52T3L-Y3X4Q-NWKLV-KUB3B'
    })

    ready.queue(() => {
      this.loadOpenScreenBanner()
      this.getLocation()

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

  componentDidShow () {
    if (this.props.curCity.id) {
      ready.queue(() => {
        this.loadData()
      })
    }
  }

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

  getLocation () {
    const { cityList, userInfo: { person: { org } } } = this.props
    let defaultCity = cityList.filter(item => {
      return item.id == org.defaultCityId
    })


    console.log('-----defaultCity-->', defaultCity)
    Taro.getLocation().then(location => {
      Taro.setStorageSync('lat', location.latitude)
      Taro.setStorageSync('lon', location.longitude)


      this.qqmapsdk.reverseGeocoder({
        location,
        success: (res) => {
          // debugger
          let city = res.result.address_component.city

          console.log('-----city-->', city)
          console.log('-----cityList-->', cityList)


          let curCity = cityList.filter(item => {
            return item.name == city
          })




          Taro.showToast({
            title: `当前定位城市:${(curCity[0] || {}).name}`,
            icon: 'none',
          })

          this.updateCity(curCity[0] || defaultCity[0])
        },
        fail: (error) => {


          Taro.showToast({
            title: `定位城市错误...`,
            icon: 'none',
          })
          console.error(err)
          this.updateCity(defaultCity[0])
        },
      })
    }).catch(err => {
      if (err.errMsg === 'getLocation:fail auth deny') {
        Taro.showModal({
          content: '请同意授权您的定位功能',
          showCancel: false,
        })
      } else {
        Taro.showToast({
          title: `定位城市错误...`,
          icon: 'none',
        })
      }
      console.error(err)
      this.updateCity(defaultCity[0])
    })
  }

  updateCity (payload) {


    this.props.dispatchCitySelected(payload).then(res => {
      this.loadData()
    })
  }

  loadData () {
    this.loadBannerList()
    this.loadHelpGroupList()
    this.loadNewsList()
    this.loadActivityList()
    this.loadList()
  }

  loadOpenScreenBanner () {
    const payload = {
      // showPosition: 'index'
    }
    // 获取开屏广告图
    queryBanners('screen', payload).then(res => {
      const banner = res[0]
      if (banner) {
        Taro.hideTabBar({
          animation: true
        })
      }
      this.setState({
        maskVisible: banner ? true : false,
        maskBanner: banner
      })
    })
  }
  loadBannerList () {
    const { curCity } = this.props
    // 获取首页banner
    const payload = {
      showPosition: 'index'
    }
    if (curCity.id) {
      payload.cityId = curCity.id
    }
    this.setState({
      visBanner: false
    })


    queryBanners('banner', payload).then(res => {
      this.setState({
        visBanner: true,
        bannerList: res || [],
      })
    })
  }

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


  loadNewsList () {
    const { curCity } = this.props
    const payload = {
      pageNumber: 1,
      pageSize: 2
    }
    if (curCity.id) {
      payload.cityId = curCity.id
    }
    queryNewsList(payload).then(res => {
      this.setState({
        newsList: res.records || []
      })
    })
  }

  loadActivityList () {
    const { curCity } = this.props
    const payload = {
      pageNumber: 1,
      pageSize: 1
    }
    if (curCity.id) {
      payload.cityId = curCity.id
    }
    queryActivityList(payload).then(res => {
      this.setState({
        activityList: res.list || []
      }, () => {
        console.log(this.state.activityList)
      })
    })
  }

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

    const payload = {
      name: keywords
    }
    if (curCity.id) {
      payload.cityId = curCity.id
    }
    Taro.showLoading()
    this.props.dispatchProjectList(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
      })
    })
  }

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

    savePoint({
      event: 'share',
      eventType: 'main',
      propertyName: '首页分享',
      data: '{}'
    }).then(res => {
      console.log('首页分享')
    })
    return {
      title: '橙蕉 精准获客平台',//分享内容
      path: `/pages/project/index?from=share&recommender=${personId}`,//分享地址
      imageUrl: this.state.shareImg
    }
  }

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

  handleBannerClick = (item) => {
    console.log(this, "this")
    this.redirectTo(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;

      // 其他
      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({
      animation: true
    })
  }

  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 () {
    const {
      userInfo: { person: { personType } }
    } = this.props
    if (personType === ROLE_CODE['DRIFT'] || !personType) {
      // 游客或者客户 区别是否有电话
      Taro.navigateTo({
        url: `/pages/agent/become/index`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/agent/recommend/index?type=index&cityId=` + this.props.curCity.id
      })
      console.log(this.props.curCity.id, "this.props.curCity.id")
    }
  }
  toMapHouse () {
    Taro.navigateTo({
      url: `/pages/project/map/index`
    })
  }


  renderProjectList () {
    const { proList: { records } } = this.props
    const { helpGroupList } = this.state
    console.log(records, 'proList')
    return (
      <Block>
        {
          records.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/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">
                {records.map(item => (
                  <FormIdCollector key={item.buildingId}>
                    <ProjectItem
                      onClick={this.onViewDetail.bind(this, item)}
                      data={item}
                    />
                  </FormIdCollector>
                ))}
              </View>
            </View >
          )
        }

        {console.log(helpGroupList, 'helpGroupList')}
        {
          helpGroupList.length > 0 &&
          <View
            style={{
              position: 'relative', padding: '20px 15px 0 15px'
            }}>

            <HelpGroupBanner
              style={{
                borderRadius: '6px',
                height: '230rpx'
              }}
              indicatorDots={false}
              list={helpGroupList}
              onClick={this.handleHelpGroupClick}>
            </HelpGroupBanner>
          </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={getThumbnail(maskBanner.image)}
            onClick={this.handleMaskBannerClick.bind(this, maskBanner)}>
          </Image>
          <Icon className="iconfont close icon-buoumaotubiao20" onClick={this.handleMaskClose}></Icon>
        </View>
      </View>
    )
  }


  render () {
    const { curCity } = this.props
    const { newsList } = this.state
    const { userInfo: { person: { personType } } } = this.props

    return (
      <Block>
        {this.state.loaded && (
          <View className="page">
            <Notice></Notice>
            <ScrollView
              scrollY
              className='home'>
              <View className="section section-top" style={{ marginTop: 0, paddingTop: 0 }}>
                <View
                  style={{
                    height: '600rpx', position: 'relative'
                  }}>
                  {
                    this.state.visBanner && (
                      <Banner
                        style={{
                          height: '600rpx'
                        }}
                        indicatorDots={true}
                        list={this.state.bannerList}
                        onClick={this.handleBannerClick}
                        onChange={() => (1)}
                      >

                      </Banner>
                    )
                  }
                </View>
                <View className="top-box">
                  <View className="search" onClick={this.handleToHouseList}>
                    <Image className="search-icon" src={require('@assets/search.png')} />
                    <Input className="search-input" placeholder-style="color:#fff" placeholder="输入你想查询的楼盘"></Input>
                  </View>
                  <View className="location" onClick={this.handleLocationClick}>
                    <Image className="location-icon" src={require('@assets/map.png')} />
                    <Text className="location-text">{curCity.id ? curCity.name : '正在定位'}</Text>
                  </View>
                </View>

                {
                  (personType !== ROLE_CODE['CONSULTANT']) && (
                    <View className='section sectionn-customer' >
                      <View className='section-content' onClick={this.toRecomonedPage.bind(this, personType)}>
                        <Image src={require('@assets/index/logo.png')} className='logo_img' mode="widthFix"></Image>
                        <View className='section-content_title'>
                          <Text>推荐客户 赢积分好礼</Text>
                          <Text>更多惊喜在积分商城等着你</Text>
                        </View>
                        <Image src={require('@assets/index/recommend.png')} className='section-content_img' mode="widthFix"></Image>
                      </View>
                    </View>
                  )
                }


              </View>


              {/* 推荐楼盘 */}
              {this.renderProjectList()}

            </ScrollView>

            {this.state.maskVisible && this.renderMaskBanner()}
          </View >
        )}
      </Block>
    )
  }
}