import React, { useEffect, useState } from 'react';
import SubMenu from '../sub/SubMenu';
import { Table, Tooltip, Spin,Pagination, Button, message } from 'antd';
import axios from 'axios';
import { Link } from 'react-router-dom';
import { truncateCommitId } from '../../common/util';
import { getImageUrl } from 'educoder';
import Nonedata from '../../Nodata';
import './Index.scss';
import Tree from '../img/tree.png'
import moment from 'moment';
import CopyTool from '../../Component/CopyTool';
import Modals from '../../Component/PublicModal/Index';

function Tags(props) {
  const [reload, setReload] = useState(undefined);
  const [source, setSource] = useState(undefined);
  const [isSpin, setIsSpin] = useState(true);
  const [page, setPage] = useState(1);
  const [total,setTotal] =useState(0);
  const [limit,setLimit] =useState(10);
  // 删除标签
  const [visible, setVisible] = useState(false);
  const { projectsId, owner } = props.match.params;
  const { projectDetail, current_user} = props;
  const permission = projectDetail && projectDetail.permission;

  useEffect(()=>{
    if(projectDetail && document.title.indexOf('所有标签-') === -1){
      const { author, name} = projectDetail;
      document.title = `所有标签-${author.name}/${name}`;
    }
  }, [projectDetail])

  useEffect(() => {
    if (projectsId) {
      setIsSpin(true);
      const url = `/v1/${owner}/${projectsId}/tags.json`;
      axios.get(url, {
        params: {
          limit,
          page: page
        }
      }).then((result) => {
        if (result) {
          setSource(result.data.tags);
          setTotal(result.data.total_count);
          setIsSpin(false);
        }
      }).catch(error => { })
    }
  }, [owner, projectsId, page, limit, reload]);

  const columns = [
    {
      title: "标签名",
      dataIndex: "name",
      key: 1,
      ellipsis: true,
      width: "240px",
      render: (txt, item) => {
        return (
          <div className="tagBranch">
            <Link className="hover tagClass font-16" to={`/${owner}/${projectsId}/tree/${item.name}`} onClick={()=>{window.scrollTo(0,0)}}>{item.name}</Link>
            <div className="tagModel">
              {
                item.tagger &&
                <Tooltip placement="top" title={item.tagger.name}>
                  {
                    item.tagger.id ?
                      <Link className="mr3 tagModelImg" to={`/${item.tagger.login}`} onClick={()=>{window.scrollTo(0,0)}}>
                        <img src={getImageUrl(`/${item.tagger && item.tagger.image_url}`)} alt="" />
                      </Link>
                      :
                      <span className="mr3 tagModelImg" style={{ cursor: "default" }} onClick={()=>{window.scrollTo(0,0)}}>
                        <img src={getImageUrl(`/${item.tagger && item.tagger.image_url}`)} alt="" />
                      </span>
                  }
                </Tooltip>
              }
              <span>最后一次提交于{item.time_ago}</span>
            </div>
          </div>
        )
      }
    },
    {
      title: "提交ID",
      dataIndex: "id",
      key: 3,
      ellipsis: true,
      width: "240px",
      render: (txt, item) => {
        return (
          <div className="treeCopyTag">
            <div className='treeCopyTagBox'>
              <span style={{lineHeight: '30px'}}>
                <img src={Tree} alt="sha" width={"16px"}/>
                <Tooltip placement="top" title={`最后提交日期:${item.created_at_unix ? moment(item.created_at_unix * 1000).format('YYYY-MM-DD') : ''}`}>
                  <Link className="hover color-blue" to={`/${owner}/${projectsId}/commits/${truncateCommitId(`${item.id}`)}`} onClick={()=>{window.scrollTo(0,0)}}>{truncateCommitId(item.id)}</Link>
                </Tooltip>
                <input type="text" id={`value${truncateCommitId(`${item.id}`)}`} value={`${truncateCommitId(item.id)}`}/>
              </span>
              <CopyTool beforeText="复制commit id" afterText="复制成功" inputId={`value${truncateCommitId(`${item.id}`)}`}/>
            </div>
          </div>
        )
      }
    },
    {
      title: "描述信息",
      dataIndex: "message",
      key: 4,
      ellipsis: true,
      render: (txt, item) => {
        return item.message || "--"
      }
    },
    {
      title: "下载",
      dataIndex: "stage_type",
      key: 5,
      align: "center",
      width: "460px",
      render: (txt, item) => {
        return (
          <React.Fragment>
            <a href={`${item.tarball_url}`} download className="btn-83" style={{width: '76px'}}>
              <i className="iconfont icon-xiazai-icon font-16 mr5"></i>TAR
            </a>
            <a href={`${item.zipball_url}`} download className="btn-83" style={{width: '76px'}}>
              <i className="iconfont icon-xiazai-icon font-16 mr5"></i>ZIP
            </a>
            {
              (current_user && current_user.login) && (permission && permission!=="Reporter") &&
              <React.Fragment>
                {item.has_release ? 
                  <Tooltip title={`该标签已绑定发行版，不支持创建`}>
                    <a className="btn-83 disabledBut">创建发行版</a>
                  </Tooltip> 
                  : 
                  <Link to={`/${owner}/${projectsId}/releases/new?tag=${item.name}`} className="btn-83">创建发行版</Link>
                }
                {item.has_release ? 
                  <Tooltip title={`该标签已绑定发行版，不支持删除操作`}>
                    <Button style={{width: '76px'}} disabled className='ml8'>删除</Button>
                  </Tooltip> : 
                  <Button className='f6_bor_but ml8' style={{width: '76px'}} onClick={()=>{setVisible(item)}}>删除</Button>
                }
              </React.Fragment>
            }
          </React.Fragment>
        )
      }
    }
  ]

  // 删除标签确认函数
  function deleteLabel(){
    axios.delete(`/v1/${owner}/${projectsId}/tags/${visible.name}.json`).then(res=>{
      if(res && res.data){
        setVisible(false);
        !res.data.status && message.success('删除成功');
        if(page>1 && (source && source.length===1)){
          setPage(page-1);
        }else{
          setReload(Math.random());
        }
      }
    })
  }

  return (
    <div>
      <SubMenu tab={"tags"} projectsId={projectsId} owner={owner} />
      <Spin spinning={isSpin}>
        <div className="tagSpin">
          {
            source && source.length > 0 &&
            <Table
              rowKey={(record) => record.id}
              className="tagTable"
              dataSource={source} columns={columns} pagination={false}></Table>
          }
          <div className="mt30 mb50 edu-txt-right">
              {total > limit && <Pagination
                current={page}
                total={total}
                pageSize={limit}
                onChange={(e)=>{setPage(e)}}
                showSizeChanger={true}
                onShowSizeChange={(current, pageSize)=>{setPage(1);setLimit(pageSize);}}
                showQuickJumper={true}
              ></Pagination>}
            </div>
          {/* {total > limit ? (
            <div className="mt30 mb50 edu-txt-right">
              {total > limit && <Pagination
                current={page}
                total={total}
                pageSize={limit}
                onChange={(e)=>{setPage(e)}}
                showSizeChanger={true}
                onShowSizeChange={(current, pageSize)=>{setPage(1);setLimit(pageSize);}}
                showQuickJumper={true}
              ></Pagination>}
            </div>
          ) : (
            ""
          )} */}
          {
            source && source.length === 0 && <Nonedata _html={'暂无数据~'} />
          }
        </div>
      </Spin>
      <Modals
        title="删除标签"
        onCancel={()=>{setVisible(false)}}
        visible={Boolean(visible)}
        width="456px"
        btn={
          <div>
            <Button size={"large"} onClick={()=>{setVisible(false)}}>取消</Button>
            <Button type={'danger'} ghost size={"large"} onClick={deleteLabel}>确认删除</Button>
          </div>
        }
      >
        <div className="contents mb30" style={{justifyContent: 'flex-start'}}>
          <i className='iconfont icon-shanchu_tc_icon1 font-36 mr18' style={{color: '#ca0002'}}></i>
          <p style={{color: '#333'}}>确定删除{visible.name}标签?</p>
        </div>
      </Modals>
    </div>
  )
}
export default Tags;