import React , { Component } from 'react';
import { Spin , Pagination, Timeline } from 'antd';
import { getImageUrl , returnbar } from 'educoder';
import { truncateCommitId ,timeFormat } from '../common/util';
import { AlignTop } from '../Component/layout';
import SelectBranch from '../Branch/Select';
import Nodata from '../Nodata';

import User from '../Component/User';
import RenderHtml from '../../components/render-html.jsx';
import Tree from './img/tree.png';
import axios from 'axios';
import {Link} from "react-router-dom";
import CopyTool from '../Component/CopyTool';

import './tree/Index.scss'


//代码库--提交页面
class CoderRootCommit extends Component{
  constructor(props){
    super(props);
    this.state={
      commitDatas:undefined,
      dataCount:undefined,
      limit:10,
      page: 1,
      isSpining:false,
      branchList:undefined
    }
  }

  componentDidMount=()=>{
    this.Init();
    this.getBranchs();
  }

  // 获取分支列表
  getBranchs=()=>{
    const { projectsId , owner } = this.props.match.params;
    axios.get(`/${owner}/${projectsId}/branches.json`).then(result=>{
      this.setState({
        branchList:result.data
      })
    }).catch((error)=>{})
  }

  componentDidUpdate=(prevProps)=>{
    const { location } = this.props;
    const prevlocation = prevProps && prevProps.location;
    if (location !== prevlocation) {
      this.Init();
    }
  }

  UrlParamHash(url){
    const params = {};
    let h;
    let hash = url.slice(url.indexOf('?')+1).split('&');
    for(let i = 0; i<hash.length;i++){
      h = hash[i].split('=');
      params[h[0]] = h[1];
    }
    return params;
  }

  Init =()=>{
    const { branchName } = this.props.match.params;
    const { limit } = this.state;
    const {search} = this.props.location;
    const realPage = (search && this.UrlParamHash(search).page) ? parseInt(this.UrlParamHash(search).page) : 1;
    this.setState({
      isSpining:true,
      page:realPage
    })
    this.getCommitList( returnbar(branchName) , realPage , limit );
  }

  getCommitList=(branch , page , limit)=>{
    this.setState({
      isSpining:true
    })
    const { projectsId , owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/commits.json`;
    axios.get(url,{
      params:{
        sha:returnbar(branch),
        page,
        limit
      }
    }).then((result)=>{
      if(result && result.data){
        this.setState({
          isSpining:false
        })
        const array = [];
        result.data.commits && result.data.commits.length > 0 && result.data.commits.map((item,key)=>{
          array.push({
            name:item.author && item.author.name,
            login: item.author && item.author.login,
            id: item.author && item.author.id,
            image_url:item.author && item.author.image_url,
            sha:item.sha,
            time_from_now:item.time_from_now,
            message:item.message,
            timestamp:item.timestamp
          })
        })
        this.setState({
          commitDatas:array,
          dataCount:result.data.total_count,
          isSpining:false
        })
      }
    }).catch((error)=>{console.log(error)})
  }

  // 切换分支 search:tag为根据标签搜索
  changeBranch=(value)=>{
    const { projectsId , owner } = this.props.match.params;
    this.props.history.push(`/${owner}/${projectsId}/commits/branch/${value}`);
  }

  ChangePage=(page)=>{
    this.props.history.push({pathname: this.props.history.location.pathname,search: `page=${page}`})
  }
  
  render(){
    const { commitDatas , dataCount , limit , page , isSpining , branchList } = this.state;
    const { projectDetail, commit_class , defaultBranch , platform } = this.props;
    const { projectsId , owner , branchName } = this.props.match.params;
    let branch = returnbar(branchName || defaultBranch);
    return(
      <React.Fragment>
        <div className={"main"}style={{padding:"0px",border:"none"}}>
          <div className="f-wrap-between">
            <SelectBranch 
              repo_id={projectDetail && projectDetail.repo_id} 
              projectsId={projectsId} 
              branch={branch}
              changeBranch={this.changeBranch}
              owner={owner}
              history={this.props.history}
              branchList={branchList}
            ></SelectBranch>
          </div>
          <Spin spinning={isSpining}>
            <Timeline className="commitList">
              {
                commitDatas && commitDatas.length > 0 && commitDatas.map((item,k)=>{
                  return(
                    <Timeline.Item key={k} dot={page ===1 && k===0 ?<span className="new-conmmit">最新</span>:<i className="iconfont icon-a-yuanquan2x"></i>}>
                      <div className="commitList-item f-wrap-between">
                        <div>
                          <AlignTop>
                            <div className="commitDesc">
                              {
                                platform ?
                                <Link to={`/${owner}/${projectsId}/commits/${truncateCommitId(`${item.sha}`)}`} className="font-14 color-grey-3 font-bd">
                                  <RenderHtml value={item.message}/>
                                </Link>
                                :
                                <RenderHtml value={item.message}/>
                              }
                            </div>
                          </AlignTop>
                          <p className="f-wrap-alignCenter mt15 pb5">
                            <User
                              id={item.id}
                              url={(item.image_url && getImageUrl(`/${item.image_url}`)) || "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3025493530,1989042357&fm=26&gp=0.jpg"}
                              name={item.name}
                              login={item.login}
                            />
                            {item.timestamp && <label className="font-14 color-grey-3 ml3">提交于 {timeFormat(item.timestamp)}</label>}
                          </p>
                        </div>
                        <div>
                          <div className="treecopy">
                            <div>
                              <span className="treecopy-cont shadow">
                                <img src={Tree} alt="sha" width={"16px"}/>
                                {
                                  platform ?
                                  <Link to={`/${owner}/${projectsId}/commits/${truncateCommitId(`${item.sha}`)}`}>{truncateCommitId(`${item.sha}`)}</Link>
                                  :
                                  <span style={{color:"#466AFF",cursor:"default"}}>{truncateCommitId(`${item.sha}`)}</span>
                                }
                                <input type="text" id={`value${k}`} value={`${truncateCommitId(`${item.sha}`)}`}/>
                              </span>
                              <CopyTool beforeText="复制commit id" afterText="复制成功" inputId={`value${k}`}/>
                            </div>
                            <button className="btn-83" onClick={()=>{window.location.href=`/${owner}/${projectsId}/tree/${truncateCommitId(item.sha)}`}}>浏览文件</button>
                          </div>
                        </div>
                      </div>
                    </Timeline.Item>
                  )
                })
              }
              {commitDatas && commitDatas.length === 0 && <Nodata _html="暂无数据"/>}
            </Timeline>
            {
              dataCount > limit ?
                <div className="edu-txt-center pt30 mb30">
                  <Pagination simple current={page} total={dataCount} pageSize={limit} onChange={this.ChangePage}></Pagination>
                </div>
              :""
            }
          </Spin>
        </div>
      </React.Fragment>
    )
  }
}
export default CoderRootCommit;
