import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import LoginJudge from '@/c/login/Judge'
import { arrToObj } from '@utils'
import { AtTabs } from 'taro-ui'

import Chat from '@/c/chat/com'
import './roomPriceXk.scss'

class Index extends Component {
  onShareAppMessage() {
    const {eId, id, name} = this.$router.params
    return {
      title: `来看看${name}的一房一价表`,
      path: `/pagesRoom/roomPrice?eId=${eId}&id=${id}&name=${name}`,
    }
  }
  onShareTimeline () {
    const {eId, id, name} = this.$router.params
    return {
      title: `来看看${name}的一房一价表`,
      path: `/pagesRoom/roomPrice?eId=${eId}&id=${id}&name=${name}`,
    }
  }

  constructor (props) {
    super(props)
    const {eId: curId} = this.$router.params
    this.state = {
      curId,
      curObj: {},
      curNav: 0,
      roomArr: [],
      curRoomObj: {},
      houseSaleStateArr: ['未售', '小定', '已定', '已售'],
      isDtlShow: false,
      buildingNumList: [],
    }
  }

  config = {
    navigationBarTitleText: '一房一价表',
    navigationBarBackgroundColor: '#369af7',
    navigationBarTextStyle: 'white'
  }

  componentWillMount () {
    Taro.$AHU(this)
    // const { name } = this.$router.params
    // Taro.setNavigationBarTitle({
    //   title: name + '-一房一价表' || '一房一价表'
    // })
    const {eId, id} = this.$router.params
    Taro.api.house.apiestatelottery2batchinfo({
      lottery_id: id,
      estate_id: eId,
    }).then(res => {
      let ll = res.lottery_list || []
      let buildingNumList = []
      ll.forEach(item => {
        const arr = item.building_num.split(',')
        arr.forEach(sub => {
          buildingNumList.push({
            id: item.id,
            title: sub,
            lottery_time: item.lottery_time
          })
        })
      })
      this.setState({
        buildingNumList,
        curObj: res || {}
      }, () => {
        this.getDtl()
      })
    })
  }

  getDtl = () => {
    const { curNav, buildingNumList } = this.state
    const {eId, name, id} = this.$router.params
    Taro.api.house.apiestatelotterypricelist({
      estate_id: eId,
      lottery_id: buildingNumList[curNav].id,
      building_num: buildingNumList[curNav].title,
    }).then(res => {
      this.setState({
        roomArr: res || []
      })
      if (this.subChat) {
        this.subChat.getData({name, id: eId}, 'pt')
      }
    })
  }
  onceGetInfo () {
    const {eId} = this.$router.params
    const { curObj, curNav, buildingNumList } = this.state
    if (curObj.id === buildingNumList[curNav].id) {
      return
    }
    Taro.api.house.apiestatelottery2batchinfo({
      lottery_id: buildingNumList[curNav].id,
      estate_id: eId,
    }).then(res => {
      this.setState({
        curObj: res || {}
      })
    })
  }

  refChat = (ref) => {
    this.subChat = ref
  }

  componentDidShow () { }

  componentDidHide () { }

  renderTop () {
    const {eId, id, name} = this.$router.params
    const curParams = `eId=${eId}&id=${id}&name=${name}`
    const { curObj, curNav, buildingNumList } = this.state
    const nameIcon = require('./img/yfyj/yfyj04.png')
    const i1 = require('./img/yfyj/yfyj05.png')
    const i2 = require('./img/yfyj/yfyj06.png')
    const op1 = require('./img/yfyj/yfyj_icon1.png')
    const op2 = require('./img/yfyj/yfyj_icon2.png')
    const op3 = require('./img/yfyj/yfyj_icon3.png')
    const op4 = require('./img/yfyj/yfyj_icon4.png')
    const bg = require('./img/yfyj/bg.jpg')
    return (
      <View className="scoped-header">
        <View className="scoped-top">
          <Image src={bg} className="bg"></Image>
          <View className="st-wrap">
            <View className="st-header">
              <View className="text">
                <Image src={nameIcon} className="i"></Image>
                <View className="t">{name}</View>
              </View>
              <View className="r" onClick={this.urlDtlLink.bind(this)}>返回楼盘详情</View>
            </View>
            <View className="st-p1">
              <Image className="i" src={i1}></Image>
              <View className="t">{curObj.under_way}</View>
            </View>
            <View className="st-p1">
              <Image className="i" src={i2}></Image>
              <View className="t2">{curObj.lottery_time}</View>
            </View>
            <View className="st-p2">
              <Image src={op1} className="op1" onClick={this.urlLink.bind(this, '/pagesRoom/roomPriceList', curParams)}></Image>
              <Image src={op2} className="op2" onClick={this.urlLink.bind(this, '/pagesRoom/roomPriceImg', curParams)}></Image>
              <Image src={op3} className="op3" onClick={this.previewImageHandle.bind(this, curObj.project_img, [curObj.project_img])}></Image>
              <Image src={op4} className="op4" onClick={this.previewQrcodeImageHandle.bind(this, 'http://icon.honglounews.com/ncfxw2.jpg', ['http://icon.honglounews.com/ncfxw2.jpg'])}></Image>
            </View>
            {this.renderQrcode()}
          </View>
        </View>
        <View className="sh-nav">
          <AtTabs
            current={curNav}
            scroll
            tabList={buildingNumList}
            onClick={this.navClick.bind(this)}>
          </AtTabs>
        </View>
      </View>
    )
  }
  urlLink (u, params) {
    if (u === 'dev') {
      Taro.$msg('开发中~敬请期待')
    } else {
      let url = u
      if (params) url += `?${params}`
      Taro.navigateTo({
        url
      })
    }
  }
  navClick (value) {
    this.setState({
      curNav: value
    }, () => {
      this.getDtl()
      this.onceGetInfo()
    })
  }
  renderQrcode () {
    const qrcodeImg = 'http://icon.honglounews.com/miniqrcode.jpg'
    return (
      <Image src={qrcodeImg} className="scoped-qrcode"  onClick={this.previewQrcodeImageHandle.bind(this, qrcodeImg, [qrcodeImg])} />
    )
  }
  previewQrcodeImageHandle (current, urls) {
    Taro.previewImage({
      current,
      urls
    })
  }
  //  
  urlDtlLink () {
    const { eId } = this.$router.params
    Taro.navigateTo({url: '/pagesHouse/indexDtl?id=' + eId + '&YH=zzyh'})
  }

  renderInfo () {
    const { roomArr } = this.state
    let cArr = roomArr || []
    const htArr = cArr[0] ? cArr[0].data : []
    const htArrIndex = htArr.length
    const htitems = htArr.map((item, index) => {
      let boxClassStr = `'srp-col num'${htArrIndex}`
      return (
        <View className={boxClassStr} key={index}>
          <View className="srp-ht">
            <View className="srp-img">
              <Image src={item.house_img + '_xs'} className="img" onClick={this.previewImageHandle.bind(this, item.house_img, [item.house_img])}/>
              <View className="tips">
                <View className="bg"></View>
                <View className="t">查看大图</View>
              </View>
            </View>
            <View className="p1">{item.house_type}</View>
            <View className="p2">{item.built}㎡</View>
            {
              item.house_rate === '100%'
              ? ''
              : 
              <View className="p2">得房率:{item.house_rate}</View>
            }
          </View>
        </View>
      )
    })
    return (
      <View className="scoped-room-price">
        <View className="srp-row">
          <View className="srp-col">户型图</View>
          {htitems}
        </View>
        {
          cArr.map((one, oIndex) => {
            return (
              <View className="srp-row" key={oIndex}>
                <View className="srp-col">{one.storey}层</View>
                {
                  one.data.map((two, tIndex) => {
                    const oneDataLength = one.data.length
                    let boxClassStr2 = `'srp-col num'${oneDataLength}`
                    if (two.house_sale_state === '小定') boxClassStr2 = `'srp-col t2 num'${oneDataLength}`
                    if (two.house_sale_state === '已定') boxClassStr2 = `'srp-col t3 num'${oneDataLength}`
                    if (two.house_sale_state === '已售') boxClassStr2 = `'srp-col t4 num'${oneDataLength}`
                    return (
                      <View className={boxClassStr2} key={tIndex} onClick={this.openDtlPopup.bind(this, two)}>
                        {
                          two.house_sale_state === '小定' || two.house_sale_state === '已定' || two.house_sale_state === '已售'
                          ? 
                          <View className="srp-tag">{two.house_sale_state}</View>
                          : ''
                        }
                        <View className="srp-room">
                          <View className="srpr-p1">{two.room}
                            <View className="s">{'>>'}</View>
                          </View>
                          <View className="srpr-p2">{two.built}㎡</View>
                          <View className="srpr-p2">￥{parseInt(two.sale)}/㎡</View>
                          <View className="srpr-p2">总价:{(Number(two.price) / 10000).toFixed(1)}万</View>
                        </View>
                      </View>
                    )
                  })
                }
              </View>
            )
          })
        }
      </View>
    )
  }
  previewImageHandle (cur, arr) {
    const current = `${cur}_plus`
    const urls = arr.map(item => {
      return `${item}_plus`
    })
    Taro.previewImage({
      current,
      urls
    })
  }


  renderDtl () {
    const { isDtlShow, curRoomObj, houseSaleStateArr } = this.state
    let boxClassStr = 'p2 t1'
    if (curRoomObj.house_sale_state === '小定') boxClassStr = `'p2 t2`
    if (curRoomObj.house_sale_state === '已定') boxClassStr = `'p2 t3`
    if (curRoomObj.house_sale_state === '已售') boxClassStr = `'p2 t4`
    
    let newTotalPrice = curRoomObj.price
    if (curRoomObj.house_discount) {
      const hdArr = curRoomObj.house_discount.split(',')
      hdArr.forEach(dis1 => {
        const oneStr = dis1.substr(0,1)
        const otherStr = dis1.substr(1,dis1.length)
        if (oneStr === '*'){
          newTotalPrice = (Number(newTotalPrice * otherStr).toFixed(2))
        }
        if (oneStr === '-'){
          newTotalPrice = (Number(newTotalPrice - otherStr).toFixed(2))
        }
        if (oneStr === '+'){
          newTotalPrice = (Number(newTotalPrice + otherStr).toFixed(2))
        }
      })
    }
    let newOnePrice = Number(newTotalPrice / curRoomObj.built).toFixed(2)
    return (
      <View className={isDtlShow ? 'l-modal-box' : 'l-modal-box hide'}>
        <View className='lmb-bg'></View>
        <View className='lmb-body'>
          <View className="scoped-dtl">
            <View className="sd-img">
              <Image src={curRoomObj.house_img + '_xs'} className="img" onClick={this.previewImageHandle.bind(this, curRoomObj.house_img, [curRoomObj.house_img])}/>
              <View className="tips">
                <View className="bg"></View>
                <View className="t">查看大图</View>
              </View>
            </View>
            <View className="sd-p">
              <View className="p2">{curRoomObj.house_type}</View>
              <View className="p2">{curRoomObj.building_num}</View>
              <View className="p2">房号:{curRoomObj.room}</View>
              <View className="p2">层高:{curRoomObj.floor_height}</View>
              <View className="p2">建筑面积:{curRoomObj.built}㎡</View>
              <View className="p2">套内面积:{curRoomObj.built === curRoomObj.space ? '未知' : curRoomObj.space}㎡</View>
              <View className="p2">公摊面积:{curRoomObj.built === curRoomObj.space ? '未知' : curRoomObj.sharing}㎡</View>
              <View className="p2">得房率:{curRoomObj.built === curRoomObj.space ? '未知' : curRoomObj.house_rate}</View>
              <View className="p2">毛坯:{curRoomObj.blank}元/㎡</View>
              <View className="p2">装修:{curRoomObj.decoration}元/㎡</View>
              <View className="p2">单价:{curRoomObj.sale}元/㎡</View>
              <View className="p2">总价:{curRoomObj.price}元</View>
            </View>
            <View className="sd-label">销控数据
              
            </View>
            <View className="sd-p">
              <View className={boxClassStr}>

              <Picker mode='selector' range={houseSaleStateArr} onChange={this.onSaleStateChange}>
              {curRoomObj.house_sale_state}<View className="s">{'修改>>'}</View>
              </Picker>

              </View>
              <View className="p2">折扣：
                <Input type='text' placeholder='请输入' value={curRoomObj.house_discount} onInput={this.inputCHnage.bind(this, 'house_discount')} />
              </View>
              <View className="p2">备注：
                <Textarea placeholder='请输入' style='background:#fff;width:100%;min-height:50px;padding:0 30rpx;box-sizing: border-box;text-align: left;color: #666;' value={curRoomObj.house_sale_remark} autoHeight/>
              </View>
              <View className="p2">
                <View className="s">折后总价：{newTotalPrice || '暂无'}元</View>
                <View className="s">折后单价：{newOnePrice || '暂无'}元/㎡</View>
              </View>
            </View>
            <View className="l-floor-footer t2">
              <View className="lff-flex">
                <View className="lff-btn t3" onClick={this.closeRulePopup.bind(this)}>关闭</View>
                <View className="lff-btn t2" onClick={this.closeRulePopup.bind(this, 'edit')}>保存</View>
              </View>
            </View>
          </View>
        </View>
      </View>
    )
  }
  inputCHnage (str, e) {
    let { curRoomObj } = this.state
    curRoomObj[str] = e.target.value
    this.setState({
      curRoomObj
    })
  }

  // const { valStr, bc } = this.props
    // bc(valStr, strTrim())
  onSaleStateChange = e => {
    let { curRoomObj, houseSaleStateArr } = this.state
    curRoomObj.house_sale_state = houseSaleStateArr[e.detail.value]
    this.setState({
      curRoomObj
    })
  }
  
  openDtlPopup (item) {
    this.setState({
      curRoomObj: item,
      isDtlShow: true
    })
  }
  closeRulePopup (str) {
    this.setState({
      curRoomObj: {},
      isDtlShow: false
    })
    if (str === 'edit') {
      let { curRoomObj } = this.state
      let house_discount = curRoomObj.house_discount.replace(/，|、|\/|\\/g, ',')
      Taro.api.house.apiestatelotterypriceedit({
        id: curRoomObj.id,
        house_sale_state: curRoomObj.house_sale_state,
        house_sale_remark: curRoomObj.house_sale_remark || '',
        house_discount,
      }).then(res => {
        this.getDtl()
      })
    }
  }

  renderShare () {
    const iconShare = require('@img/images/icon_g_share6.png')
    return (
      <Button className="g-icon-share btn-to-div" openType="share">
        <Image className="img" src={iconShare} />
      </Button>
    )
  }

  render () {
    return (
      <View className="l-box">
        <LoginJudge />
        {this.renderTop()}
        {this.renderInfo()}
        {this.renderDtl()}
        {this.renderShare()}
        <Chat onRef={this.refChat} />
      </View>
    )
  }
}

export default Index
