import React, { Component } from 'react';
import { config, request, permission, util } from 'utils'
import ReactDOM from "react-dom"
import { connect } from 'dva';
import { SearchBar, Modal, Flex, Tabs, Badge, Carousel, Button, WhiteSpace, WingBlank, PullToRefresh, ListView } from 'antd-mobile';
import { StickyContainer, Sticky } from 'react-sticky';
import HomeCarousel from '../../components/home-tabbar/home-tabber-carousel'
import Link from 'umi/link';
import router from 'umi/router';
import styles from './index.less';

const { APIV3, WXMpAPI } = config
// localStorage.setItem("sso.token",{"expire":"2020-07-23T23:12:55.064Z","value":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHRyYSI6IntcIld4QXBwSWRzXCI6W1wid3g0ZjhjOWZlZjM4OTZhZDcxXCIsXCJ3eDRmOGM5ZmVmMzg5NmFkNzFcIl19IiwiYXBwbGljYXRpb25LZXkiOiJ3ZWNoYXRjcCIsInJvbGVLZXkiOiJhZG1pbiwiLCJpc3MiOiJjbXMiLCJvcmdLZXkiOiJudWxsIiwidXNlck5hbWUiOiJsaXpob3Vsb25nMSIsImdyYW50VHlwZSI6InBhc3N3b3JkIiwiZXhwIjoxNTk1NTA5NjQ2LCJpYXQiOjE1OTU1MDI0NDYsImRlcHRDb2RlIjoibnVsbCJ9.j5j7H8tbscls1XY61EAwukX387Z7QIfWz5jimSTRAgU"})

@connect(({ home }) => ({ home }))
class Home extends Component {
  constructor(props) {
    super(props)
    this.state = {
      columnId:  "",
      banner: [],
      icon: [],
      tab: [],
      bottomBanner: [],
      loinBannerList: [],
      cardLists: [],
      tofobanner: [],
      visible: false,
      data: ['1', '2', '3'],
      imgHeight: 70,
      slideIndex: 2,
      floorData:[],
      classData:[],
      sliceData:[],
      departmentlist:[],
      depmentId:"",
      classId:"",
      searchText:"",
      wenzhangData:[],
    }
  }

  renderTabBar = () => {
    return (<Sticky>
      {({ style }) => <div style={{ ...style, zIndex: 1 }}><Tabs.DefaultTabBar {...props} /></div>}
    </Sticky>);
  }
  componentDidMount() {
    const columnId= window.location.search.split("=")[1]
    this.setState({
      columnId:columnId
    },()=>{
    this.requestsliceItem()
    this.requestDepartmentsData()
    this.requestFloorData()
    this.requestClassData()
    this.requestWenzhanData(true)
    })
  }
  getUrlToken=(name, str)=> {
    const reg = new RegExp(`(^|&)${ name}=([^&]*)(&|$)`);
    const r = str.substr(1).match(reg);
    if (r != null) return  decodeURIComponent(r[2]); return null;
}
  componentDidUpdate() {
    // After the new child element is rendered, change the slideIndex
    // https://github.com/FormidableLabs/nuka-carousel/issues/327
    if (this.state.slideIndex !== this.state.data.length - 1) {
      /* eslint react/no-did-update-set-state: 0 */
      this.setState({ slideIndex: this.state.data.length - 1 });
    }

  }
  componentWillMount(props){
    // // this.getUrlToken("columnId",)
  }
//获取轮播数据
requestsliceItem=()=>{
  let self = this
  let listlist ={
    "filters":[
    {
    "field":"rotation_graph_column_id",
    "operate":"equal",
    "value":this.state.columnId
    }
    ],
    }
      request({
          url: WXMpAPI + '/wx/content/rotationGraph/queryAllRotationGraphs',
          method: "post",
          data: listlist
      }).then(function (getListRes) {
          if (getListRes.success == 1) {
            self .setState({
              sliceData:getListRes.items
            })
          }
      });

}
//获取科室
requestDepartmentsData=()=>{
  let self = this
  let list ={
        "pageIndex":1,
        "pageSize":10,
        "filters": [
            {
                "field": "column_id",
                "operate": "equal",
                "value": this.state.columnId
            }
        ],
    //     "sortDirection": 0,
    //     "sortField": "排序列名"
    }
      request({
          url: WXMpAPI + '/wx/content/department/queryDepartmentsByColumnId',
          method: "post",
          data: list
      }).then(function (getListRes) {
          if (getListRes.success == 1) {
            self.setState({
              departmentlist:getListRes.items
            })
          }
          console.log(getListRes.items);
      });
}
//获取楼层
requestFloorData=()=>{

  let self = this
  let list ={
        "pageIndex":1,
        "pageSize":10,
        "filters": [
            {
                "field": "floor_column_id",
                "operate": "equal",
                "value": this.state.columnId
            }
    ],
    }
      request({
          url: WXMpAPI + '/wx/content/floor/queryFloorsFornt',
          method: "post",
          data: list
      }).then(function (getListRes) {
          if (getListRes.success == 1) {
            self.setState({
              floorData:getListRes.items
            })
          }
          console.log(getListRes.items);
      });

}
//获取分类数据
requestClassData=()=>{
  let self= this ;
  let {columnId} = this.state
  let list = {
    "pageIndex":1,
    "pageSize":10,
    "filters":[
    {
    "field":"classification_column_id",
    "operate":"equal",
    "value":columnId
    }
    ],
    }
  request({
      url: WXMpAPI + '/wx/content/classification/queryAllClassificationsFront',
      method: "post",
      data: list
  }).then(function (getListRes) {
      if (getListRes.success == 1) {
        self.setState({
          classData:getListRes.items
        })

      }
      console.log(getListRes);
  });

}
 //查询文章
 requestWenzhanData=(start,reqClass)=>{
   let self = this
   let list
  //  let {classId,depmentId,searchText} = this.state
   if(reqClass){
        list = {
              "pageIndex":1,
              "pageSize":10,
              "filters":[
                     {
                "field":"classification_column_id",
                "operate":"contains",
                "value":reqClass
                    },
        ],
     }
   }else if(start){
        list ={
             "pageIndex":1,
              "pageSize":10,

      }
   }
      request({
          url: WXMpAPI + '/wx/content/article/queryArticlesFront',
          method: "post",
          data: list
      }).then(function (getListRes) {
          if (getListRes.success == 1) {
            self.setState({
              wenzhangData:getListRes.items
            })
      
          }
      });
      console.log(this.state.wenzhangData);
 }
 //切换分类
changeSlice=(tab,index)=>{
  var classid = this.state.classData[index].classificationColumnId
  this.requestWenzhanData(false,classid);
}
  render() {
    const { home } = this.props;
    let self = this
    const tabs = []
    this.state.classData.map((val)=>{
    return tabs.push({title: <Badge >{val.classificationName}</Badge> })
    })
    // const tabs = [
    //   { title: <Badge >推荐</Badge> },
    //   { title: <Badge >健康饮食</Badge> },
    //   { title: <Badge>两性健康</Badge> },
    //   { title: <Badge>孕产育儿</Badge> },
    // ];
    return (
      <div className='homePage'>
        <div className='homePage_search'>
          <div className='homePage_input'>
            <SearchBar
              placeholder="搜索你想要的商品"
              ref={ref => this.manualFocusInst = ref}
              onFocus={() => router.push({pathname:'/searchText',query:{columnId:self.state.columnId}})}
            />
          </div>
        </div>
        <div className="home_swiper">
          <WingBlank>
            {/* <Button
              onClick={() => {
                this.setState({
                  data: this.state.data.concat('AiyWuByWklrrUDlFignR'),
                });
              }}
            >Click me to add child</Button> */}

            <Carousel
              autoplay={true}
              infinite
              selectedIndex={this.state.slideIndex}
              // beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
              // afterChange={index => console.log('slide to', index)}
            >
              {this.state.sliceData.map((val, index) => (
                <a
                  key={val + index}
    
                  style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                >
                  <img
                    src={val.rotationGraphAddress}
                    alt=""
                    style={{ width: '100%', verticalAlign: 'top', height: '100%' }}
                    onLoad={() => {
                      this.setState({ imgHeight: '30' });
                    }}
                  />
                </a>
              ))}
            </Carousel>
          </WingBlank>
        </div>
        <div className='stepBlock'>
          {/* <div className='stepBlocktitle'>四步变现</div> */}
          {/* <img className='stepBlockimg' onClick={() => router.push('/class')} src={require('../../assets/recycleH5_01.png')} alt="" /> */}
          {/* <Router ></Router> */}

          {
            self.state.departmentlist==null?[]:self.state.departmentlist.map((item,index)=>{
              return (
                 <div className="stepitem">
                  {
                    item.departmentIconaddress==""?<div></div>:<img src={item.departmentIconaddress}/>
                  }
                  <span>{item.departmentName}</span>
                </div>
              )
            })
          }
          <div className="stepitem">
                  <div></div>
                  <span>更多</span>
           </div>

        </div>
        <div className='hotMobileBlock'>
        </div>
          {
            self.state.floorData==null?[]:self.state.floorData.map((item,index)=>{
                return (
                  <div className='itemList itemList2'>
                      <div className='itemListtitle'>{item.floorName}<div className='gotoMore' onClick={() =>router.push({pathname:'/class',query:{columnId:self.state.columnId}})}>查看更多<img src="https://res.zudeapp.com/wximage/right_arrow.png" alt="" /></div></div>
                          <div className='hotlist'>
                         {
                     item.floorItemList && item.floorItemList.length !== 0 ? item.floorItemList.map((val) => (
                      <div className='itemBlock' key={val.id} onClick={() => { console.log('去商品') }}>
                        <div className='product_img'>
                    <img className='img' src={val.flooritemPhotoaddress} />
                  </div>
                  <span className='text_ellipsis'>{val.flooritemTitle}</span>
                </div>
              ))
                : ""
            }
          </div>
        </div> 
                )
            })
          }
        <div className="lastpart">
          <Tabs tabs={tabs}
            initialPage={0}
            onChange={(tab, index) => { this.changeSlice(tab,index)}}
            onTabClick={(tab, index) => { console.log('onTabClick', index, tab); }}
          >
          </Tabs>

          {
             this.state.classData.length<=0?[]:this.state.wenzhangData.length<=0?[]:this.state.wenzhangData.map((item,index)=>{
                  return (
                  <div className="shopitem" style={{ width:" 100%",height: "1.58rem",display: "flex",flexflow:" row nowrap",justifyContent: "space-around",alignItems:" center",margin: ".25rem 0",}}>
                      <img src={item.articlePhotoaddress} style={{width: "1.84rem",height:" 1.41rem"}}/>
                    <div className="shoptitle" style={{ width: "70%",height:" 100%"}}>
                      <p className="shopname"style={{
                      fontSize: ".3rem",
                      textAlign: "left",
                      color: "#333",
                      textOverflow:" ellipsis",
                      wordBreak: "break-all",
                      display: "-webkit-box",
                      webkitlineClamp: "2",
                      MozBoxOrient: "vertical",
                      overflow:"hidden",
                      height: "0.86rem",
                    }}>{item.articleTitle}</p>
                    <p className="shopintroduce"style={{

                      fontSize: ".28rem",
                      textAlign: "left",
                      color: "#666",
                      textOverflow:" ellipsis",
                      wordBreak: "break-all",
                      display: "-webkit-box",
                      webkitlineClamp: "2",
                      MozBoxOrient: "vertical",
                      overflow:"hidden",
                      height: "0.86rem",
                    }}>{item.articleSummary}</p>
                    </div>
              </div>
              )
                
           
            
               
             })
          }
        </div>


      </div>
    )
  }
}
export default Home;
