import React, { useEffect, useState } from 'react';
import { Modal , Checkbox , Spin , Input } from 'antd';
import Axios from 'axios';
import CheckProfile from '../../Component/ProfileModal/Profile';

const { Search } = Input;
const limit = 20;
function ConcentrateBox({ visible , onCancel , onSure , username , choosed , history , showCompeleteDialog , completeProfile , current_user,checkIfLogin,showLoginDialog }) {
  const [ page , setPage ]= useState(1);
  const [ total , setTotal ]= useState(0);
  const [ pageSize , setPageSize ] = useState(false);
  const [ search , setSearch ] = useState("");

  const [ list , setList ]= useState([]);
  const [ value , setValue ]= useState([]);
  const [ isSpin , setIsSpin ]= useState(true);
  const [ disable , setDisable ] = useState(false);
  const [ loadCount , setLoadCount ] = useState(0);

  const [ copyList , setCopyList ] = useState([]);
  const [ copyAllList , setCopyAllList ] = useState([]);
  
  useEffect(()=>{
    if(visible && loadCount === 0){
      setLoadCount(loadCount+1);
      setIsSpin(true);
      getProjectList();
    }else{
      setSearch("");
      setCopyAllList([]);
      setCopyList([]);
      setList([]);
    }
  },[visible])

  useEffect(()=>{
    if(page>1){
      setIsSpin(true);
      getProjectList(page,undefined);
    }
  },[page])


  useEffect(()=>{
    if(visible && choosed && choosed.length >0 ){
      setValue(choosed);
    }
  },[visible,choosed])

  useEffect(()=>{
    if(value && value.length === 6){
      setDisable(true);
    }else{
      setDisable(false);
    }
  },[value])

  function getProjectList(p,s) {
    const url =  `/users/${username}/projects.json`;
    Axios.get(url,{
      params:{
        page:p,limit,is_public: "public",search:s,choosed
      }
    }).then(result=>{
      if(result && result.data){
        let e = !search ? mergeArrayMerge(list,result.data.projects) : result.data.projects;
        setCopyAllList(!search ? e : copyAllList);
        setTotal(result.data.count);
        setList(e);
        setIsSpin(false);
        // 查看更多需要页数
        let s = parseInt(result.data.count/limit,0);
        let y = result.data.count%limit;
        setPageSize(y>0?s+1:s);
      }
    }).catch(error=>{})
  }

  function mergeArrayMerge (array1, array2) {
    array1.map((v, index) => {
      if (v !== '') {
          let idx = array2.indexOf(v);
          if (idx > -1) {
              array2.splice(idx, 1)
          }
      }
    });
    array1 = array1.concat(array2);
    return array1
  }

  function saveList(c) {
    // 将选中的复制下来保存到copyList数组里
    if(c && c.length > 0){
      let l = []
      for(var i=0;i<c.length;i++){
        let filter = copyAllList.filter(j=>j.id === c[i]);
        if(filter && filter.length>0){
          l.push(filter[0]);
        }
      }
      setCopyList(l);
    }
  }

  function onOk() {
    onSure && onSure(value);
    setValue([]);
  }

  function chooseProject(e) {
    setValue(e);
  }

  // 搜索
  function onSearch(params) {
    if(params === search && params === ""){
      return;
    }
    setCopyAllList(list);
    value && value.length > 0 ? saveList(value) : setCopyList([]);
    setPage(1);
    setSearch(params);
    getProjectList(1,params);
  }


  return(
    <Modal 
      visible={visible}
      title={'选择精选项目'}
      closable={true}
      width={500}
      className="ConcentrateBox"
      onCancel={onCancel}
      onOk={onOk}
      okText="确定"
      cancelText="取消"
    >
      <Spin spinning={isSpin}>
        <div className="operateDiv">
          <p>最多可选取6个公开仓库</p>
          <Search 
            placeholder="请输入项目名称进行搜索" 
            onSearch={onSearch}
            enterButton="搜索"
            allowClear
            value={search}
            onChange={(e)=>setSearch(e.target.value)}
          />
        </div>
        <div className="listbox">
          <Checkbox.Group value={value} onChange={chooseProject} style={{width:"100%"}}>
            {
              copyList && copyList.length >0 && copyList.map((i,k)=>{
                return(
                  <Checkbox value={i.id} disabled={disable && (value.filter(j=>j === i.id).length===0)}>{i.author && i.author.name}/{i.name}</Checkbox>
                )
              })
            }
            {
              list && list.length > 0 && list.map((i,k)=>{
                let c = copyList && copyList.length >0 && copyList.filter(j=>j.id === i.id).length !== 0;
                return(
                  !c && <Checkbox value={i.id} disabled={disable && (value.filter(j=>j === i.id).length===0)}>{i.author && i.author.name}/{i.name}</Checkbox>
                )
              })
            }
          </Checkbox.Group>
        </div>
        { total > limit && page < pageSize && <div className="morelist" onClick={()=>setPage(page+1)}>查看更多</div> }
        { 
          (list && list.length === 0) && (copyList && copyList.length === 0) && 
          <div style={{textAlign:"center"}}>您还没有公开的{search && `“${search}”`}项目，先去
            <CheckProfile 
              checkIfLogin={checkIfLogin}
              showLoginDialog={showLoginDialog}
              current_user={current_user}
              showCompeleteDialog={showCompeleteDialog}
              completeProfile={completeProfile}
              sureFunc={()=>{history.push(`/projects/deposit/new`)}} 
              className="color-blue">新建项目</CheckProfile>
          </div> 
        }
      </Spin>
    </Modal>
  )
}
export default ConcentrateBox;