import Taro, { Component } from '@tarojs/taro';
import { getWindowHeight } from '@utils/style'
import { AtTabs, AtTabsPane } from 'taro-ui'
import "taro-ui/dist/style/components/tabs.scss"
import './index.scss'

// import Search from '@components/search'
import Banner from './banner'
import ready from '@utils/ready'
import { ROLE_CODE } from '@constants/user'
import { queryBanners } from '@services/common'
import { getGoodsBuilding, getGoodsList } from '@services/item'
import { connect } from '@tarojs/redux'
import * as actions from '@actions/shop'
import { queryUserInfo, doUserSignin } from '@services/user'

// import getUserPhone from '@utils/getUserPhone'
import Authorize from '@components/authorize'

@connect(({ user, shop, city }) => ({ ...user, ...shop, ...city }), { ...actions })
export default class Shop extends Component {
  config = {
    navigationBarTitleText: '积分商城'
  }

  state = {
    keywords: '',
    bannerList: [
      'https://estateagents.oss-cn-shanghai.aliyuncs.com/images/banner/1.jpg',
      'https://estateagents.oss-cn-shanghai.aliyuncs.com/images/banner/2.jpg',
      'https://estateagents.oss-cn-shanghai.aliyuncs.com/images/banner/3.jpg',
      'https://estateagents.oss-cn-shanghai.aliyuncs.com/images/banner/4.jpg',
      'https://estateagents.oss-cn-shanghai.aliyuncs.com/images/banner/5.jpg'
    ],
    cityName: '',
    goodsBuilding: [],
    goodsList: [],
    user: {},
  }

  componentDidShow() {

    Taro.showLoading()
    ready.queue(() => {
      this.loadBannerList()
      this.loadGoodsBuilding()

      //    this.loadCity()
      this.loadUserInfo()
    })
    Taro.hideLoading()
  }

  loadBannerList() {
    const payload = {
      showPosition: 'mall',
      cityId: this.props.curCity.id
    }
    queryBanners('banner', payload).then(res => {
      this.setState({
        bannerList: res || []
      })
    })
  }

  loadList() {


    Taro.showLoading()
    let current = this.state.current
    const params = {
      pageNum: '1',
      pageSize: '9999',
      buildingId: this.state.goodsBuilding[current].buildingId || this.state.goodsBuilding[0].buildingId,
      cityId: this.props.curCity.id
    }

    getGoodsList(params).then(res => {
      this.setState({
        goodsList: res.records || []
      })
      Taro.hideLoading()
    }).catch(err => {
      console.error(err)
      Taro.hideLoading()
    })
  }

  loadGoodsBuilding() {
    const payload = {

      cityId: this.props.curCity.id
    }

    console.log(payload, "999999999999")
    getGoodsBuilding(payload).then(res => {
      res.map(item => {
        item.title = item.buildingName
      })

      this.setState({
        goodsBuilding: res || []
      }, () => {
        if (res && res.length) {
          this.loadList()
        } else {
          this.setState({
            goodsList: []
          })
        }
      }
      )
    })
  }

  handleClick(value) {

    this.setState({
      current: value
    })

    const payload = {
      pageNum: '1',
      pageSize: '9999',
      buildingId: this.state.goodsBuilding[value].buildingId,
      cityId: this.props.curCity.id
    }
    getGoodsList(payload).then(res => {
      this.setState({
        goodsList: res.records || []
      })
      console.log(this.state.goodsList, "goodsList")
    })

  }

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

  goPointRecords() {
    const { person: { points } } = this.props.userInfo
    Taro.navigateTo({
      url: `/pages/shop/integralDetail/index?points=` + points
    })
  }

  goPointRule() {
    Taro.navigateTo({
      url: `/pages/shop/rule/index`
    })
  }

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

  doSign() {
    const { user: { id, havaSigned } } = this.state
    if (havaSigned) {
      return
    }

    doUserSignin({ id }).then(res => {
      Taro.showToast({
        title: '签到成功'
      })
      this.setState({

        points: res.points

      })

      this.loadUserInfo()

      // App.zhuge.track('签到成功')
    })
  }

  loadUserInfo() {
    // debugger
    queryUserInfo().then(user => {
      console.log(user, "user")
      // debugger
      this.setState({
        user,
        points: user.points

      })
    })
  }

  renderLogin() {
    return <Authorize></Authorize>
  }
  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;
    }
  }
  state = {
    current: 0,
  }



  renderGoods() {
    const { goods: { records = [] } } = this.props
    const { goodsList, goodsBuilding, current } = this.state

    return (
      <View>
        {
          goodsBuilding && goodsBuilding.length < 2 &&
          <View className="list__wrap">
            <View className="hot_title">热门商品</View>
            {
              goodsList.length &&
              goodsList.map(item => (
                
                <View className="item" key={item.goodsId} onClick={this.onViewDetail.bind(this, item)}>
                  {console.log(item,'--item---')}
                  <Image className="item__img" mode="aspectFill" src={item.imgUrl} />
                  <View className="item__title">{item.goodsName}</View>
                  <View className="item__des">
                    <View>
                      剩余数量{item.inventory}
                    </View>
                    <View >
                      <Text className="item__jifen">{item.pointPrice}</Text>积分
                </View>
                  </View>
                </View>
              ))
            }
            {
              goodsList.length < 1 &&
              <View style="font-size:14px;color:#888;margin:40px auto;text-align: center;">
                暂无商品~
              </View>
            }
          </View>
        }
        {
          goodsBuilding && goodsBuilding.length >= 2 &&
          <View className="list__wrap">
            <AtTabs scroll tabDirection='horizontal' current={current} tabList={goodsBuilding} onClick={this.handleClick.bind(this)}>

              {goodsBuilding.map((l_item, index) => (
                <AtTabsPane current={current} key={`pane-${index}`} index={index} >
                  <View>
                    {goodsList.length &&
                      goodsList.map(item => (
                        <View className="item" key={item.goodsId} onClick={this.onViewDetail.bind(this, item)}>
                          <Image className="item__img" mode="aspectFill" src={item.imgUrl} />
                          <View className="item__title">{item.goodsName}</View>
                          <View className="item__des">
                            <View>
                              剩余数量{item.inventory}
                            </View>
                            <View >
                              <Text className="item__jifen">{item.pointPrice}</Text>积分
                </View>
                          </View>

                        </View>
                      ))
                    }
                    {
                      goodsList.length < 1 &&
                      <View style="font-size:14px;color:#888;margin:40px auto;text-align: center;">
                        暂无商品~
                      </View>
                    }
                  </View>
                </AtTabsPane>
              ))
              }
            </AtTabs>
          </View>
        }
      </View>


    )
  }

  renderDetail() {
    const { user, points } = this.state
    const { userInfo: { person }, curCity } = this.props
    const { bannerList = [] } = this.state
    return (
      <View className="page">
        {/* <Search placeholder="请输入要搜索的商品名称" onSearch={this.onSearch} /> */}
        <ScrollView
          scrollY
          scroll-with-animation
          enable-back-to-top
          className="list"
          style={{
            height: getWindowHeight()
          }}>
          <View className="user_box">
            <View className="user_con">
              <Image className="bg" src={require('@assets/shop/background.jpg')} ></Image>
              <Image className="user__left__headimg" src={person.avatarurl} />
              <View className='user__left__name'>{person.nickname}</View>
              {
                user.havaSigned ?
                  (<View className="qiandao__btn">已签到</View>) :
                  (<View className="qiandao__btn" onClick={this.doSign}>签到</View>)
              }
              <View className='message'>
                <View className='message__left'>
                  <View className='user__jifen'>
                    积分<Text className='user__jifen__right'>{points || 0}</Text>
                  </View>
                  <View className='message__left__btn' onClick={this.goPointRule.bind(this)}>
                    <Image className="message__left__img" src={require('@assets/shop/rule.png')} />
                    <View className='message__left__word'>积分规则</View>
                  </View>
                  <View className='message__left__btn' onClick={this.goPointRecords.bind(this)}>
                    <Image className="message__left__img" src={require('@assets/shop/liebiao.png')} />
                    <View className='message__left__word'>积分明细</View>
                  </View>

                </View>
                {/* <View className='message__right' onClick={this.handleLocationClick.bind(this)}>
                <Image className="message__right__img" src={require('@assets/shop/address.png')} />
                <View className='message__right__word'>{curCity.name}</View>
              </View> */}
              </View>
            </View>
          </View>


          {bannerList.length > 0 &&
            <Banner list={bannerList} onClick={this.handleBannerClick} indicatorDots={false}></Banner>
          }


          {this.renderGoods()}
        </ScrollView>
      </View >
    );
  }

  render() {
    const { person: { phone, tel } } = this.props.userInfo

    return (
      <View className='wrap'>
        {!phone && !tel ? this.renderLogin() : this.renderDetail()}
      </View>
    )
  }
}
