import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { AutoComplete, Pagination, List, Popconfirm, Dropdown, Spin } from 'antd';
import { WhiteBack, Blueline, FlexAJ, GroupProjectBackgroup, Greenline, Redline } from '../../../Component/layout';
import Title from '../../../Component/Title';
const { Option } = AutoComplete;
const limit = 15;
// 使用了faker数据，后续需要修改
function GroupProjectSetting(props) {
  const [isSpin, setIsSpin] = useState(false);
  const [projects, setProjects] = useState(undefined);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [repo_name, setRepoName] = useState(undefined);

  const [ search , setSearch ] = useState("");
  const [ optionsSource , setOptionsSource ] = useState(undefined);

  const { OIdentifier, groupId } = props.match.params;

  useEffect(() => {
    get_project()
  }, [page])

  function get_project() {
    setIsSpin(true);
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_projects.json`;
    axios.get(url, {
      params: {page,limit},
    })
    .then((result) => {
      if (result && result.data) {
        setProjects(result.data.team_projects)
        setTotal(result.data.total_count)
      }
    }).catch((error) => { });
    setIsSpin(false)
  }

  // 切换分页
  function ChangePage(page) {
    setPage(page);
  }

  function removeProject(identifier) {
    setIsSpin(true)
    const url = `/organizations/${OIdentifier}/teams/${groupId}/team_projects/${identifier}.json`;
    axios.delete(url)
      .then((result) => {
        if (result && result.data.status > -1) {
          setPage(1)
          get_project()
        }
      }).catch((error) => { });
    setIsSpin(false)
  }

  function removeALLProject() {
// 移除所有项目
  }

  function addALLProject() {
// 添加所有项目
  }

  // 添加单个项目
  function addSingleProject(){
    if(repo_name){
      setIsSpin(true);
      const url = `/organizations/${OIdentifier}/teams/${groupId}/team_projects.json`;
      axios.post(url, {repo_name})
      .then((result) => {
        if (result && result.data.id) {
          setPage(1)
          get_project()
        }
        setIsSpin(false)
      }).catch((error) => {setIsSpin(false)});
    }else{
      props.showNotification("请选择要添加的项目!");
    }
  }

  // 搜索项目有关
  useEffect(()=>{
      const url = `/organizations/${OIdentifier}/projects/search.json`;
      axios.get(url,{
        params:{
          search
        }
      }).then(result=>{
        if(result && result.data){
          setOptions(result.data.projects);
        }
      }).catch(error=>{})
  },[search])
  function setOptions(data){
    const s = data && data.map((item, key) => {
      return (
        <Option
          key={key}
          value={`${item.id}`}
          searchValue={`${item.name}`}
        >
          {item.name}
        </Option>
      );
    });
    setOptionsSource(s);
  }
  function changeInput(value){
    let s = value || "";
    setSearch(s);
  }
  function selectInput(value){
    setRepoName(value);
    setSearch(value);
  }

  return (
    <Spin spinning={isSpin}>
      <WhiteBack className="mb30">
        <Title>
          <FlexAJ style={{width:"100%"}}>
            <span>团队项目管理</span>
            <div>
              <AutoComplete
                style={{ width: 300 }}
                placeholder="搜索项目..."
                onChange={changeInput}
                onSelect={selectInput}
                allowClear
              >
                {optionsSource}
              </AutoComplete>
              <Blueline className="ml30" onClick={()=>addSingleProject()}>+&nbsp;添加项目</Blueline>
            </div>
          </FlexAJ>
        </Title>
      {/* <FlexAJ className="padding20-30">
          <GroupProjectBackgroup>
            <FlexAJ>
              <div>
                <Popconfirm
                  title="确认添加所有成员的项目吗？"
                  onConfirm={() => addALLProject()}
                  okText="确认"
                  cancelText="取消"
                >
                  <Greenline bold>添加所有</Greenline>
                </Popconfirm>

                <Popconfirm
                  title="确认移除所有项目吗？"
                  onConfirm={() => removeALLProject()}
                  okText="确认"
                  cancelText="取消"
                >
                  <Redline bold className="ml30">移除所有</Redline>
                </Popconfirm>
              </div> 
            </FlexAJ>
          </GroupProjectBackgroup>
        </FlexAJ>*/}
        <div className="padding20-30"style={{paddingTop:"0px",minHeight:"400px"}}>
          <List
            itemLayout="horizontal"
            dataSource={projects}
            renderItem={item => (
              <List.Item
                extra={
                  <Popconfirm
                    title="确认移除项目吗？"
                    onConfirm={() => removeProject(item.project.identifier)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <a className="color-red">移除</a>
                  </Popconfirm>
                }
              >
                <List.Item.Meta
                  title={<a href={`/${item.project.owner_login}/${item.project.identifier}`}>{item.project.owner_name}/{item.project.name}</a>}
                />
              </List.Item>
            )}
          />
        </div>
        {
          total > limit ?
          <div className="edu-txt-center mt30 mb20">
            <Pagination simple defaultCurrent={page} total={total} pageSize={limit} onChange={ChangePage}></Pagination>
          </div>
          : ""
        }
      </WhiteBack>
    </Spin>
  )
}
export default GroupProjectSetting;