import React, { useEffect, useState } from 'react';
import DataEmpty from './dataEmpty';
import DetectionModal from './detectionModal';
import { Table , Spin, message } from 'antd';
import axios from 'axios';


function Data(props){
  const [ detectionVisible , setDetectionVisible ] =  useState(false);
  const [ dataSource , setDataSource ] = useState(undefined);
  const [ page , setPage ] = useState(1);
  const [ spining , setSpining ] = useState(true);
  const [ relayCount , setRelayCount ] = useState(5);
  const [ repeatId , setRepeatId ] = useState(undefined);
  const [ repeatBranch , setRepeatBranch ] = useState(undefined);

  const { owner , projectsId } = props.match.params;
  const { current_user , isManager } = props;
  const limit = 15;


  function onDetectionOk(){
    props.showNotification("新建分析成功，可在“检测状态”处查看扫描检测进度");
    setDetectionVisible(false);
    setSpining(true);
    Init();
  }

  function Init(){
    const url = `/traces/${owner}/${projectsId}/task_results.json`;
    axios.get(url,{
      params:{
        page,limit
      }
    }).then(result=>{
      if(result){
        setDataSource(result.data.data);
        setRelayCount(result.data.left_tasks_count);
        setSpining(false);
      }
    }).catch(error=>{})
  }

  useEffect(()=>{
    setSpining(true);
    Init();
  },[])


  // 重新扫描
  function repeatCheck(project_id,branch){
    if(relayCount <= 0){
      message.error("无可用检测次数");
      return;
    }
    setRepeatId(project_id);
    setRepeatBranch(branch);
    setDetectionVisible(true);
  }

  function createCheck(){
    if(relayCount <= 0){
      message.error("无可用检测次数");
      return;
    }
    setRepeatBranch(undefined);
    setRepeatId(undefined);
    setDetectionVisible(true);
  }

  function handleDownExcel(task_id){
    setSpining(true);
    const url = `/api/traces/${owner}/${projectsId}/task_pdf.json?task_id=${task_id}`;
    // window.open(`/api/traces/${owner}/${projectsId}/task_pdf.json?task_id=${task_id}`);
    const x = new XMLHttpRequest();
    x.open('GET', url, true)
    x.responseType = 'blob';
    x.onload = (e) => {
      // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
      const url = window.URL.createObjectURL(x.response)
      const a = document.createElement('a')
      a.href = url;
      a.download = "report.pdf";
      a.click();
      setSpining(false);
    }
    x.send();
    console.log("spining");
  }

  return(
    <div>
      <DetectionModal 
        visible={detectionVisible} 
        onCancel={()=>setDetectionVisible(false)} 
        onOk={onDetectionOk} 
        owner={owner}
        projectsId={projectsId}
        relayCount={relayCount}
        repeatId={repeatId}
        repeatBranch={repeatBranch}
      />
      <div className="servertitle">
        <span className="systitle">重晴鸟代码溯源系统</span>
        { isManager && <a className="btnhover" onClick={createCheck}>新建分析</a> }
      </div>
      <Spin spinning={spining}>
        <div style={{minHeight:"400px"}}>
          {
            dataSource && dataSource.length >0 &&
            <div>
              <ul className="dataUl">
                <li className="dataUlhead">
                  <span>序号</span>
                  <span>分支名称</span>
                  <span>检测状态</span>
                  <span>检测时间</span>
                  { isManager && <span>操作</span> }
                </li>
                {
                  dataSource.map((e,key)=>{
                    return(
                      <div key={key}>
                        <li className="dataUlbody">
                          <span>{key + 1 }</span>
                          <span title={e.branch_tag}>{e.branch_tag}</span>
                          <span>
                            {
                              e.detect_status === "fail" ?
                              <span className="failure">失败</span>
                              : e.detect_status==="detecting" ?
                              <div className="running">
                                <span className="percentline" style={{width:`${e.detect_process}%`}}></span>
                                <span className="percentNum" style={{left:`${e.detect_process+5}%`}}>{e.detect_process}%</span>
                              </div>
                              :
                              <span className="success">成功</span>
                            }
                          </span>
                          <span>{e.detect_startdate}</span>
                          {
                            isManager &&
                            <span>
                              <div className="operationBtns">
                                {
                                  e.detect_status ==="detecting" ? 
                                  <span>重新扫描</span>
                                  :
                                  <a onClick={()=>repeatCheck(e.project_id,e.branch_tag)}>重新扫描</a>
                                }
                                {/* {
                                  (e.detect_status ==="fail" || e.detect_status ==="detecting") ?
                                  <span>查看<i className="iconfont icon-sanjiaoxing-down"></i></span>
                                  :
                                  <a>查看<i className="iconfont icon-sanjiaoxing-down"></i></a>
                                } */}
                                {
                                  (e.detect_status ==="fail" || e.detect_status ==="detecting") ?
                                  <span>下载报告</span>
                                  :
                                  <a onClick={()=>handleDownExcel(e.task_id)}>下载报告</a>
                                }
                              </div>
                            </span>
                          }
                        </li>
                        {false && <iframe src="www.baidu.com" id={`htmlIframe_${key}`} frameBorder="0" name={`htmlIframe_${key}`} style={{ background: '#fff', height: '100%', width: '100%' }}></iframe>}
                      </div>
                    )
                  })
                }
              </ul>
            </div>
          }
          {
            (dataSource === null || (dataSource && dataSource.length === 0)) &&
            <DataEmpty />
          }
        </div>
      </Spin>
    </div>
  )
}
export default Data;