import Taro, { Component } from '@tarojs/taro'
import { View, Image, Picker } from '@tarojs/components'
import { comGetTime } from '@utils'
import './index.scss'
export default class TopPie extends Component {
  constructor (props) {
    super(props)
    const curArr = props.curArr || []
    let startDate = ''
    let endDate = ''
    if (curArr.length > 0) {
      startDate = curArr[0]
      endDate = curArr[1]
    }
    this.state = {
      startDate,
      endDate,
    }
  }

  onDateChange = (str, e) => {
    if (str === 'startDate') {
      this.setState({
        endDate: '',
        [str]: e.detail.value
      })
    } else {
      this.setState({
        [str]: e.detail.value
      }, () => {
        const { bc } = this.props
        const { startDate, endDate} = this.state
        bc([startDate, endDate])
      })
    }
  }

  componentDidUpdate (prevProps, prevState) {
    const { curArr } = this.props
    if (prevProps.curArr !== curArr) {
      let startDate = ''
      let endDate = ''
      if (curArr.length > 0) {
        startDate = curArr[0]
        endDate = curArr[1]
      }
      this.setState({
        startDate,
        endDate,
      })
    }
  }

  render () {
    const iconDate = require('@img/icon_date.png')
    const { startDate, endDate } = this.state
    let endCurMax = ''
    const { endMax  } = this.props
    let { startLabel = '开始时间', endLabel = '结束时间'  } = this.props
    if (endMax && endMax.length > 0) {
      endCurMax = endMax
    } else {
      if (startDate) {
        let start = new Date(startDate)
        const end = new Date(start.setTime(start.getTime() + 3600 * 1000 * 24 * 31))
        endCurMax = comGetTime(end)
      }
    }
    const { isFull } = this.props
    return (
      <View className={isFull ? 'l-select-date full' : 'l-select-date'}>
        <View className="lsd-date">
          <Image className="icon" src={iconDate}></Image>
          <Picker mode='date' value={startDate} onChange={this.onDateChange.bind(this, 'startDate')}>
            {
              startDate
              ?
              <View className='val'>{startDate}</View>
              :
              <View className='val un'>{startLabel}</View>
            }
          </Picker>
        </View>
        <View className="lsd-date">
          <Image className="icon" src={iconDate}></Image>
          <Picker mode='date' value={endDate} onChange={this.onDateChange.bind(this, 'endDate')} start={startDate} end={endCurMax}>
            {
              endDate
              ?
              <View className='val'>{endDate}</View>
              :
              <View className='val un'>{endLabel}</View>
            }
          </Picker>
        </View>
      </View>
    )
  }
}