import React, { useEffect, useState } from 'react';
import './Index.scss';
import { AlignCenter, Blueback , FlexAJ } from '../Component/layout';
import { Dropdown, Input , Menu , Pagination, Spin , Popconfirm, Button } from 'antd';
import { Link } from 'react-router-dom';
import UploadSource from './UploadSource';
import AddTag from './AddTag';
import { getImageUrl } from 'educoder';
import Nodata from '../Nodata';
import axios from 'axios';

const { Search } = Input;
const sort = [
  "按上传时间排序",
  "按下载次数排序"
]
const limit = 15;
const https = 'https://testfiles.trustie.net';
function Index(props){
  const [ sortValue , setSortValue ] = useState(0);
  const [ page , setPage ] = useState(1);
  const [ total , setTotal ] = useState(0);
  const [ search , setSearch ] = useState(undefined);
  const [ data , setData ] = useState(undefined);
  const [ isSpin , setIsSpin ] = useState(true);
  const [ error , setError ] = useState(false);
  const [ attachments , setAttachments ] = useState(undefined);
  
  const [ id , setId ] = useState(undefined);

  const [ visible , setVisible ] = useState(false);
  const [ addVisible , setAddVisible ] = useState(false);
  
  const repo_id = props.projectDetail && props.projectDetail.repo_id;
  const owner = props.match.params.owner;
  const current_user = props.current_user;

  useEffect(()=>{
    if(owner && repo_id){
      setIsSpin(true);
      getData();
    }
  },[repo_id,owner,search,sortValue,page])

  function getData(){
    const url = https +`/api/project/achievement/`;
    axios.get(url,{
      params:{
        projectId:repo_id,
        curPage:page,
        pageSize:limit,
        name:search,
        sort:sortValue+1,
      }
    }).then(result=>{
      if(result && result.data){
        setData(result.data.data.rows);
        setTotal(result.data.data.total);
        setIsSpin(false);
        setError(false);
      }
    }).catch(error=>{setIsSpin(false);setError(true);})
  }

  // 搜索
  function onSearch(value){
    setSearch(value);
  }

  // 切换排序方式
  function changeSort(e,index){
    setSortValue(index);
  }


  const menu=(
    <Menu>
      {
        sort && sort.map((item,key)=>{
          return(
            <Menu.Item onClick={(e)=>changeSort(e,key)} value={key} className={key=== sortValue ?"color-blue":""}>{item}</Menu.Item>     
          )
        })
      }
    </Menu>
  )

  function listmenu(id,attachments,isPublic){
    return(
      <Menu>
        <Menu.Item onClick={()=>{setId(id);setVisible(true);setAttachments(attachments)}}>更新版本</Menu.Item>
        <Menu.Item onClick={()=>changeStatus(id,isPublic===1?0:1)}>{isPublic === 1 ? "设为私有":"设为公开"}</Menu.Item>
        <Menu.Item onClick={()=>deleteSourceFunc(id)}>删除资源</Menu.Item>
      </Menu>
    )
  }
  // 更细私有状态
  function changeStatus(id,isPublic){
    const url = https+`/api/project/achievement/updateStatus`;
    axios.put(url,{
      id,status:isPublic
    }).then(result=>{
      if(result && result.data){
        props.showNotification(`资源${isPublic === 1 ? "设为公开":"设为私有"}成功！`);
        setIsSpin(true);
        getData();
      }
    }).catch({})
  }

  // 删除资源方法
  function deleteSourceFunc(id){
    props.confirm({
      content: "是否确认删除所选资源文件？",
      onOk: () => {
        const url = https + `/api/project/achievement/${id}`;
        axios.delete(url).then(result=>{
          if(result && result.data && result.data.code === "1"){
            props.showNotification("资源删除成功");
            setIsSpin(true);
            getData();
          }
        })
      }
    })
    
  }
    

  // 上传资源成功
  function onOk(){
    setVisible(false);
    setIsSpin(true);
    getData();
  }

  //  确认删除标签
  function removeTagFunc(id,tag){
    const url = https + `/api/project/achievement/deleteTag`;
    axios.delete(url,{
      params:{id,tagName:tag}
    }).then(result=>{
      if(result && result.data){
        props.showNotification("标签删除成功");
        setIsSpin(true);
        getData();
      }
    }).then(error=>{})
  }

  function addPanel(id){
    setAddVisible(true);
    setId(id);
  }

  function onCancelAdd(){
    setId(undefined);
    setAddVisible(false);
  }

  // 添加标签
  function sureAddTag(values){
    const url = https+`/api/project/achievement/addTag?id=`+id+`&tagName=`+values.tagName;
    axios.put(url).then(result=>{
      if(result){
        setId(undefined);
        setAddVisible(false);
        setIsSpin(true);
        getData();
      }
    })
  }

  return(
    <div className="sourcePanel">
      <AddTag 
        visible={addVisible}
        onCancel={onCancelAdd}
        onOk={sureAddTag}
      />
      <UploadSource 
        visible={visible} 
        onCancel={()=>setVisible(false)} 
        onOk={onOk} 
        showNotification={props.showNotification}
        owner={owner}
        projectsId={repo_id}
        id={id}
        attachments={attachments}
      />
      <div className="headtitle">
        <FlexAJ>
          <span className="font-18">资源库{total ? <span>({total})</span>:""}</span>
          { current_user && current_user.login && (props.projectDetail && props.projectDetail.permission) ?
            <Blueback onClick={()=>{setId(undefined);setVisible(true);}}>上传资源</Blueback>:""
          }
        </FlexAJ>
      </div>
      <FlexAJ className="subHeadtitle">
        <Search 
          placeholder="在项目内搜索资源" 
          onSearch={onSearch} 
          allowClear 
          enterButton="搜索"
          width="220px"
        />
        <Dropdown overlay={menu} placement="bottomRight">
          <span className="color-grey-9">{sort[sortValue]}<i className="iconfont icon-sanjiaoxing-down font-16 color-grey-9 ml3"></i></span>
        </Dropdown>
      </FlexAJ>
      <Spin spinning={isSpin}>
        <div className="bodycontent">
        {
          data && data.length> 0 &&
          <ul className="bodycontentul">
            {
              data.map((item,key)=>{
                return(
                  <li>
                    <Link to= {`/${item.login}`} className="infoImg"><img src={getImageUrl(`/${item.imageUrl}`)} alt="" /></Link>
                    <div style={{flex:'1',width:"0"}}>
                      <FlexAJ>
                        <AlignCenter>
                          <a href={https+`/busiAttachments/download/${item.attachId}`} download className="infoname">{item.fileName}</a>
                          <a href={https + `/busiAttachments/view/${item.attachId}`}><i className="iconfont icon-shenqinggongkai font-15 ml10 color-grey-9"></i></a>
                          {item.isPublic === 0 && <span className="privateTip">私有</span>}
                        </AlignCenter>
                        { current_user && current_user.login && 
                          <Dropdown overlay={()=>listmenu(item.id,item.attachments,item.isPublic)} placement={'bottomRight'}>
                            <i className="iconfont icon-gengduo1 color-grey-6"></i>
                          </Dropdown>
                        }
                      </FlexAJ>
                      <p className="infos">
                        <span>上传时间：<span>{item.uploadTime}</span></span>
                        <span>文件大小：<span>{item.fileSize}</span></span>
                        <span>下载：<span>{item.download}</span></span>
                      </p>
                      <p className="infodesc task-hide-2">{item.remark}</p>
                      <div className="infotag">
                        {
                          item.tags && item.tags.length>0 && item.tags.map((i,k)=>{
                            return(
                              <span>{i}
                                {
                                  current_user && (current_user.login === item.login) ?
                                  <Popconfirm title="确定要删除当前标签？" onConfirm={()=>removeTagFunc(item.id,i)} okText="是" cancelText="否">
                                    <i className="iconfont icon-guanbi font-12 ml2"></i>
                                  </Popconfirm>:""
                                }
                              </span>
                            )
                          })
                        }
                        {
                          current_user && (current_user.login === item.login) &&
                          <a className="color-blue font-12" onClick={()=>addPanel(item.id)} style={{height:"20px",lineHeight:"20px"}}>+新增标签</a>
                        }
                      </div>
                    </div>
                  </li>
                )
              })
            }
          </ul>
        }
        {
          ((data && data.length === 0) || error) && <Nodata _html="暂无数据"/>
        }
        {
          total > limit && 
          <div className="pt20 pb20 edu-txt-center">
            <Pagination 
              simple
              current={page}
              pageSize={limit}
              total={total}
              onChange={(p)=>{setPage(p)}}
            />
          </div>
        }
      </div>
      </Spin>
    </div>
  )
}
export default Index;