import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Button, Swiper, Block } from '@tarojs/components'
import HouseGrid from '../../components/HouseGrid'
import NamedIcon from '../../components/NamedIcon'
import ScrollMessage from '../../components/ScrollMessage'
import Blank from '../../components/Blank'
import ActSheet from '../../components/ActSheet'
import ShareButtons from '../../components/ShareButtons'
import GrantProfile from '../../components/GrantProfile'
// import Poster from './poster'
import Poster from '@/components/Poster'
import { connect } from '@tarojs/redux'
import ready from '@/utils/ready'
import { queryHouseList, queryNoticeInfo, queryApartmentType, querySalesInfo } from '@/services/project'
import { getQrCodeParams } from '@/utils/qrcode'
import { withDetail } from '@/utils/page'
import { share as shareSavePoint } from '@/utils/shareSavePoint'
import { ROLE_CODE } from '@/constants/user'
import { report as reportCustomer } from '@/utils/customer'
import { getMiniQrcode, savePoint, updatePoint } from '@/services/common'
import { getCanvasConfig, transferImage } from '@/utils/tools'
import { getCardDetail } from '@/services/card'
import Consultant from '@/components/consultant'
import './index.scss'
import { Loading } from '@/components/Loading'
import * as houseActions from '@/actions/house'

@connect(s => s.user, { ...houseActions })
@withDetail({
  track: {
    event: 'house_list',
    eventType: 'house',
    propertyName: '查看房源列表',
    data: '{}',
  }
})
export default class HouseList extends Component {
  config = {
    navigationBarTitleText: '房源',
  }
  state = {
    showShareMenu: false,
    showPoster: false,
    tipsList: [],
    houseList: [{}],
    id: null,
    qrcodeParams: {},
    current: 0,
    priceCurrent: -1,
    apartmentList: [],
    conditionVisible: false,
    startPrice: '',
    endPrice: '',
    apartmentId: '',
    reportedCustomer: false,
    posterShow: false,
    posterData: {},
    buildingId: null,
    salesBatchDetail: {},
    posterConfig: [],
    consultData: {}, // 分享的置业顾问信息
    consultShow: false,  // 置业顾问悬浮框显示隐藏
    noRecord: false,
    loading: true,
    dataType: 1,
  }


  componentDidShow() {
    ready.queue(() => {
      this.setState({ showShareMenu: false })
      this.initPageData()
    })

    // 清空认筹选择
    this.props.dispatchFlush2Cart([])
  }


  componentWillReceiveProps() {
    this.reportClientFn()
  }

  transTPLs2Configs(tpls, params) {
    return tpls.map((tpl) => {
      const conf = getCanvasConfig(tpl.configs, params)
      return { ...conf }
    })
  }

  // 报备客户
  reportClientFn() {

    const { qrcodeParams } = this.state
    const consultant = this.$router.params.consultant || qrcodeParams.consultant || ""
    const { userInfo: { person } } = this.props

    if (!this.state.reportedCustomer) {
      reportCustomer(person, consultant).then(() => {
        this.setState({ reportedCustomer: true })
      })
    }
  }
  initPageData() {

    Taro.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    const id = this.$router.params.id

    if (this.$router.params.scene) {
      getQrCodeParams(this.$router.params.scene).then((res) => {
        this.setState({ id: res.id, qrcodeParams: res }, () => {
          this.getInfo(res.id)
          this.anotherInfo(res.id)
        })
      })
    } else {
      this.getInfo(id)
      this.anotherInfo(id)
    }
    this._$_dataReady()
  }

  getInfo(id) {
    const { startPrice, endPrice, apartmentId } = this.state
    const params = {
      salesBatchId: id,
      startPrice,
      endPrice,
      apartmentId,
      pageNum: 1,
      pageSize: 9999,
    }
    queryHouseList(params).then(res => {
      this.setState({
        houseList: this.groupHouseList(res) || [],
        loading: false,
      }, () => {
        Taro.hideToast()
      })


    }).catch(err => {
      Taro.hideToast()
      Taro.showToast({ title: '未找到房源批次', icon: 'none', duration: 2000 })
    })
  }
  anotherInfo(id) {
    queryNoticeInfo(id).then(res => {
      this.setState({
        tipsList: res || {}
      })
    })
    this.reportClientFn()
    let { qrcodeParams } = this.state
    const consultant = this.$router.params.consultant || qrcodeParams.consultant

    if (consultant) {
      getCardDetail(consultant).then(res => {
        this.setState({
          consultData: res,
          consultShow: true
        })
      })
    }
    querySalesInfo(id).then(res => {

      this.setState({
        buildingId: res.buildingId,
        salesBatchDetail: res || {},
        noRecord: res.status == '1' ? false : true
      })
      const { templates = [], posterImg = '' } = (res.posters || [])[0] || {}

      this.setState({
        posterData: { poster: posterImg },
      }, () => {
        this.getPosterData().then(posterData => {
          const posterConfig = this.transTPLs2Configs(templates, posterData)
          this.setState({ posterConfig, posterData })
        })
      })
    })
    queryApartmentType({ salesBatchId: id }).then(res => {
      this.setState({
        apartmentList: res || []
      })
    })
  }
  groupHouseList(houseList = []) {
    // 先按照楼层分组
    const floorList = houseList.reduce((list, room) => {
      let found = false

      list.forEach((floor) => {
        if (floor.floorId === room.floorId) {
          found = true
          floor.roomList.push(room)
        }
      })

      if (!found) {
        list.push({ ...room, roomList: [room] })
      }

      return list
    }, [])

    // 再按照单元分组
    const unitList = floorList.reduce((list, floor) => {
      let found = false
      list.forEach((unit) => {
        if (unit.unitId === floor.unitId) {
          found = true
          unit.floorList.push(floor)
        }
      })

      if (!found) {
        list.push({ ...floor, floorList: [floor] })
      }

      return list
    }, [])

    // 最后按照楼栋分组
    return unitList.reduce((list, unit) => {
      let found = false
      list.forEach((block) => {
        if (block.blockId === unit.blockId) {
          found = true
          block.unitList.push(unit)
        }
      })

      if (!found) {
        list.push({ ...unit, unitList: [unit] })
      }

      return list
    }, [])
  }

  goto = url => Taro.navigateTo({ url })

  handleExplainClick = e => {
    const buildingId = this.$router.params.buildingId || this.state.buildingId
    this.goto(`/onlineSelling/pages/help/index?buildingId=${buildingId}`)
  }

  handleSearchClick = e => {
    // Taro.setNavigationBarTitle({ title: '房源筛选' })
    this.setState({
      conditionVisible: true
    })
    // const id = this.$router.params.id || this.state.id
    // this.goto(`/onlineSelling/pages/screenHouse/index?id=${id}`)
  }

  handleShareBtn = e => {
    this.setState({ showShareMenu: true })
  }

  handleRecordBtn = e => {
    const { salesBatchDetail } = this.state
    this.goto(`/onlineSelling/pages/records/index?id=${salesBatchDetail.salesBatchId}`)
  }

  currentPageAndParams() {
    const id = this.$router.params.id || this.state.id
    const {
      userInfo: { person: { personId, personType, userId } }
    } = this.props

    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""

    const queryParams = [
      `id=${id}`,
      'from=house_share',
      `recommender=${personId}`,
      `consultant=${consultant}`,
      `consultantId=${consultantId}`,
    ]

    return [
      'onlineSelling/pages/houseList/index',
      queryParams.join('&'),
    ]
  }
  // handleShareFrineds = e => {
  onShareAppMessage = () => {
    this.setState({ showShareMenu: false })
    const id = this.$router.params.id || this.state.id
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""
    const { salesBatchDetail: { shareContents } } = this.state
    const shareData = shareContents && shareContents.length ? shareContents[0] : { shareContentTitle: '房源列表', shareContentImg: null };
    // 分享埋点
    shareSavePoint({
      event: 'share',
      eventType: 'house',
      propertyName: '房源列表分享',
      consultantId: consultantId,
      sharePersonId: personId,
      targetId: id,
      data: '{}'
    }, 'houseApp')

    const [page, params] = this.currentPageAndParams()

    console.log(`/${page}?${params}`, "`/${page}?${params}`")
    return {
      title: shareData.shareContentTitle,//分享标题
      path: `/${page}?${params}`,//分享地址
      imageUrl: shareData.shareContentImg
    }
  }

  // 开始生成海报
  togglePosterStatus = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          showPoster: !!flag,
          posterData,
          showShareMenu: false
        })
        const id = this.$router.params.id || this.state.id
        shareSavePoint({
          event: 'poster',
          eventType: 'house',
          propertyName: '生成房源列表海报',
          targetId: id,
          data: '{}'
        }, 'housePoster')
      })


    } else {
      this.setState({
        showPoster: !!flag,
        showShareMenu: false
      })
    }


  }
  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }

      const [page, scene] = this.currentPageAndParams()
      const payload = { page, scene, showToast: false }

      getMiniQrcode(payload).then(qrcode => {
        const { posterData = {} } = this.state
        let data = {
          qrcode,//小程序二维码
          ...posterData,
        }
        resolve(data)
      })
    })
  }



  handleRoomClick = room => {
    this.goto(`/onlineSelling/pages/detail/index?id=${room.houseId}`)
  }

  renderBar() {
    const { tipsList } = this.state

    return (
      <View className="topbar">
        <View className="body">
          <ScrollMessage summary={tipsList} />
        </View>
        <View className="action">
          <View onClick={this.handleExplainClick}>
            <Image style="width:50rpx;height:50rpx" src={transferImage(require('../../assets/explain.png'))}></Image>
          </View>
          <View onClick={this.handleSearchClick}>
            <Image style="width:50rpx;height:50rpx" src={transferImage(require('../../assets/screen.png'))}></Image>
          </View>
        </View>
      </View>
    )
  }

  renderHouses() {
    const { houseList, dataType } = this.state

    return (
      <ScrollView className="container" scrollY scrollWithAnimation>
        {
          houseList.map((item) => {
            return <HouseGrid key={item.unitId} showDataType={dataType} dataset={item} onRoomClick={this.handleRoomClick} />
          })
        }
      </ScrollView>
    )
  }

  renderBlank() {
    return (
      <View className="container"><Blank tips="暂无可选房源" /></View>
    )
  }

  renderBottom() {
    return (
      <View className="bottombar">
        <Button className="btn record" onClick={this.handleRecordBtn}>
          <Image style="width:42rpx;height:42rpx" src={transferImage(require('../../assets/record.png'))}></Image>
          <Text className="txt">选房记录</Text>
        </Button>
        <Button className="btn share" onClick={this.handleShareBtn}>
          <Image style="width:42rpx;height:42rpx" src={transferImage(require('../../assets/share.png'))}></Image>
          <Text className="txt">分享</Text>
        </Button>
      </View>
    )
  }

  handleCondition(value) {
    const { salesBatchDetail: { displayHousePrice } } = this.state
    if ((!displayHousePrice && value == 1) || value == 2) {
      this.setState({
        apartmentId: '',
        startPrice: '',
        endPrice: '',
        conditionVisible: false,
      }, () => {
        const id = this.$router.params.id || this.state.id
        this.getInfo(id)
      })
    }
    this.setState({
      current: value,
    })
  }
  handlePriceItem(item) {
    this.setState({
      priceCurrent: item.value,
      startPrice: item.startPrice,
      endPrice: item.endPrice,
      apartmentId: '',
      conditionVisible: false
    }, () => {
      const id = this.$router.params.id || this.state.id
      this.getInfo(id)
    })
  }
  handleInput(e) {
    this.setState({ startPrice: e.detail.value })
  }
  handleInput2(e) {
    this.setState({ endPrice: e.detail.value })
  }
  sureFilter() {
    this.setState({
      conditionVisible: false,
      apartmentId: ''
    }, () => {
      // Taro.setNavigationBarTitle({ title: '房源' })
      const id = this.$router.params.id || this.state.id
      this.getInfo(id)
    })
  }
  renderPrice() {
    const { priceCurrent, startPrice, endPrice } = this.state
    const priceList = [
      { startPrice: null, endPrice: '100', value: 0 },
      { startPrice: '100', endPrice: '150', value: 1 },
      { startPrice: '150', endPrice: '200', value: 2 },
      { startPrice: '200', endPrice: '250', value: 3 },
      { startPrice: '250', endPrice: '300', value: 4 },
      { startPrice: '300', endPrice: '400', value: 5 },
      { startPrice: '400', endPrice: '500', value: 6 },
      { startPrice: '500', endPrice: '600', value: 7 },
      { startPrice: '600', endPrice: null, value: 8 },
    ]
    return (
      <View>
        <View className="price-con">
          {priceList.map(priceItem => (
            <View key={priceItem.value} className={priceCurrent == priceItem.value ? 'active-item' : 'price-item'} onClick={() => { this.handlePriceItem(priceItem) }}>
              {!priceItem.startPrice && <View className="item-con">{priceItem.endPrice}万以下</View>}
              {priceItem.startPrice && priceItem.endPrice && <View className="item-con">{priceItem.startPrice}万-{priceItem.endPrice}万</View>}
              {!priceItem.endPrice && <View className="item-con">{priceItem.startPrice}万以上</View>}
            </View>
          ))}
        </View>
        <View style="color:#666;font-size:28rpx;margin-left:40rpx">
          填写价格（万元）
        </View>
        <View className="search">
          <Input
            type="number"
            placeholder="最低价"
            class="search-input"
            placeholder-style="color:#dcdcdc;font-size:28rpx"
            maxlength="6"
            value={startPrice}
            onInput={this.handleInput}
          />
          <Text style="margin:0 8rpx;color:#999;font-size:28rpx">-</Text>
          <Input
            type="number"
            placeholder="最高价"
            class="search-input"
            placeholder-style="color:#dcdcdc;font-size:28rpx"
            maxlength="6"
            value={endPrice}
            onInput={this.handleInput2}
          />
          <View className="sure-btn" onClick={() => this.sureFilter()}>
            确定
              </View>
        </View>
      </View>
    )
  }
  apartmentFilter(apartmentId) {
    this.setState({
      apartmentId,
      startPrice: '',
      endPrice: '',
      conditionVisible: false,
    }, () => {
      // Taro.setNavigationBarTitle({ title: '房源' })
      const id = this.$router.params.id || this.state.id
      this.getInfo(id)
    })
  }
  renderApartment() {
    const { apartmentList } = this.state
    return (
      <Block>
        {apartmentList.length ? <View style="padding:40rpx 20rpx">
          {apartmentList.map((apartmentItem, index) => (
            <View className='item' key={index + 'apartment'} onClick={() => this.apartmentFilter(apartmentItem.apartmentId)}>
              <View className='house__img-info'>
                <Image className='house__img' src={transferImage(apartmentItem.buildingImgList[0].url)} mode="widthFix"></Image>
              </View>
              <View className="rest-info">
                <View className='house-type__name'>{apartmentItem.apartmentName || ''}</View>
                <View className='construction__area'>
                  <Text>{apartmentItem.buildingArea ? '建筑面积约' + apartmentItem.buildingArea + 'm²' : '建筑面积待定'}</Text>
                  {
                    apartmentItem.insideArea ? <Text>使用面积约{apartmentItem.insideArea}m²</Text> : <Text>使用面积待定</Text>
                  }
                </View>
              </View>
            </View>
          ))}
        </View>
          : <Blank tips="暂无户型"></Blank>
        }
      </Block>
    )
  }

  renderCondition() {
    const { current, salesBatchDetail: { displayHousePrice } } = this.state
    const condition = [{ title: '按户型', value: 0 }, { title: '按价格', value: 1 }, { title: '不限条件', value: 2 }]
    const condition2 = [{ title: '按户型', value: 0 }, { title: '不限条件', value: 2 }]
    const conditionList = displayHousePrice ? condition : condition2
    return (
      <View className="screen-page">
        <View className="screen-top">
          筛选房源
            {conditionList.map(item => (
            <View key={item.value} onClick={() => this.handleCondition(item.value)} className={current == item.value ? 'top-item active' : 'top-item'}>
              {item.title}
            </View>
          ))}
        </View>
        {current == 0 && this.renderApartment()}
        {current == 1 && displayHousePrice && this.renderPrice()}


      </View>

    );
  }
  toBuildingDetail() {
    const buildingId = this.$router.params.buildingId || this.state.buildingId
    this.goto(`/pages/project/detail/index?id=${buildingId}`)
  }
  handleScreen(value) {
    this.setState({ dataType: value })
  }

  render() {
    const {
      consultData,
      consultShow,
      showShareMenu,
      showPoster,
      houseList,
      conditionVisible,
      posterData,
      posterConfig,
      noRecord,
      loading,
      salesBatchDetail,
      dataType
    } = this.state

    if (loading) {
      return <View style="margin: 80px auto;"><Loading color="#BB9C79" size={100} /></View>
    }

    const { userInfo: { person } } = this.props

    const showCircleBtn = posterData && posterData.qrcode
    console.log('==============>', posterData, showPoster, posterConfig)

    const screenList = [{ title: '预选热度图', value: 1 }, { title: '认筹热度图', value: 2 }]
    return (
      <Block>
        {conditionVisible && this.renderCondition()}
        {/* 授权电话与头像 */}
        <GrantProfile both person={person} />
        {/* 置业顾问悬框 */}
        {
          consultShow && <Consultant style="bottom:150rpx" smallStyle="bottom:178rpx" personId={person.personId} name={person.name || person.nickname} data={consultData}></Consultant>
        }
        {/* 生成海报 */}
        {showPoster && <Poster data={posterData} configs={posterConfig} onCancel={this.togglePosterStatus} onFinish={this.togglePosterStatus} ></Poster>}
        {!noRecord ?
          <Block>
            {!conditionVisible && <Block>
              <View className="houselist">
                {this.renderBar()}
                <View className="building-top">
                  <View style="color:#333;font-size:28rpx">{salesBatchDetail.buildingName || ''}</View>
                  <View style="color:#666;font-size:24rpx;" onClick={() => this.toBuildingDetail()}>查看楼盘详情<Text className="right-icon"></Text></View>
                </View>

                <View className="screen-flex" >
                  {screenList.map(item => (
                    <View key={item.value} onClick={() => this.handleScreen(item.value)} className={dataType == item.value ? 'top-item active' : 'top-item'}>
                      {item.title}
                    </View>
                  ))}
                </View>

                {houseList.length ? this.renderHouses() : this.renderBlank()}
                {this.renderBottom()}
              </View>
              {/* 分享按钮 */}
              <ActSheet show={showShareMenu}>
                <ShareButtons
                  circleBtn={showCircleBtn}
                  onShareFrineds={this.handleShareFrineds}
                  onSharingCircleOfFriends={() => this.togglePosterStatus(true)}
                />
              </ActSheet>
            </Block>
            }
          </Block>
          :
          <View style="text-align: center;margin-top: 30vh;font-size: 28rpx;color: #999;">当前销售批次已被取消发布，请在发布后再试。</View>
        }

      </Block>
    )
  }
}

