import Taro, { Component } from '@tarojs/taro';
import './index.scss'

import { ROLE_CODE } from '@constants/user'
import { queryUserInfo, doUserSignin } from '@services/user'
import { connect } from '@tarojs/redux'
import Notice from '@components/Notice'
import { getCodeMessage, putRegisterConsultant } from '@services/getCode'
import * as actions from '@actions/user'
import Authorize from '@components/authorize'

import { menus } from './menus'

@connect(({ user, city }) => ({ user, city }), { ...actions })
export default class Person extends Component {
  config = {
    navigationBarTitleText: '我的'
  }

  state = {
    isLogin: false,
    user: {},
    isAgent: false,//经纪人
    consultant: false,//置业顾问
    tourist: false,//普通用户,
    menus: [],
    roleName: '普通用户',
  }

  componentDidShow () {
    Taro.showLoading()
    this.loadUserInfo()
    Taro.hideLoading()
  }

  loadUserInfo () {
    queryUserInfo().then(user => {
      const [roleSetting, roleName] = this.getRoleName(user.personType)

      this.setState({
        user,
        phone: user.phone,
        menus: menus.map(group => group.filter(x => x.userTypes.indexOf(user.personType) > -1)),
        roleName,
        ...roleSetting,
      })
    })
  }

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

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

      this.loadUserInfo()

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

  toHomePage () {
    Taro.switchTab({
      url: '/pages/project/index'
    })
  }

  toShopPage () {
    Taro.switchTab({
      url: '/pages/shop/index'
    })
  }

  redirectTo = (url) => {
    if (url) {
      if (typeof url === 'function') {
        Taro.navigateTo({ url: url(this.state.user) })
      } else {
        Taro.navigateTo({ url })
      }
    }
    else {


      putRegisterConsultant().then(res => {
        // console.log("匹配成功，请退出小程序重新登录即可")
        Taro.showToast({
          title: "匹配成功，请退出小程序重新登录即可"
        })
      }).catch(err => {
        console.error(err)
        Taro.showToast({
          title: "匹配失败，请联系相关管理人员",
          icon: "none"
        })
      })
    }

  }

  getRoleName (type) {
    switch (type) {
      case ROLE_CODE['CONSULTANT']:
        return [{ consultant: true }, '置业顾问']
      case ROLE_CODE['ESTATE_AGENT']:
        return [{ isAgent: true }, '普通用户']
      case ROLE_CODE['CHANNEL_AGENT']:
        return [{ isAgent: true }, '专业经纪人']
      default:
        return [{ tourist: true }, '普通用户']
    }
  }

  goShop () {
    Taro.switchTab({
      url: `/pages/shop/index`
    })
  }
  handleMore () {
    Taro.showModal({
      title: '温馨提示',
      content: '敬请期待'
    })
  }

  goPersonDetail () {

    const { user: { personType } } = this.state

    // if (personType == ROLE_CODE['CHANNEL_AGENT'] || personType == ROLE_CODE['ESTATE_AGENT']) {
    Taro.navigateTo({
      url: '/pages/person/personDetail/index'
    })
    // }

  }

  renderLogin () {
    return <Authorize></Authorize>
  }

  renderDetail () {
    const { user, menus, roleName } = this.state
    // const showQRCode = user.personType === ROLE_CODE['CONSULTANT'] || ROLE_CODE['ESTATE_AGENT'] || ROLE_CODE['CHANNEL_AGENT']
    // const isConsultant = user.personType == ROLE_CODE['CONSULTANT']
    // const isConsultant = user.personType
    return (
      <View className="person">
        <Notice></Notice>
        <View className="info">
          <Image className="bg" src={require('@assets/mine/background.png')} mode='aspectFill'></Image>
          <View className="content">
            <View className="info-block">
              <View className="avatar" onClick={this.goPersonDetail}>
                <Image className="info__headimg" src={user.avatar} />
                <View className="info-intro">{roleName}</View>
              </View>

              <View className="info-text" onClick={this.goPersonDetail}>
                <View className="info-text__name">{user.name ? user.name : user.nickname}</View>
                <View className="info-text__intro">积分 {user.points || 0}</View>
              </View>
              {/* {
                user.personType != 'customer' && (
                  <Navigator url={`/pages/person/spread/index`} className="tuiguang">
                    <Image style="width:40px;height:36px" src={require('@assets/mine/tuiguangma.png')} ></Image>
                    <View className="info-text__intro" style="margin:4px 0 0 4px">推广码</View>
                  </Navigator>
                )
              } */}
            </View>
            {/* <View
              className={`sign__btn ${user.havaSigned && 'signed'}`}
              onClick={this.doSign}>{user.havaSigned ? '已打卡' : '打卡'}
            </View> */}

          </View>
          <View className='qiandao-con'>
            <Text className='qiandao-text'>签到得积分，积分兑好礼，马上去签到吧！</Text>
            <View className={user.havaSigned ? 'reday-qiandao-btn' : 'qiandao-btn'} onClick={this.doSign}>{user.havaSigned ? '已签到' : '签到'}</View>

            {/* <Text className='integral-cont_btn' onClick={this.goShop}>去兑换</Text> */}

          </View>
        </View>
        <View>
          {
            menus.map((group, ginx) => {

              return (
                <Block key={`grp-${ginx}`}>
                  {
                    group.map((menu, inx) => {
                      return (
                        <View onClick={() => this.redirectTo(menu.url)} style={{ color: menu.style }} className="menu-item-con" key={`menu-${inx}`}>
                          <Image className="left-icon" src={menu.icon} ></Image>
                          <View className="menu-maintext">
                            <Text className="menu-name" style={ menu.style }>{menu.name}</Text>
                            <Text className="right-icon"></Text>
                          </View>
                        </View>
                      )
                    })
                  }
                  <View className='line'></View>
                </Block>
              )
            })
          }
        </View>
      </View>
    );
  }

  render () {
    const { phone, tel } = this.state.user
    return (
      <View className='wrap'>
        {(phone || tel) && this.renderDetail()}
        {!phone && !tel && this.renderLogin()}
      </View>
    )
  }
}
