import Taro, { Component } from '@tarojs/taro'
import { View, Swiper, SwiperItem, Image } from '@tarojs/components'
import { queryNewsList } from '@services/news'
import dayjs from 'dayjs'

export default class SwiperBanner extends Component {
  static options = {
    addGlobalClass: true,
  };

  state = {
    lastCity: undefined,
    list: [],
    current: 0,
  }

  timer = null;

  componentWillReceiveProps(nextProps) {

    // if (nextProps.cityId != this.state.lastCity) {
    const payload = {
      pageNumber: 1,
      pageSize: 999,
      cityId: nextProps.cityId,
    }

    queryNewsList(payload).then(res => {
      if (JSON.stringify(this.state.list) !== JSON.stringify(res.records || [])) {

        this.setState({
          list: res.records || [],
          lastCity: nextProps.cityId,
          current: 0,
        }, () => {
          this.props.showNesBox(!!(res.records || []).length)

          if (this.state.list.length > 1) {
            this.clearTimer()
            this.timer = setInterval(() => {
              let current = this.state.current + 1
              if (current >= this.state.list.length) {
                current = 0
              }

              this.setState({ current })
            }, 3000)
          }
        })
      }
    })
    // }
  }

  clearTimer = () => {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }

  componentWillUnmount() {
    this.clearTimer()
  }

  render() {
    if (!this.state.list.length) return null;

    return (
      <View className="notice-box" >
        <View style="display: flex;align-items: center;">
          <View className="left-text">
            <View className="up"> 地产</View >
            <View className="down"> 头条</View >
          </View >
          <Swiper
            className='notice-swiper'
            circular
            vertical="true"
            current={this.state.current}
          >
            {
              this.state.list.map((item, inx) => {
                return (
                  <SwiperItem key={`news-${inx}`}>
                    <View className="notice-text" onClick={() => this.props.onClick(item)}>
                      <View className="date"><View className="dot"></View>{dayjs(item.createDate).format('YYYY-MM-DD')}</View>
                      {item.newsName}
                    </View>
                  </SwiperItem>
                )
              })
            }
          </Swiper>
        </View>
        {this.state.list.length > 1 &&
          <View className="notice-more" onClick={this.props.onClickMore}>
            更多 <Text className="iconfont icon-more"></Text>
          </View>
        }
      </View>
    )
  }
}
