import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { AutoComplete, Pagination, Popconfirm, Spin, Table, message, Tooltip } from 'antd';
import { WhiteBack, Blueline, FlexAJ, Redback, Blueback } 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;
  const { includesAllProject} = props;

  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() {
    setIsSpin(true);
    axios.delete(`/organizations/${OIdentifier}/teams/${groupId}/team_projects/destroy_all.json`).then((result) => {
      if (result && !result.data.status) {
        message.success('移除成功');
        get_project();
      }
      setIsSpin(false);
    }).catch((error) => {setIsSpin(false)});
  }

  // 添加所有项目
  function addALLProject() {
    setIsSpin(true);
    axios.post(`/organizations/${OIdentifier}/teams/${groupId}/team_projects/create_all.json`).then((result) => {
      console.log('result', result);
      if (result && !result.data.status) {
        message.success('添加成功');
        get_project();
      }
      setIsSpin(false);
    }).catch((error) => {setIsSpin(false)});
  }

  // 添加单个项目
  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);
  }

  const columns = [
    {
      title: '项目名称',
      dataIndex: 'project',
      width: "85%",
      render: (value, item) => {
        return (
          <a href={`/${value.owner_login}/${value.identifier}`}>{value.owner_name}/{value.name}</a>
        )
      }
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (value, item) => {
        return includesAllProject ? <Tooltip title={"该团队拥有所有项目权限，不支持移除，可在基本设置中进行调整。"}><span style={{color: 'gray'}}>移除</span></Tooltip> : <Popconfirm
          title="确认移除项目吗？"
          onConfirm={() => removeProject(item.project.identifier)}
          okText="确认"
          cancelText="取消"
        >
          <a className="color-red">移除</a>
        </Popconfirm>
      }
    }
  ]

  return (
    <Spin spinning={isSpin}>
      <WhiteBack className="mb30">
        <Title>
          <span>团队项目管理</span>
        </Title>
        <FlexAJ style={{width:"100%"}}>
          <div className="padding20-30">
            <AutoComplete
              style={{ width: 300 }}
              placeholder="搜索项目..."
              onChange={changeInput}
              onSelect={selectInput}
              allowClear
            >
              {optionsSource}
            </AutoComplete>
            <Blueline className="ml30" onClick={()=>addSingleProject()}>+&nbsp;添加项目</Blueline>
          </div>
          {!includesAllProject && <div className='pr30'>
            <Popconfirm
              title="确认添加组织内所有项目至该团队？"
              onConfirm={() => addALLProject()}
              okText="确认"
              cancelText="取消"
            >
              <Blueback className="mr30">添加所有</Blueback>
            </Popconfirm>
            <Popconfirm
              title="确认移除该团队内所有项目？"
              onConfirm={() => removeALLProject()}
              okText="确认"
              cancelText="取消"
            >
              <Redback>移除所有</Redback>
            </Popconfirm>
          </div>}
        </FlexAJ>
        <div className="padding20-30"style={{paddingTop:"0px",minHeight:"400px"}}>
          <Table
            size="small"
            columns={columns}
            dataSource={projects}
            pagination={false}
            className="teamMemberTable"
          ></Table>
        </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;