import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Menu, Input , Spin, Pagination , Popover, Affix, } from 'antd';
import '../css/index.scss'
import './list.css';
import './Index.scss';
import ListItem from './IndexItem'
import axios from 'axios';
import img_new from '../Images/new.png';
import img_array from '../Images/array.png';
import banner from '../Images/banner_list.png';
const Search = Input.Search;

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      projectsList: undefined,
      page: 1,
      limit: 15,
      search: undefined,
      sort: undefined,
      total: 0,
      isSpin: true,
      category_id: undefined,

      typeList: undefined,
      categoryList: undefined,
      recommendList:undefined,

      languageList:undefined,
      languageId:undefined
    }

  }

  componentDidMount = () => {
    const { page,search, sort,category_id , languageId } = this.state;
    this.getListData(page,search, sort,category_id , languageId);

    this.getType();

    this.getCategory();

    this.getRecommand();

    this.getLanguage();
  }

  // 获取语言列表
  getLanguage=()=>{
    const url = '/project_languages.json';
    axios.get(url).then(result=>{
      if(result){
        this.setState({
          languageList:result.data.project_languages
        })
      }
    }).catch(error=>{})
  }
  // 获取推荐列表
  getRecommand=()=>{
    const url = `/projects/recommend.json`;
    axios.get(url).then(result=>{
      if(result){
        this.setState({
          recommendList:result.data
        })
      }
    }).catch(error=>{})
  }

  // 获取列表
  getListData = (page,search, sort,category_id,language_id) => {
    const { current_user } = this.props;
    const url = `/projects.json`;
    if(category_id==0){
      category_id=undefined;
    }
    if(language_id==0){
      language_id=undefined;
    }
    axios.get(url, {
      params: {
        user_id: current_user && current_user.user_id,
        page,
        limit:15,
        search,
        sort_by: sort,
        category_id,
        language_id
      }
    }).then((result) => {
      if (result) {
        this.setState({
          projectsList: result.data.projects,
          total: result.data.total_count,
          isSpin: false
        })
      }
    }).catch((error) => { })
  }

  // 获取类型
  getType = () => {
    const url = `/projects/group_type_list.json`;
    axios.get(url).then((result) => {
      if (result && result.data) {
        result.data.unshift({
          name:'全部语言',
          id:0,
        });
        this.setTypeList(result.data, 0)
      }
    }).catch((error) => { })
  }

  setTypeList = (list, active_type) => {
    this.setState({
      typeList: list.map((item, key) => {
        return (
          <li key={key} className={ parseInt(active_type) === item.id ? 'active' : ''} onClick={() => this.changeType(`${item.id}`, list)}>
            <p>
              <span className="font-16">{item.name}</span>
              <span className="color-blue">{item.projects_count}</span>
            </p>
          </li>
        )
      })
    })
  }

  // 切换语言类型
  changeType = (id, list) => {
    this.setState({
      isSpin: true,
      languageId: id,
      search: undefined
    })
    this.setTypeList(list, id);
    const { page,sort, category_id} = this.state;
    this.getListData(page,undefined, sort,category_id , id);
  }

  // 获取类型
  getCategory = () => {
    const url = `/project_categories/group_list.json`;

    axios.get(url).then((result) => {
      if (result && result.data) {
        result.data.unshift({
          name:'全部类别',
          id:0,
        });
        this.setCategoryList(result.data, 0);
      }
    }).catch((error) => { })
  }

  setCategoryList = (list, active_id) => {
    this.setState({
      categoryList: list.map((item, key) => {
        return (
          <li key={key} className={ parseInt(active_id) === item.id ? 'active' : ''} onClick={() => this.changeCategory(`${item.id}`, list)}>
            <p>
              <span className="font-16">{item.name}</span>
              <span className="color-blue">{item.projects_count}</span>
            </p>
          </li>
        )
      })
    })
  }

  changeCategory = (id, list) => {
    this.setState({
      category_id: id,
      page: 1
    });
    this.setCategoryList(list, id)
    const { sort,languageId } = this.state;
    this.getListData(1,undefined, sort,id , languageId);
  }

  // 排序
  ChangeSoryBy = (e) => {
    this.setState({
      sort_by: e.key,
      page: 1,
      search: undefined,
      isSpin: true
    })
    const {category_id , languageId } = this.state;
    this.getListData(1,undefined, e.key,category_id , languageId);
  }

  // 搜索
  searchFun = (value) => {
    this.setState({
      page: 1,
      search: value,
      isSpin: true,
      project_type: undefined,
      sort: "updated_on"
    })
    const {sort, category_id , languageId } = this.state;
    this.getListData(1,value, sort,category_id , languageId);
  }
  changeSearchValue = (e) => {
    this.setState({
      search: e.target.value
    })
  }
  // 翻页
  ChangePage = (page) => {
    this.setState({
      page
    })
    const {search, sort,category_id , languageId } = this.state;
    this.getListData(page,search, sort, category_id , languageId);
  }

  getoDetail=(login,identifier)=>{
    this.props.history.push(`/projects/${login}/${identifier}`);
  }


  menu =()=> { 
    return(
      <Menu onClick={this.ChangeSoryBy}>
        <Menu.Item key="updated_on">更新时间排序</Menu.Item>
        <Menu.Item key="created_on">创建时间排序</Menu.Item>
        <Menu.Item key="forked_count">fork数据排序</Menu.Item>
        <Menu.Item key="praises_count">点赞数量排序</Menu.Item>
      </Menu>
    )
  }

  newItem = ()=>{
    return(
      <Menu>
        <Menu.Item key="created_mirror"><Link to={`/projects/mirror/new`}>新建镜像项目</Link></Menu.Item>
        <Menu.Item key="created_deposit"><Link to={`/projects/deposit/new`}>新建托管项目</Link></Menu.Item>
      </Menu>
    )
  }

  pagination=(total,limit,page)=>{
    return(
      total && total > limit ?
      <div className="edu-txt-center pt30 mb30 border-top-grey">
        <Pagination simple defaultCurrent={page} total={total} pageSize={limit} onChange={this.ChangePage}></Pagination>
      </div>:""
    )
  }

  render() {
    const { current_user } = this.props;

    const { projectsList , isSpin , total , search , limit , page , typeList , categoryList } = this.state;

    return (
      <div>
        <p className="t_project_banner">
          <img src={banner} width="100%" alt=""/>
        </p>
        {/* {
          recommendList && recommendList.length>0 &&
          <div className="recommandProjects">
            {
              recommendList.map((item,key)=>{
                return(
                  <div onClick={()=>this.getoDetail(item.author && item.author.login,item.identifier)}>
                    <div className="mainInfo">
                      <img src={getUrl(`/images/${item.author && item.author.image_url}`)} alt=""/>
                      <p className="school">{item.name}</p>
                      <p className="name">{item.author && item.author.name}</p>
                    </div>
                    <div className="baseInfo">
                      <span className="look"><i className="iconfont icon-dianjiliang font-12"></i>{item.visits}</span>
                      <span className="type">{item.category && item.category.name}</span>
                    </div>
                  </div>
                )
              })
            }
          </div>
        }
         */}
        <div className="ProjectListIndex">

         <Affix className="affix-list-left" offsetTop={90}>
          <div className="affix-list-content">
            <ul className="list-l-Menu">
              <li className="MenuTitle" onClick={() => {this.getType();this.changeType(undefined, this.state.typeList);}}>
                <span><i className="iconfont icon-bianchengyuyan color-grey-9 font-15 mr5"></i>
                语言</span></li>
              <div className="list-affix">{typeList}</div>
            </ul>
            <ul className="list-l-Menu">
              <li className="MenuTitle" onClick={() => {this.getCategory();this.changeCategory(undefined, this.state.categoryList);}}>
              <span><i className="iconfont icon-xiangmuleibie color-grey-9 font-15 mr5"></i>项目类别</span></li>
              <div className="list-affix">{categoryList}</div>
            </ul>
          </div>
          </Affix>

          <div className="list-right boxShandow radius-2" style={{padding:0}}>
            <Spin spinning={isSpin}>
              <div className="list-r-operation">
                <div>
                  <Search
                    placeholder="输入项目名称关键字进行搜索"
                    enterButton="搜索"
                    size="large"
                    onSearch={this.searchFun}
                    className="list-r-Search"
                    value={search}
                    onChange={this.changeSearchValue}
                  />
                </div>
                <div>
                  {
                    current_user && current_user.login &&
                    <Popover content={this.newItem()} trigger={["click"]} placement='bottom' className="mr50">
                      <a className="ant-dropdown-link">
                        <span className="color-blue font-16"><img src={img_new} alt="" width="13px" /> 新建</span>
                      </a>
                    </Popover>
                  }

                  <Popover content={this.menu()} trigger={['click']} placement='bottom'>
                    <a className="ant-dropdown-link">
                      <span className="color-blue font-16">排序 <img src={img_array} alt="" width="10px" /></span>
                    </a>
                  </Popover>
                </div>
              </div>
              <ListItem {...this.props} {...this.state} projects={projectsList} getListData={this.getListData}></ListItem>
              {this.pagination(total,limit,page)}
            </Spin>
          </div>
        </div>
      </div>
    )
  }
}
export default Index;
