import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView } from '@tarojs/components'

import './index.scss'
import Blank from '../../components/Blank'
import HouseGrid from '../../components/HouseGrid'
import { queryHouseList } from '@/services/project'

import ready from '@/utils/ready'
import { connect } from '@tarojs/redux'
import * as houseActions from '@/actions/house'
import { fetch, apis } from '@/utils/request'

const getRaiseProfile = ({ salesBatchId, raiseRecordId, personId }) => {
  const queryString = [
    `${raiseRecordId ? 'raiseRecordId=' + raiseRecordId : ''}`,
    `${salesBatchId ? 'salesBatchId=' + salesBatchId : ''}`,
    `${personId ? 'personId=' + personId : ''}`,
  ].filter(Boolean).join('&')

  return fetch({ url: `${apis.API_RAISE_PROFILE}?${queryString}` })
}

@connect(
  ({ user, house }) => ({ ...user, house }),
  {...houseActions}
)
export default class extends Component {
  config = {
    navigationBarTitleText: '添加其他房源',
  }

  state = {
    loading: true,
    dataType: 1, // maybe need change  1 预选, 2 认筹
    houseList: [],
    chooseList: [], // 已经选择的房源列表
    collapsed: true,      // 已选列表默认关闭, true 关闭, false 开启
    multiSelect: true,  // 是否多选, 自动锁房是单选
  }

  componentWillMount () {
    ready.queue(() => {
      const { userInfo, house } = this.props
      const { id: salesBatchId, multi } = this.$router.params

      const params = {
        source: 'raiseChoose',
        salesBatchId,
        pageNum: 1,
        pageSize: 9999,
      }

      queryHouseList(params).then(res => {
        this.setState({
          houseList: this.groupHouseList(res) || [],
          loading: false,
        })
      })

      // 获取认筹信息
      // getRaiseProfile(salesBatchId, undefined, userInfo.person.personId)

      if (house.raiseCart && house.raiseCart.length) {
        this.setState({ chooseList: house.raiseCart })
      }

      this.setState({ multiSelect: multi !== 'false' })
    })
  }
  
  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
    }, [])
  }

  changeShowData = (dataType) => {
    // 此处需要按照 dataType 去切换数据
    // 切换成功之后
    this.setState({ dataType })
  }

  // 添加到选择列表
  // 注意, 不是确认选择
  add2Cart = (room) => {
    const locked = room.houseLockingStatus == 'locked'
    if (locked) {
      Taro.showToast({ title: '该房源已经被锁定', icon: 'none' })
      return;
    }

    const { chooseList, multiSelect } = this.state
    const checked = (chooseList || []).filter(x => x.houseId == room.houseId)[0]

    if (checked) {
      this.setState({ chooseList: chooseList.filter(x => x.houseId != room.houseId) })
    } else {
      if (multiSelect) {
        this.setState({ chooseList: chooseList.concat(room) })
      } else {
        this.setState({ chooseList: [room] })
      }
    }
  }

  // 确认选择
  handleSubmit = () => {
    if (!this.state.chooseList.length) {
      Taro.showModal({
        title: '提示',
        content: '您未选择房源, 确认离开?',
        success: (res) => {
          if (res.confirm) {
            this.props.dispatchFlush2Cart([])
            Taro.navigateBack({ delta: 1 })
          }
        }
      })
    } else {
      this.props.dispatchFlush2Cart(this.state.chooseList)
      Taro.navigateBack({ delta: 1 })
    }
  }

  // 取消选择
  subChooseList = (house) => {
    const name = [house.termName, house.blockName, house.unitName, house.floorName, house.roomName].join('')
    const { chooseList } = this.state

    Taro.showModal({
      title: '取消选择',
      content: `确认取消 ${name} ?`,
      success: (res) => {
        if (res.confirm) {
          this.setState({ chooseList: chooseList.filter(x => x.houseId != house.houseId) })
        }
      }
    })
  }

  // 是否展开已选列表
  trigCartPannel = () => {
    const { collapsed } = this.state;
    this.setState({ collapsed: !collapsed })
  }

  renderHead() {
    const { dataType, houseList } = this.state
    const hasData = houseList && houseList.length

    return (
      <View className="head">
        <View className="tips">仅显示符合认筹条件的房源。点击房源卡片查看房源详情，不要在房源详情页做操作。请在当前页面选择提交认筹。</View>
        {
          hasData && (
            <View className="actions">
              <View className={`action ${dataType === 1 ? 'active' : ''}`} onClick={() => this.changeShowData(1)}>预选热度图</View>
              <View className={`action ${dataType === 2 ? 'active' : ''}`} onClick={() => this.changeShowData(2)}>认筹热度图</View>
            </View>
          )
        }
      </View>
    );
  }

  renderHouses() {
    const { houseList, dataType, chooseList } = this.state
    const hasData = houseList && houseList.length

    return hasData && (
      <ScrollView className="body" scrollY>
      {
        houseList.map((item) => {
          return (
            <HouseGrid
              key={item.unitId}
              dataset={item}
              showAction
              showDataType={dataType}
              chooseList={chooseList}
              onRoomClick={this.handleRoomClick}
              onActionClick={this.add2Cart}
            />
          )
        })
      }
      </ScrollView>
    )
  }

  renderAction() {
    const { chooseList, collapsed, houseList } = this.state;
    const defChoose = chooseList[0] || {}
    const defName = [defChoose.termName, defChoose.blockName, defChoose.unitName, defChoose.floorName, defChoose.roomName].join('')
    const title = collapsed ? `已选择: ${defName} 等 ${chooseList.length} 个房源` : '已选列表'
    const opened = collapsed ? 'off' : 'on'
    const nodata = houseList && houseList.length ? '' : 'nodata'
    const btnText = chooseList && chooseList.length ? '确认以上选择' : '未选择房源'
    const choosed = chooseList && chooseList.length

    return (
      <View className="footer">
      {
        choosed && (
          <View className="shoping-cart collapse">
            <View className={`title ${opened}`} onClick={this.trigCartPannel}>
              <Text>{title}</Text>
              {collapsed?<Text className="at-icon at-icon-chevron-up"></Text> :<Text className="at-icon at-icon-chevron-down"></Text> }           
            </View>

            <View className={`choose-list ${opened}`}>
              {chooseList.map((house, index) => {
                const name = [house.termName, house.blockName, house.unitName, house.floorName, house.roomName].join('')

                return (
                  <View key={`cart-item-${index}`} className="choose-item" onClick={() => this.subChooseList(house)}>
                    <View className="choose-item-body">{name}</View>
                    <View className="choose-item-action">
                      <Text className="at-icon at-icon-subtract-circle"></Text>
                    </View>
                  </View>
                )
              })}
            </View>          
          </View>
        )
      }
        <Button className={`btn ${nodata}`} onClick={this.handleSubmit}>{btnText}</Button>
      </View>
    )
  }

  renderBlank() {
    const { houseList } = this.state

    return !(houseList && houseList.length) && (
      <Blank tips="暂无符合条件的房源" />
    )
  }

  render() {
    return (
      <View className="house-cart">
        {this.renderHead()}
        {this.renderBlank()}
        {this.renderHouses()}
        {this.renderAction()}
      </View>
    )
  }
}