import Taro, { Component } from '@tarojs/taro'
import { View, Swiper, SwiperItem } from '@tarojs/components'
import { AtCurtain } from 'taro-ui'
import { arrToObj } from '@utils'
import Rooms from './components/dtl/rooms'
import './dtl.scss'

class Index extends Component {
  onShareAppMessage() {
    const { curId, curObj } = this.state
    return {
      title: `${curObj.title}`,
      path: `/pagesRoom/dtl?id=${curId}`,
    }
  }
  onShareTimeline () {
    const { curId, curObj } = this.state
    return {
      title: `${curObj.title}`,
      path: `/pagesRoom/dtl?id=${curId}`,
    }
  }

  constructor (props) {
    super(props)
    const {id: curId} = this.$router.params
    this.state = {
      curId,
      curObj: {},
      curImgIndex: 0,
      curShareCardImg: require('./img/dtl/bg_room_dtl.png')
    }
  }

  config = {
    navigationBarTitleText: '房源详情',
  }

  componentWillMount () {
    Taro.$AHU(this)
    this.getDtl()
    // this.popupOpen()
  }
  
  getDtl = () => {
    const { curId } = this.state
    Taro.api.room.apieshousedetail({id: curId}).then(res => {
      Taro.setNavigationBarTitle({
        title: res.title || '房源详情'
      })
      this.drawAndShareImage(res.mini_coder)
      this.setState({
        curObj: res || {}
      }, () =>{
        if (this.subRooms) this.subRooms.getData(res.old_house_list || [])
      })
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  renderHeader () {
    const { curImgIndex, curObj } = this.state
    let moreImg = []
    let images = curObj.images ? curObj.images.split(',') : []
    images.forEach(url => {
      moreImg.push({img_url: `${url}`})
    })
    const imgArr = [{img_url: `${curObj.pri_image}`}, ...moreImg, {img_url: curObj.house_img}]
    return (
      <View className="dtl-header">
        <Swiper
          circular
          current={curImgIndex}
          onChange={this.headerImgChange.bind(this)}
          className='dh-swiper'>
            {
              imgArr.map((item, index) => {
                return (
                  <SwiperItem key={index}>
                    <View className='dh-item'>
                      <Image src={item.img_url ? item.img_url + '_white' : ''} className="img" onClick={this.previewImage2Handle.bind(this, item.img_url, imgArr)} />
                    </View>
                  </SwiperItem>
                )
              })
            }
        </Swiper>
        <View className="dh-count">
          <View className="bg"></View>
          <View className="num">{curImgIndex + 1}/{imgArr.length}</View>
        </View>
      </View>
    )
  }
  headerImgChange (e) {
    this.setState({
      curImgIndex: e.detail.current || 0
    })
  }
  previewImage2Handle (cur, arr) {
    const current = `${cur}`
    const urls = arr.map(item => {
      return `${item.img_url}`
    })
    Taro.previewImage({
      current,
      urls
    })
  }


  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
    })
  }


  editHandle () {
    const { curId } = this.state
    const appUserInfo = Taro.getStorageSync('APP_userInfo')
    if (appUserInfo.is_sale == 1) {
      Taro.navigateTo({
        url: `/pagesMore/center/uploadRoom2?id=${curId}`
      })
    }
  }
  
  renderMain () {
    const dictData = Taro.getStorageSync('dictData')
    const htObj = arrToObj(dictData.house_type)
    const ptObj = arrToObj(dictData.product_type)
    const atObj = arrToObj(dictData.area_type)
    const hryObj = arrToObj(dictData.house_room_year)
    const roomDecObj = arrToObj(dictData.room_dec)
    const { curObj } = this.state
    const tagArr = curObj.custom_tag ? curObj.custom_tag.split(',') : []
    const moreImg = require('./img/dtl/bg_estate.png')
    const FH = Number(curObj.floor) || 1
    const H = Number(curObj.storeys) || 1
    let FHstr = '未知'
    if (FH > H * 0.6666) {
      FHstr = '中高层'
    } else if (FH > H * 0.33333) {
      FHstr = '中楼层'
    } else {
      FHstr = '中低层'
    }
    if (FH === 1) FHstr = '一楼'
    if (FH === H) FHstr = '顶楼'
    return (
      <View className="scoped-main">
        {this.renderQrcode()}
        <View className="sm-tags">
          {
            tagArr.map((tag, tI) => {
              return (
                <View className="s" key={tI}>{tag}</View>
              )
            })
          }
        </View>
        <View className="sm-title" onClick={this.editHandle.bind(this)}>{curObj.title}</View>
        <View className="sm-focus">
          <View className="op">
            <View className="v">{curObj.price}万</View>
            <View className="k">总价</View>
          </View>
          <View className="op">
            <View className="v">{parseInt(curObj.price * 10000 / curObj.area)}元/㎡</View>
            <View className="k">单价</View>
          </View>
          {/* <View className="op">
            <View className="v"></View>
            <View className="k">户型</View>
          </View> */}
          <View className="op">
            <View className="v">{curObj.area}㎡</View>
            <View className="k">建筑面积</View>
          </View>
        </View>
        <View className="sm-op">
          <View className="op" onClick={this.houseImgHandle.bind(this)}>
            <View className="k">户型：</View>
            <View className="v">{htObj[curObj.house_type]}
              <View className="s">点击查看户型</View>
            </View>
          </View>
          <View className="op">
            <View className="k">楼层：</View>
            <View className="v">{FHstr}/{curObj.storeys}层</View>
          </View>
          <View className="op">
            <View className="k">满几年：</View>
            <View className="v">{hryObj[curObj.full_year]}</View>
          </View>
          {/* <View className="op">
            <View className="k">房源类型：</View>
            <View className="v">{ptObj[curObj.product_type]}</View>
          </View> */}
          <View className="op">
            <View className="k">装修状态：</View>
            <View className="v">{roomDecObj[curObj.is_dec]}</View>
          </View>
          <View className="op full">
            <View className="k">楼盘名称：</View>
            <View className="v">{curObj.estate_name}</View>
          </View>
          <Navigator url={`/pagesHouse/indexDtlAround?id=${curObj.estate_id}&name=${curObj.estate_name}`} className="op full">
            <View className="k">房源地址：</View>
            <View className="v">{curObj.address} <View className="s">查看周边配套</View></View>
          </Navigator>
          <View className="op">
            <View className="k">区域：</View>
            <View className="v">{atObj[curObj.area_type]}</View>
          </View>
          <View className="op">
            <View className="k">录入时间：</View>
            <View className="v">{curObj.create_at ? curObj.create_at.substring(0, 10) : ''}</View>
          </View>
          <Navigator url={`/pagesHouse/price?id=${curObj.estate_id}&name=${curObj.estate_name}`} className="op full">
            <View className="k">最近成交：</View>
            <View className="v t2">点击查看历史成交价</View>
          </Navigator>
          {
            curObj.introduce
            &&
            <View className="op full">
              <View className="k">房源简介：</View>
              <View className="v">{curObj.introduce}</View>
            </View>
          }
        </View>
        <Image className="sm-more" src={moreImg} onClick={this.dtlLink.bind(this)} />
      </View>
    )
  }
  dtlLink () {
    const { curObj } = this.state
    Taro.navigateTo({
      url: `/pagesHouse/indexDtl?id=${curObj.estate_id}`
    })
  }

  renderImg () {
    const { curObj } = this.state
    return (
      <View className="dtl-options">
        <View className="do-title">
          <View className="t">户型图</View>
        </View>
        <View className="do-content" onClick={this.houseImgHandle.bind(this)}>
          <View className="scoped-img">
            <Image src={curObj.house_img + '_xs'} className="img"/>
            <View className="tips">
              <View className="bg"></View>
              <View className="t">查看大图</View>
            </View>
          </View>
        </View>
      </View>
    )
  }
  houseImgHandle () {
    const { curObj } = this.state
    const current = `${curObj.house_img}_plus`
    const urls = [`${curObj.house_img}_plus`]
    Taro.previewImage({
      current,
      urls
    })
  }


  renderOther () {
    const { curObj } = this.state
    return (
      <View className="dtl-options">
        <View className="do-title">
          <View className="t">同小区房源</View>
          <Navigator url={'/pagesRoom/list?estate_id=' + curObj.estate_id + '&estate_name=' + curObj.estate_name} className="r">查看更多{' >'}</Navigator>
        </View>
        <Rooms onRef={this.refRooms} />
      </View>
    )
  }
  refRooms = (ref) => {
    this.subRooms = ref
  }


  netLink (saleObj) {
    const { curObj } = this.state
    Taro.navigateTo({
      url: `/pagesQa/msg/chat?to_user_id=${saleObj.user_id}&qTitle=${curObj.title}&qId=${curObj.id}`
    })
  }
  callHandle (saleObj) {
    Taro.makePhoneCall({
      phoneNumber: saleObj.sale_phone
    })
  }
  afterCount (type) {
    const { curObj } = this.state
    if (type === 'chat') {
      this.netLink(curObj.sale_user)
    }
    if (type === 'call') {
      this.callHandle(curObj.sale_user)
    }
  }
  countHandle (type) {
    const { curObj } = this.state
    Taro.api.room.apiusercontactclick({
      target_id: curObj.id,
      sale_id: curObj.sale_id,
      click_type: type === 'call' ? '2' : '1' // 1在线聊 2打电话
    }).then(() => {
      this.afterCount(type)
    }).catch(() => {
      this.afterCount(type)
    })
  }

  renderSale () {
    const { curObj } = this.state
    const saleObj = curObj.sale_user || {}
    const tagStr = saleObj.custom_tag ? saleObj.custom_tag.substring(0, 8) : ''
    return (
      <View className="scoped-sale">
        <View className="ss-img">
          <Image src={saleObj.sale_avatar} className="img"/>
        </View>
        <View className="ss-info">
          <View className="p1">{saleObj.sale_name}</View>
          <View className="p2">{tagStr}</View>
        </View>
        <View className="ss-r">
          <View className="b" onClick={this.countHandle.bind(this, 'chat')}>在线问</View>
          <View className="b t2" onClick={this.countHandle.bind(this, 'call')}>打电话</View>
        </View>
      </View>
    )
  }


  renderPopup () {
    const { isPopupShow, curShareCardImg  } = this.state
    return (
      <AtCurtain
        isOpened={isPopupShow}
        onClose={this.popupClose.bind(this)}
      >
        <Image
          className="scoped-share-card-img"
          src={curShareCardImg}
        />
      </AtCurtain>
    )
  }
  popupClose () {
    this.setState({
      isPopupShow: false
    })
  }
  popupOpen () {
    this.setState({
      isPopupShow: true
    })
  }


  drawAndShareImage (qrcodeSrc) {
    const { curObj } = this.state
    const that = this
    const canvas = Taro.createOffscreenCanvas({type: '2d', width: 600, height: 1067})
    const ctx = canvas.getContext('2d')
    ctx.rect(0 , 0 , canvas.width , canvas.height)
    ctx.fillStyle = "#fff"
    ctx.fill()
    const img1 = canvas.createImage()
    img1.src = require('./img/dtl/bg_room_dtl.png')
    img1.crossOrigin = 'Anonymous'
    img1.onload = () => {
      ctx.drawImage(img1, 0, 0, 600, 1067)
      const img2 = canvas.createImage()
      img2.src = qrcodeSrc
      img2.crossOrigin = 'Anonymous'
      img2.onload = () => {
        ctx.drawImage(img2, 320, 950, 100, 100)
        that.drawText(ctx, 'red', "哈哈哈哈，测试文字", 100, 500)
        let base64 = ctx.canvas.toDataURL("image/png")
        that.setState({
          curShareCardImg: base64
        })
      }
    }
  }
  drawText = (ctx, color, text, x, y, font = 50) => {
    ctx.font="50px Arial";
    ctx.fillStyle = color;
    ctx.textAlign = 'left';
    ctx.fillText(text, x, y);
    // ctx.stroke();
    // ctx.closePath();
   }




  render () {
    const { curObj } = this.state
    return (
      <View className="l-box has-footer">
        {this.renderHeader()}
        {this.renderMain()}
        {this.renderImg()}
        {(curObj.old_house_list && curObj.old_house_list.length > 0) && this.renderOther()}
        {this.renderSale()}
        {this.renderPopup()}
      </View>
    )
  }
}

export default Index
