import React , { useRef , useState , useEffect } from 'react';
import { Menu, Input , Checkbox , Pagination, Button , Tooltip ,Spin  } from 'antd';
import { Link } from "react-router-dom";
import AllMenus from './component/allMenus';
import Datas from '../Issues/Component/datas';
import axios from 'axios';
import { FlexAJ } from '../Component/layout';
import CheckProfile from '../Component/ProfileModal/Profile';
import emp from '../../forge/Issues/Img/emp.png';
import './milepost.scss';
import './order.scss';
import '../Issues/index.scss';

function MilepostDetail(props){
  const [ milepost, setMilepost] = useState(undefined);
  const [ issueList , setIssueList ] = useState(undefined);
  const [ closedCount , setClosedCount ] = useState(0);
  const [ openedCount , setOpenedCount ] = useState(0);

  const[ aboutMe , setAboutMe ] = useState("aboutme");
  const[ keyword , setKeyword ] = useState(undefined);

  const [ category , setCategory] = useState("opened");

  const [ allValue , setAllValue ] = useState([]);
  const [ allIds , setAllIds ] = useState([]);
  const [ checkAll , setCheckAll ] = useState(false);

  const [ updateIds , setUpdateIds ] = useState([]);
  const [ limit, setLimit] = useState(10);
  const [ page , setPage ] = useState(1);
  const [ total , setTotal ] = useState(undefined);
  const [ issuesCount, setIssueCount] = useState(undefined);

  const menuRef = useRef(null);
  const { projectsId, mileId , owner } = props.match.params;
  const {current_user, projectDetail, showLoginDialog, history} = props;
  const permission = props && props.projectDetail && props.projectDetail.permission;
  // 排序字段
  const sortBy = {
    '1': {'sort_by': 'issues.created_on', 'sort_direction': 'desc'},
    '2': {'sort_by': 'issues.created_on', 'sort_direction': 'asc'},
    '3': {'sort_by': 'issues.updated_on', 'sort_direction': 'desc'},
    '4': {'sort_by': 'issues.updated_on', 'sort_direction': 'asc'},
    '5': {'sort_by': 'issue_priorities.position', 'sort_direction': 'desc'},
    '6': {'sort_by': 'issue_priorities.position', 'sort_direction': 'asc'}
  }

  useEffect(()=>{
    Init();
  },[aboutMe, keyword, category, page, limit])

  useEffect(()=>{
    updateDocumentTitle()
  }, [projectDetail, milepost])

  // 更新网页标题
  function updateDocumentTitle(){
    if(projectDetail && milepost){
      const { author, name} = projectDetail;
      document.title = `${milepost.name}-里程碑-${author.name}/${name}`;
    }
  }

  // 获取issue列表数据
  function Init(params){
    const url = `/v1/${owner}/${projectsId}/milestones/${mileId}.json`;
    axios.get(url,{
      params:{
        page,
        limit,
        category,
        ...params
      }
    }).then(result=>{
      if(result){
        const {milestone, issues, total_count, closed_issues_count, opened_issues_count, total_issues_count} = result.data;
        if(issues.length === 0 && page>1){
          setPage(page-1);
          return;
        }
        setMilepost(milestone);
        setIssueList(issues);
        setTotal(total_count);
        setClosedCount(closed_issues_count);
        setOpenedCount(opened_issues_count);
        setIssueCount(total_issues_count)
        const ids = issues.length>0 ? issues.map(i=>{return i.id}) : [];
        setAllIds(ids);
      }
    }).then(error=>{console.log("error:",error)})
  }

  // 第一个下拉搜索
  const menu = (
    <Menu selectedKeys={[`${aboutMe}`]} onClick={chooseAboutMe}>
      <Menu.Item key={"all"}>全部</Menu.Item>
      <Menu.Item key={"aboutme"}><Tooltip title="指我创建的、我负责的和@我的疑修">与我相关</Tooltip></Menu.Item>
      <Menu.Item key={"assignedme"}>我负责的</Menu.Item>
      <Menu.Item key={"authoredme"}>我创建的</Menu.Item>
      <Menu.Item key={"atme"}>@我的</Menu.Item>
    </Menu>
  )
  function chooseAboutMe(e){
    setCategory("all");
    setAboutMe(e.key);
  }

  // 全选所有issue
  function chooseAll(e){
    setCheckAll(e.target.checked);
    if(e.target.checked){
      setAllValue(allIds);
    }else{
      setAllValue([]);
    }
  }

  // 选择列表里的issue
  function checkIssues(value){
    setAllValue(value);
    if(value.length === allIds.length){
      setCheckAll(true);
    }else{
      setCheckAll(false);
    }
  }

  // 取消
  function cancelUpdate(){
    setAllValue([]);
    setCheckAll(false);
    // 清除下拉选项
    menuRef.current && menuRef.current.clearChoose();
  }

  // 确认修改 allValue updateIds
  function sureUpdate(){
    const url =  `/v1/${owner}/${projectsId}/issues/batch_update`;
    axios.patch(url,{
      assigner_ids: updateIds && updateIds.assigner_id && updateIds.assigner_id.split(","),
      ids: allValue,
      issue_tag_ids:  updateIds && updateIds.issue_tag_ids && updateIds.issue_tag_ids.split(","),
      milestone_id: updateIds && updateIds.milestone_id,
    }).then(result=>{
      if(result){
        setUpdateIds(undefined);
        setAllValue([]);
        setTotal(undefined);
        Init();
        cancelUpdate();
      }
    }).catch(error=>{})
  }

  // 切换页码
  function changepage(page){
    setPage(page);
  }

  function chooseFunc(ids){
    if(allValue && allValue.length>0){
      // 将ids保存下来以便修改
      setUpdateIds(ids);
    }else{
      const {sort_by} = ids;
      const params = {...ids, ...sortBy[sort_by]}
      Init(params);
    }
  }

  return(
    <div className="main milepostDetail">
      {milepost && <FlexAJ>
        <div>
          <p className="font-17 font-bd color-black" style={{width: '900px'}}>{milepost.name}</p>
          <p className="mt7">
            <span className="mr20">
              <i className="iconfont icon-a-31shijian font-14 mr5 color-grey-89"></i>
              <span className="color-grey-89">{milepost.effective_date || '暂无截止时间'}</span>
            </span>
            {(milepost.percent || milepost.percent===0) ? <span style={{color: '#1aaf42'}}> {milepost.percent > 0 ? parseInt(milepost.percent*100):milepost.percent}%完成 </span> :"" }
          </p>
        </div>
        <div className="milepostdiv">
          {
            (current_user && current_user.login) && (permission && permission !== "Reporter") ?
            <Link to={`/${owner}/${projectsId}/milestones/${mileId}/edit`} className="grayButton" style={{ marginRight: 15 }}><i className="iconfont icon-lichengbeiicon1 font-12 mr5"></i>编辑里程碑</Link>
            :""
          }
          {/* {
            current_user && current_user.login ?
            <Button type='primary' onClick={() => {history.push(`/${owner}/${projectsId}/issues/${mileId}/new`)}} className='createMilepostBtn' style={{width: '83px'}}>+ 创建疑修</Button>
            :<Button type='primary' onClick={showLoginDialog} className='createMilepostBtn' style={{width: '83px'}}>+ 创建疑修</Button>
          } */}
          <CheckProfile {...props} sureFunc={()=>{history.push(`/${owner}/${projectsId}/issues/${mileId}/new`)}} checklogin className="operateButton ml20">+ 创建疑修</CheckProfile>
        </div>
      </FlexAJ>}
      <div className="lists mt25">
        <div className="listheader">
          <div style={{display:"flex"}}>
            <Checkbox value="all" style={{marginRight: "16px", display: (permission && permission !== "Reporter") ?"block":"none"}} checked={checkAll} onChange={chooseAll}></Checkbox>
            {
              allValue && allValue.length>0 ? 
              <span>选择{allValue.length}个issue</span>
              :
              <ul className="statusul">
                <li className={category === "all" ?"active":""} onClick={()=>setCategory("all")}>全部<span>{issuesCount}</span></li>
                <li className={category === "opened" ?"active":""} onClick={()=>setCategory("opened")}>开启中<span>{openedCount}</span></li>
                <li className={category === "closed" ?"active":""} onClick={()=>setCategory("closed")}>已关闭<span>{closedCount}</span></li>
              </ul>
            }
          </div>
          <div className="menusul">
            <AllMenus 
              ref={menuRef} 
              update={allValue && allValue.length>0} 
              owner={owner} 
              projectsId={projectsId} 
              chooseFunc={chooseFunc}
            />
            {
              allValue && allValue.length>0 ?
                <div>
                  <Button type="primary" ghost onClick={sureUpdate}>确定</Button>
                  <Button ghost className="ml10 mr10" onClick={cancelUpdate}>取消</Button>
                </div>
              :""
            }
          </div>
        </div>
        {
          total === 0 && <div className="milestonesNoDate"><img src={emp} alt=""/></div>
        }
        {
          total > 0 &&
          <React.Fragment>
            <Checkbox.Group name="issues" onChange={checkIssues} value={allValue} style={{ width: "100%" }}>
              <div className="listdatas">
                {issueList.map((item,key)=>{
                  return(
                    <Datas
                      key={key}
                      checkbox={ <Checkbox value={item.id} key={item.id} style={{marginRight: "16px", display: (permission && permission !== "Reporter") ?"block":"none"}}></Checkbox> } 
                      item={item}
                      owner={owner}
                      projectsId={projectsId}
                    />
                  )
                })
              }
              </div>
            </Checkbox.Group>
            {
              total > 10 &&
              <div className="pt25 pb30" style={{textAlign:"right"}}>
                <Pagination total={total} pageSize={limit} current={page} onChange={changepage} showSizeChanger showQuickJumper onShowSizeChange={(current, pageSize)=>{setPage(1);setLimit(pageSize);}}/>
              </div>
            }
          </React.Fragment>
        }
        {total === undefined && <div style={{height:344,display:"flex",alignItems:"center",justifyContent:"center"}}><Spin /></div> }
      </div>
    </div>
  )
}
export default MilepostDetail;