import Taro, { Component } from '@tarojs/taro';
import FormIdCollector from '@components/formIdCollector'
import './index.scss'
import ProjectItem from './item'
import Banner from './banner'
import Newsbanner from './newsbanner'
import Activity from './activity'
import BannerTwo from './swiper'
// import ActivityItem from '../activity/item'
import ready from '@utils/ready'
import { getLocationCity } from '@services/map'
import { queryBanners, savePoint, updatePoint } from '@services/common'
import { queryHelpGroup } from '@services/news'
import { getIndexShare } from '@services/user'
import { queryActivityList } from '@services/activity'
import { dispatchCitySelected } from '@actions/city'
import { ROLE_CODE, DECREASE_UNREADNUM } from '@constants/user'
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 Authorize from '@components/authorize'
import * as noticeType from '@constants/common.js'


const { miniProgram: { appId } } = wx.getAccountInfoSync();

// // 分享图
// let shareImageOfApp;
// // banner 广告图
// let advImageOfApp;

// switch (appId) {
//   case 'wx755faa4b3ec76cd3':
//     // 尾房宝
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/cff400dab32e9230f6bf7498b8291d7.jpg';
//     advImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/f58480ff83787b64235b729bca5d805.jpg';
//     break;

//   case 'wx1d981b76761246ce':
//     // 橙蕉嘉房
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/%E6%A9%99%E8%95%89%E5%98%89%E6%88%BF.jpg';
//     break;

//   case 'wxa431cc21403b51bb':
//     // 橙蕉海房
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/%E6%A9%99%E8%95%89%E6%B5%B7%E6%88%BF.jpg';
//     break;

//   case 'wx25c971cd14b0e11d':
//     // 橙蕉越房
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/%E6%A9%99%E8%95%89%E8%B6%8A%E6%88%BF.jpg';
//     break;

//   case 'wx593a402c7c27beb9':
//     // 橙蕉金房
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/%E6%A9%99%E8%95%89%E9%87%91%E6%88%BF.jpg';
//     break;

//   default:
//     shareImageOfApp = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/upload/images/1574145199853-97feda7895c65be33aa234a7b81b37f.jpg';
//     break;
// }

@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: '',
    imgDocument: '',
    // adImage: advImageOfApp,
    bannerList: [],
    helpGroupList: [],
    activityList: [],
    recordId: null,
    visBanner: false,
    visPropagandaBanner: false,
    indicatorDots: false,
    vertical: true,
    achieve: false,
    propagandaBanner: [],
    newsShow: false,
  }

  componentWillMount() {
    ready.queue(() => {

      Taro.hideTabBar()
      this.getLocation()
      this.getIndexShareInfo()

      Taro.setNavigationBarTitle({ title: this.props.userInfo.miniApp.name })

      savePoint({
        event: 'index',
        eventType: 'main',
        propertyName: '进入首页',
        data: '{}'
      }).then(res => {
        this.setState({
          recordId: res.recordId
        })
        console.log('进入首页')
      })
    })
  }
  getIndexShareInfo() {
    getIndexShare().then(res => {
      this.setState({
        shareImg: (res || {}).imgUrl,
        imgDocument: (res || {}).imgDocument,
      })
      console.log(res, '首页分享信息')
    })
  }

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

    this.getIndexShareInfo()
    if (this.props.curCity.id) {
      ready.queue(() => {
        // Taro.hideTabBar()
        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
    })[0]
    // console.log('-----defaultCity-->', defaultCity)

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

      const payload = { location: `${location.longitude},${location.latitude}` }

      getLocationCity(payload).then(res => {

        let curCity = cityList.filter(item => {
          return item.name == res.name || ''
        })
        // console.log('-----curCity-->', curCity)
        this.updateCity(curCity[0] || defaultCity)
      }).catch(err => {
        Taro.showToast({
          title: `定位错误: ${err.message}`,
          icon: 'none',
        })
        console.error(err)
        this.updateCity(defaultCity)
      })
    }).catch(err => {
      if (err.errMsg === 'getLocation:fail auth deny') {
        Taro.showModal({
          content: '请同意授权您的定位功能',
          showCancel: false,
        })
      } else {
        Taro.showToast({
          title: `定位失败: ${err.errMsg}`,
          icon: 'none',
        })
      }
      console.error(err)
      this.updateCity(defaultCity)
    })
  }
  updateCity(payload) {
    this.props.dispatchCitySelected(payload).then(res => {
      this.loadData()
    })
  }

  loadData() {
    this.loadBannerList()
    this.loadHelpGroupList()
    this.loadOpenScreenBanner()
    // this.loadActivityList()
    this.loadList()

  }
  loadOpenScreenBanner() {
    const { curCity } = this.props

    const payload = {}
    if (curCity.id) {
      payload.cityId = curCity.id
    }

    // 获取开屏广告图
    this.props.dispatchProjectScreen(payload).then(res => {
      const banner = res[0]

      const maskVisible = banner && this.props.screenShow !== (banner || {}).contentId
      if (maskVisible) {
        Taro.hideTabBar()
      } else {
        Taro.showTabBar()
      }

      this.setState({
        maskVisible,
        maskBanner: banner || {}
      }, () => {
        if (Taro.getStorageSync('firstLoading') != '8') {
          const { dispatch } = getStore()
          dispatch({ type: SET_SCREEN_SHOWED, payload: (banner || {}).contentId })

        } else {
          Taro.setStorageSync('firstLoading', '6')
        }
      })
    })
  }

  loadBannerList() {
    const { curCity } = this.props
    // 获取首页banner
    const payload = {
      showPosition: 'index'
    }
    if (curCity.id) {
      payload.cityId = curCity.id

      var propagandaParams = {
        cityId: curCity.id
      }

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


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

      })
      console.log(this.state.visPropagandaBanner, "visPropagandaBanner")
    })


  }

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


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

    const payload = {
      name: keywords,
      pageSize: 999
    }
    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: this.state.imgDocument || `${this.props.userInfo.miniApp.name || '橙蕉'} 精准获客平台`,//分享内容
      path: `/pages/project/index?from=share&recommender=${personId}`,//分享地址
      imageUrl: this.state.shareImg || 'https://estateagents.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;

      // 其他
      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: `/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: `/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 => (
                  <FormIdCollector key={item.buildingId}>
                    <ProjectItem
                      onClick={this.onViewDetail.bind(this, item)}
                      data={item}
                    />
                  </FormIdCollector>
                ))}
              </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 { curCity } = this.props
    const { achieve, helpGroupList, propagandaBanner, newsShow } = this.state
    const { userInfo: { person: { personType, phone } } } = this.props
    const { 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>
              {/* 菜单栏 */}
              <View className="mune-box" style={personType == ROLE_CODE['CONSULTANT'] ? "padding:0 8%" : ""}>
                <View className="mune-item" onClick={this.toShopMallPage}>
                  <Image src={require('@assets/index/mall-icon.png')} className='icon'></Image>
                  <View className="mune-text">
                    积分商城
                  </View>
                </View>
                <View className="mune-item" onClick={this.toPolicyPage}>
                  <Image src={require('@assets/index/encyclopedia-icon.png')} className='icon'></Image>
                  <View className="mune-text">
                    购房百科
                  </View>
                </View>
                {
                  (personType !== ROLE_CODE['CONSULTANT']) &&
                  <View className="mune-item" onClick={this.toRecomonedPage}>
                    <Image src={require('@assets/index/recommend-icon.png')} className='icon'></Image>
                    <View className="mune-text">
                      推荐客户
                  </View>
                  </View>
                }
                <View className="mune-item" onClick={this.toMapHouse}>
                  <Image src={require('@assets/index/map-icon.png')} className='icon'></Image>
                  <View className="mune-text">
                    地图找房
                  </View>
                </View>
              </View>
              <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>
    )
  }
}
