import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Block } from '@tarojs/components'
import HouseCard from '../../components/HouseCard'
import RaiseCard from '../../components/RaiseCard'
import { getItemList } from '@/services/item'
import { queryPreselectionRecord, queryRaiseRecord, querySalesList, queryApartmentType } from '@/services/project'
import { connect } from '@tarojs/redux'
import ready from '@/utils/ready'
import Blank from '../../components/Blank'
import Statement from '../../components/Statement'
import { transferImage } from '@/utils/tools'
import PickerComponent from '../../components/Picker'
import './index.scss'
import * as houseActions from '@/actions/house'
import * as noticeType from '@/constants/common.js'


@connect(
  ({ user, city, house }) => ({ ...user, ...city, house }),
  { ...houseActions }
)
export default class Records extends Component {
  config = {
    navigationBarTitleText: '选房记录'
  }

  state = {

    current: 0,
    recordList: [],
    noRecord: false,
    raiseList: [],
    noRaiseRecord: false,
    screenVisible: false,
    buildingList: [],
    buildingValue: '',
    buildingId: '',

    salesList: [],
    saleBatch: '',
    salesBatchId: '',

    apartmentList: [],
    apartmentValue: '',
    apartmentId: '',

    lockStatus: [{ value: '不限', code: '' }, { value: '未锁定', code: 'unlocked' }, { value: '已锁定', code: 'locked' }],
    lockStatusValue: '',
    houseLockingStatus: '',

    lockCustomer: [{ value: '不限', code: '' }, { value: '我自己', code: 'mine' }, { value: '其他人', code: 'other' }],
    lockCustomerValue: '',
    customerLocked: '',

    chooseList: [], // 选中的房源ID列表
    clickDisable: true,
  }
  componentDidShow() {
    ready.queue(() => {

      const { id: salesBatchId = '' } = this.$router.params
      const { userInfo: { person: { personId } }, house } = this.props
      const params = {
        personId,
        // salesBatchId,
        pageNumber: 1,
        pageSize: 999,
      }
      this.getPreselection(params)
      this.getRaise(params)
      querySalesList().then(res => {
        res.unshift({ salesBatchName: '请选择', salesBatchId: '' })
        this.setState({
          salesList: res || [],
        })
      })
      this.loadBuildingList()

      if (house.raiseCart.length) {
        this.setState({ chooseList: house.raiseCart.map(x => x.houseId) })
      }

      this.setState({ salesBatchId })

      // 清空认筹选择
      this.props.dispatchFlush2Cart([])
    })
  }
  getPreselection(params) {
    queryPreselectionRecord(params).then(res => {
      const list = res.records
      this.setState({
        recordList: list.filter(item => item.status == '1') || [],

      }, () => {
        this.setState({
          noRecord: this.state.recordList.length > 0 ? false : true
        })
      })
    })
  }
  getRaise(params) {
    queryRaiseRecord(params).then(res => {
      this.setState({
        raiseList: res.records || [],

      }, () => {
        this.setState({
          noRaiseRecord: this.state.raiseList.length > 0 ? false : true
        })
      })
    })
  }
  loadBuildingList() {
    const params = {
      pageNumber: 1,
      pageSize: 50,
      // cityId: this.props.curCity.id || ''
    }
    getItemList(params).then(res => {
      res.records.unshift({ buildingName: '请选择', buildingId: '' })
      this.setState({
        buildingList: res.records,
      })
    })

  }

  CheckboxChange = (e) => {
    // 加了一个转整型的处理
    // 因为所有的 houseId 都是整型
    this.setState({ chooseList: e.detail.value.map(x => (x - 0)) })
  }

  handleSubmit = () => {
    const { recordList, chooseList } = this.state
    if (!chooseList.length) {
      Taro.showToast({ title: '请选择房源', icon: 'none' })
      return;
    }

    const houseList = recordList.map(x => x.housingInfo).filter(x => chooseList.indexOf(x.houseId) > -1)

    // 选择房源必须同一批次
    const checkHouse = houseList[0]
    for (let inx in houseList) {
      if (houseList[inx].salesBatchId != checkHouse.salesBatchId) {
        Taro.showToast({ title: '所选房源不属于同一销售批次, 请筛选后重选', icon: 'none', duration: 2000, })
        return;
      }
    }

    this.props.dispatchFlush2Cart(houseList);

    Taro.navigateTo({
      url: `/onlineSelling/pages/raiseMoney/index?salesBatchId=${checkHouse.salesBatchId}`
    })
  }
  toHouseDetail(item) {
    if (item.housingStatus == '0' || item.saleBatchStatus == '0') {
      Taro.showToast({ title: '当前销售批次或该房源已被取消发布', icon: 'none', duration: 2000 })
    } else {
      Taro.navigateTo({
        url: `/onlineSelling/pages/detail/index?id=${item.houseId}`
      })
    }
  }
  renderPreselection() {
    const { recordList, noRecord, chooseList } = this.state

    return (
      <Block>
        <ScrollView scrollY className="container">
          <CheckboxGroup onChange={this.CheckboxChange}>
            {
              noRecord ? <Blank style="margin:10vh 0 22vh 0" tips="暂无预选记录" /> :
                <View>
                  {
                    recordList.map((item) => {
                      // const checked = (chooseList || []).filter(x => x == item.houseId)[0]
                      // const disabled = item.housingInfo.houseLockingStatus == 'locked'

                      return (
                        <Label class="checkbox" >
                          {/* <Checkbox value={item.houseId - 0} checked={checked} disabled={disabled}> */}
                          <View className="carditem" key={item.preselectionRecordId} >
                            <HouseCard summary={item} onClick={() => this.toHouseDetail(item)} />
                          </View>
                          {/* </Checkbox> */}
                        </Label>
                      )
                    })
                  }
                </View>
            }
          </CheckboxGroup>
          <Statement />
        </ScrollView >

        {/* <View className="raise-box"> <View className="raise-btn" onClick={this.handleSubmit}>认筹房源</View></View> */}

      </Block>
    )
  }
  toRaiseProfile(id) {
    this.setState({
      clickDisable: false
    })

    const { userInfo: { miniApp: { tpls } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_HOUSE && x.isSubscribe == true)[0] || {}).tplId
    const that = this
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
      },
      fail(res) {

      },
      complete() {
        that.setState({
          clickDisable: true
        })
        Taro.navigateTo({
          url: `/onlineSelling/pages/raiseProfile/index?id=${id}`
        })
      }
    })

  }
  renderRaise() {
    const { raiseList, noRaiseRecord, clickDisable } = this.state
    return (
      <Block>
        <ScrollView scrollY className="container">
          {
            noRaiseRecord ? <Blank style="margin:10vh 0 22vh 0" tips="暂无认筹记录" /> :
              <Block>
                {
                  raiseList.map(item => (
                    <View key={item.raiseRecordId} >
                      <RaiseCard handleCard={clickDisable ? () => this.toRaiseProfile(item.raiseRecordId) : ''} summary={item} statusType="raise" />
                    </View>
                  )
                  )
                }

              </Block>
          }
          <Statement styel="margin-top:80rpx" />
        </ScrollView >

      </Block>
    )
  }


  handleBuildingChange = e => {
    const { buildingList } = this.state
    this.setState({
      buildingValue: buildingList[e.detail.value].buildingName,
      buildingId: buildingList[e.detail.value].buildingId,
    }, () => {
      querySalesList({ buildingId: this.state.buildingId }).then(res => {
        res.unshift({ salesBatchName: '请选择', salesBatchId: '' })
        this.setState({
          salesList: res || [],
        }, () => {
          console.log(this.state.salesList, "salesListsalesListsalesListsalesListsalesListsalesList")
        })
      })
    })
  }
  handleSaleBatchChange = e => {
    const { salesList } = this.state
    this.setState({
      saleBatch: salesList[e.detail.value].salesBatchName,
      salesBatchId: salesList[e.detail.value].salesBatchId,

    }, () => {
      if (this.state.salesBatchId) {
        this.loadAparamentType(this.state.salesBatchId)
      } else {
        this.setState({
          apartmentList: [{ apartmentName: '请选择', apartmentId: '' }]
        })
      }
    })
  }

  loadAparamentType(salesBatchId) {
    queryApartmentType({ salesBatchId: salesBatchId }).then(res => {
      if (res) {
        res.unshift({ apartmentName: '请选择', apartmentId: '' })
        this.setState({
          apartmentList: res || []
        })
      } else {
        this.setState({
          apartmentList: [{ apartmentName: '请选择', apartmentId: '' }]
        })
      }

    })
  }

  handleApartmentChange = e => {
    const { apartmentList } = this.state

    this.setState({
      apartmentValue: apartmentList[e.detail.value].apartmentName,
      apartmentId: apartmentList[e.detail.value].apartmentId,
    })

  }
  handleLockStatusChange = e => {
    const { lockStatus } = this.state
    this.setState({
      lockStatusValue: lockStatus[e.detail.value].value,
      houseLockingStatus: lockStatus[e.detail.value].code,
    })
  }
  handleCustomerChange = e => {
    const { lockCustomer } = this.state
    this.setState({
      lockCustomerValue: lockCustomer[e.detail.value].value,
      customerLocked: lockCustomer[e.detail.value].code,
    })
  }


  unlimitedBtn() {

    this.setState({
      screenVisible: false,
      buildingValue: '',
      buildingId: '',
      saleBatch: '',
      salesBatchId: '',
      apartmentValue: '',
      apartmentId: '',
      lockStatusValue: '',
      houseLockingStatus: '',
      lockCustomerValue: '',
      customerLocked: '',
    })
    const { userInfo: { person: { personId } } } = this.props
    const params = {
      personId,
      pageNumber: 1,
      pageSize: 999,
    }
    this.getPreselection(params)
    this.getRaise(params)
  }
  ScreenBtn() {
    this.setState({
      screenVisible: false
    })
    const { userInfo: { person: { personId } } } = this.props
    const { buildingId, salesBatchId, houseLockingStatus, apartmentId, customerLocked } = this.state

    if (this.state.current == '0') {

      const params = {
        personId,
        pageNumber: 1,
        pageSize: 999,
        buildingId,
        salesBatchId,
        apartmentId,
        houseLockingStatus,
        customerLocked
      }
      this.getPreselection(params)
    } else {

      const params = {
        personId,
        pageNumber: 1,
        pageSize: 999,
        buildingId,
        salesBatchId,
        houseLockingStatus,
      }

      this.getRaise(params)
    }


  }

  renderPreselectScreen() {
    const { current, buildingValue, buildingList, saleBatch, salesList, apartmentList, apartmentValue, lockCustomerValue, lockCustomer, lockStatusValue, lockStatus } = this.state

    const selector = [{ buildingTypeName: '楼盘1' }, { buildingTypeName: '楼盘2' }, { buildingTypeName: '楼盘3' }, { buildingTypeName: '楼盘4' }]

    return (

      <View className="base-con">
        <PickerComponent title="选择楼盘" selector={buildingList} keyValue={"buildingName"} currentValue={buildingValue || ''} handleChange={this.handleBuildingChange} />
        <PickerComponent title="选择销售批次" selector={salesList} keyValue={"salesBatchName"} currentValue={saleBatch || ''} handleChange={this.handleSaleBatchChange} />
        {current == '0' && <PickerComponent title="选择户型" selector={apartmentList} keyValue={"apartmentName"} currentValue={apartmentValue || ''} handleChange={this.handleApartmentChange} />}
        <PickerComponent title="锁定状态" selector={lockStatus} keyValue={"value"} currentValue={lockStatusValue || ''} handleChange={this.handleLockStatusChange} />
        {current == '0' && <PickerComponent title="锁定客户" keyValue={"value"} selector={lockCustomer} currentValue={lockCustomerValue || ''} handleChange={this.handleCustomerChange} />}

        <View className="bottom-btn">
          <View className="save" onClick={this.ScreenBtn}>
            筛选
            </View>
          <View className="cancel" onClick={this.unlimitedBtn}>
            不限
          </View>
        </View>
      </View>
    )
  }


  handleScreenClick() {


    this.setState({
      screenVisible: true
    })

  }
  handleCondition(value) {
    this.setState({
      current: value,
      buildingValue: '',
      buildingId: '',
      saleBatch: '',
      salesBatchId: '',
      apartmentValue: '',
      apartmentId: '',
      lockStatusValue: '',
      houseLockingStatus: '',
      lockCustomerValue: '',
      customerLocked: '',


    })
  }
  renderBar() {
    const { current } = this.state
    const condition = [{ title: '预选记录', value: 0 }, { title: '认筹单', value: 1 }]

    return (
      <Block>
        <View className="screen-top">
          <View className="flex">
            {condition.map(item => (
              <View key={item.value} onClick={() => this.handleCondition(item.value)} className={current == item.value ? 'top-item active' : 'top-item'}>
                {item.title}
              </View>
            ))}
          </View>
          <View onClick={this.handleScreenClick}>
            <Image style="width:50rpx;height:50rpx" src={transferImage(require('../../assets/screen.png'))}></Image>
          </View>
        </View>
        {current == 0 && this.renderPreselection()}
        {current == 1 && this.renderRaise()}
      </Block>
    )
  }
  render() {

    const { screenVisible } = this.state
    return (
      <View className="records" >
        {!screenVisible && this.renderBar()}
        {screenVisible && this.renderPreselectScreen()}

      </View >
    )
  }
}
