import React, { Component } from 'react';
import { Menu, Input , Spin, Pagination , Popover , Select } from 'antd';
import Slider from "react-slick";
import { getImageUrl } from 'educoder';
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import '../css/index.scss'
import './list.scss';
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.png';
import CheckProfile from '../Component/ProfileModal/Profile';
import AddProjectModal from '../Head/AddProjectModal';

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,
      project_type: undefined,
      category_id: undefined,

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

      recommendOriList:undefined,

      languageList:undefined,
      languageId:undefined,

      CategoryList:undefined

    }

  }

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

    this.getType();

    this.getCategory();

    // this.getRecommand();

    this.getLanguage();

    // this.getRecommandOri();
  }

  // 获取语言列表
  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=>{})
  }

  getRecommandOri=()=>{
    const url = `/organizations/recommend.json`;
    axios.get(url).then(result=>{
      if(result){
        this.setState({
          recommendOriList:result.data.organizations
        })
      }
    }).catch(error=>{})
  }

  // 获取列表
  getListData = (page, limit, search, sort, project_type, category_id,languageId) => {
    const { current_user } = this.props;
    const url = `/projects.json`;
    axios.get(url, {
      params: {
        user_id: current_user && current_user.user_id,
        page,
        limit,
        search,
        sort_by: sort,
        project_type,
        category_id,
        language_id:languageId
      }
    }).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) {
        this.setTypeList(result.data, undefined)
      }
    }).catch((error) => { })
  }

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

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

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

    axios.get(url).then((result) => {
      if (result && result.data) {
        
        this.setCategoryList(result.data, undefined);
      }
    }).catch((error) => { })
  }

  setCategoryList = (list) => {
    this.setState({
      CategoryList: list
    })
  }

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

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

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

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

  // 选择语言类别
  changeLanguage=(e)=>{
    this.setState({
      isSpin:true,
      languageId:e === 0 ?undefined:e
    })
    const { page, limit, sort , project_type , category_id } = this.state;
    this.getListData(page, limit, undefined, sort, project_type, category_id ,e === 0 ?undefined:e);
  }

  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(
      <ul>
        <li>
          <CheckProfile {...this.props} sureFunc={()=>{this.props.history.push('/projects/deposit/new')}}>新建项目</CheckProfile>
        </li>
        <li>
          <CheckProfile {...this.props} sureFunc={()=>{this.props.history.push('/projects/mirror/new')}}>导入项目</CheckProfile>
        </li>
      </ul>
    )
  }

  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 , mygetHelmetapi } = this.props;
    const { projectsList , recommendList , languageList , languageId , 
      isSpin, total, search, limit, page, typeList, categoryList , 
      recommendOriList , CategoryList , category_id } = this.state;

      const setting={
        dots: true,
        infinite: true,
        speed: 500,
        slidesToShow: 5,
        slidesToScroll: 5,
        autoplay:false,
        arrows:false,
        adaptiveHeight:true
      }
    return (
      <div>
        <div class="subjectBanner">
          <img src={banner} width="100%" height="100%" alt=""/>
          <div class="bannerBox">
            <div class="subjectleft">
              <span>{mygetHelmetapi && mygetHelmetapi.banner && mygetHelmetapi.banner.title}</span>
              <span>
                <span>
                  <span class="words">{mygetHelmetapi && mygetHelmetapi.banner && mygetHelmetapi.banner.sub_title}</span>
                  <p class="font-13" style={{color: "rgb(204, 204, 204)"}}>{mygetHelmetapi && mygetHelmetapi.banner && mygetHelmetapi.banner.content}</p>
                </span>
              </span>
            </div>
            <CheckProfile {...this.props} sureFunc={()=>this.props.history.push("/projects/deposit/new")}>
              <i class="iconfont icon-xinjianxiangmu"></i>新建项目
            </CheckProfile>
            <a>
              <i class="iconfont icon-jiaruketang1"></i>
              <AddProjectModal {...this.props} showNotification={this.props.showNotification}/>
            </a>
            <a href="https://data.educoder.net/api/attachments/1955244?disposition=inline" target="_blank">
              <i class="iconfont icon-xinshouzhiyin"></i>新手指引
            </a>
          </div>
        </div>
        {
          recommendList && recommendList.length>0 &&
          <Slider {...setting} className={recommendList.length>5 ? "recommandProjects":"recommandProjects mb20"}>
            {
              recommendList.map((item,key)=>{
                return(
                  <div className="items" onClick={()=>this.getoDetail(item.author && item.author.login,item.identifier)}>
                    <div className="mainInfo">
                      <img src={getImageUrl(`/${item.author && item.author.image_url}`)} width="50px" height="50px"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>
                )
              })
            }
          </Slider>
        }
        <div className="ProjectListIndex">
          <div className="list-left">
            <ul className="list-l-Menu">
              <li className="MenuTitle"><i className="iconfont icson-xiangmuleixing color-grey-9 font-15 mr5"></i>项目类型</li>
              {typeList}
            </ul>
            <ul className="list-l-Menu">
              <li className="MenuTitle"><i className="iconfont icon-xiangmuleibie color-grey-9 font-15 mr5"></i>项目类别</li>
              {
                CategoryList && CategoryList.length > 0 ? CategoryList.map((item,key)=>{
                  return(
                    <li key={key} className={category_id && parseInt(category_id) === item.id ? 'active' : ''} onClick={() => this.changeCategory(`${item.id}`)}>
                      <p>
                        <span className="font-16">{item.name}</span>
                        <span className="color-blue">{item.projects_count}</span>
                      </p>
                    </li>
                  )
                })
                :""
              }
            </ul>
          </div>
          <div className="list-right boxShandow radius-2" style={{padding:0}}>
            <Spin spinning={isSpin}>
              <div className="list-r-operation">
                <div>
                  <Select 
                    showSearch
                    placeholder="请选择语言"
                    style={{width:"150px",marginRight:"20px"}}
                    size={"large"}
                    onChange={this.changeLanguage}
                    value={languageId}
                    allowClear={true}
                    optionFilterProp="children"
                    filterOption={(input,option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  >
                    <Select.Option key={0} value={0}>请选择语言</Select.Option>
                    {
                      languageList && languageList.length>0 && languageList.map((item,key)=>{
                        return(
                          <Select.Option key={item.id} value={item.id}>
                            {item.name}
                          </Select.Option>
                        )
                      })
                    }
                  </Select>
                  <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
                      overlayClassName="newPopUl" 
                      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}></ListItem>
              {this.pagination(total,limit,page)}
            </Spin>
          </div>
        </div>
      </div>
    )
  }
}
export default Index;
