import Taro, { Component } from '@tarojs/taro'
import { View, Map } from '@tarojs/components'
import { arrToObj } from '@utils'

import './pkList.scss'
import ListMore from '@/c/pageDataList/listMore'

class Index extends Component {
  onShareAppMessage() {
    const { dataList } = this.state
    const curArr = dataList.map(item => {
      return item.id
    })
    return {
      title: `看看我选的这几个楼盘怎么样`,
      path: `/pagesHouse/pkList?id=${curArr.join(',')}`,
    }
  }
  onShareTimeline () {
    return {
      title: '让买房，更省心！',
    }
  }

  constructor (props) {
    super(props)
    this.state = {
      dataList: [],
      isCanPk: false
    }
  }

  config = {
    navigationBarTitleText: 'PK列表',
  }

  componentWillMount () {
    const {id} = this.$router.params
    //  && !Taro.getStorageSync('APP_pkList')
    if (id) {
      const idArr = id.split(',') || []
      let tempArr = []
      idArr.forEach(cId => {
        tempArr.push(
          new Promise((resolve, reject) => {
            Taro.api.house.admestatesimple({id: cId}).then(res => {
              return resolve(res)
            }).catch(err => {
              return reject(err)
            })
          })
        )
      })
      Promise.all(tempArr).then(res => {
        if (res && res.length > 0 && !Taro.getStorageSync('APP_pkList')) Taro.setStorageSync('APP_pkList', res)
        this.setState({
          dataList: res || []
        })
      })
    } else {
      this.getDtl()
    }
  }

  getDtl = (data) => {
    const dataList = data || Taro.getStorageSync('APP_pkList') || []
    this.setState({
      dataList
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  previewImageHandle (cur, arr) {
    const current = `${cur}_plus`
    const urls = arr.map(item => {
      return `${item.img_url}_plus`
    })
    Taro.previewImage({
      current,
      urls
    })
  }

  checkHandle (item, index) {
    const { dataList } = this.state
    const curData = JSON.parse(JSON.stringify(dataList))
    let curItem = {...item}
    curItem.check = curItem.check === '1' ? '2' : '1'
    curData[index] = curItem
    let num = 0
    curData.forEach(item => {
      if (item.check === '1') {
        num++
      }
    })
    if (num > 1) {
      this.setState({isCanPk: true})
    } else {
      this.setState({isCanPk: false})
    }
    if (num > 2) {
      Taro.$msg("请选择两个楼盘进行PK")
    } else {
      this.setState({
        dataList: curData
      })
    }
  }
  delHandle (item, index) {
    Taro.$msgConfirm(`确定删除${item.estate_name}吗？`, () => {
      let { dataList } = this.state
      dataList.splice(index, 1)
      this.setState({
        dataList,
      }, () => {
        Taro.setStorageSync('APP_pkList', dataList)
      })
    })
  }

  renderPkList () {
    const { dataList } = this.state
    const dictData = Taro.getStorageSync('dictData')
    const icon01 = require('@img/icon_g_check01.png')
    const icon02 = require('@img/icon_g_check02.png')
    const delIcon = require('@img/icon_g_del2.png')
    const curItems = dataList.map((item, index) => {
      const product_type = item.product_type || ''
      const productTypeArr = product_type.split(',').map(v => {
        return arrToObj(dictData.product_type)[v]
      })
      const cTagStr = item.custom_tag || ''
      const tagViews = cTagStr.split(',').map((tag, tagIndex) => {
        return (
          <View className="s" key={tagIndex}>{tag}</View>
        )
      })
      return (
        <View className="lhl-item col-1" key={index}>
          <View className="scoped-deal">
            <View className="sd-check" onClick={this.checkHandle.bind(this, item, index)}>
              {
                item.check === '1'
                ? <Image className="icon" src={icon01}></Image>
                : <Image className="icon" src={icon02}></Image>
              }
            </View>
            {/* <View className="sd-del" onClick={this.delHandle.bind(this, item, index)}>
              <Image className="icon" src={delIcon}></Image>
            </View> */}
          </View>
          <View className="lhl-img">
            <Image src={item.pri_image + '_xs'} className="img" />
          </View>
          <View className="lhl-info" onClick={this.checkHandle.bind(this, item, index)}>
            <View className="lhl-p1">{item.estate_name}</View>
            <View className="lhl-p2">{item.price_range || "未知"}/㎡</View>
            <View className="lhl-p3">{arrToObj(dictData.area_type)[item.area_type]}  {productTypeArr.length > 0 ? `-${productTypeArr.join('/')}` : ''}</View>
            <View className="lhl-sign">
              {
                item.estate_tag === '售罄'
                ? <View className="s t4">{item.estate_tag}</View>
                : item.estate_tag === '待售'
                ? <View className="s t3">{item.estate_tag}</View>
                : <View className="s t2">{item.estate_tag}</View>
              }
              {tagViews}
            </View>
          </View>
          <View className="scoped-del" onClick={this.delHandle.bind(this, item, index)}>
            <Image className="icon" src={delIcon}></Image>
          </View>
        </View>
      )
    })
    
    return (
      <View className="l-house-list">
        {curItems}
      </View>
    )
  }



  saveHandle () {
    const { dataList } = this.state
    const {id} = this.$router.params
    let edIndex = []
    let edIds = []
    dataList.forEach((item, index) => {
      if (item.check === '1') {
        edIds.push(item.id)
        edIndex.push(index)
      }
    })
    if (id) {
      Taro.navigateTo({
        url: `/pagesHouse/pkDtl?id=${edIds.join(',')}`
      })
    } else {
      Taro.navigateTo({
        url: `/pagesHouse/pkDtl?i=${edIndex.join(',')}`
      })
    }
  }
  
  addHandle () {
    Taro.navigateTo({
      url: '/pagesHouse/pkAdd'
    })
  }

  tipsHandle () {
    Taro.$msg("请选择两个楼盘进行PK")
  }


  linkHome () {
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
  renderGoHome () {
    const icon = require('@img/images/icon_go_home.png')
    return (
      <Image className="g-go-home" src={icon} onClick={this.linkHome.bind(this)}/>
    )
  }

  render () {
    const { dataList, isCanPk } = this.state
    return (
      <View className="l-box has-footer">
        {this.renderPkList()}
        {
          dataList.length === 0
          &&
          <ListMore isOther={true} text="暂无楼盘" />
        }
        <View className="l-floor-footer">
          <View className="lff-flex">
            <View className="lff-btn t2" onClick={this.addHandle.bind(this)}>添加楼盘</View>
            {
              isCanPk
              ? <View className="lff-btn t2s" onClick={this.saveHandle.bind(this)}>开始PK</View>
              : <View className="lff-btn t3s" onClick={this.tipsHandle.bind(this)}>开始PK</View>
            }
          </View>
        </View>
        {this.renderGoHome()}
      </View>
    )
  }
}

export default Index
