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

function Data(props) {
  const [detectionVisible, setDetectionVisible] = useState(false);
  const [dataSource, setDataSource] = useState(undefined);
  const [page, setPage] = useState(1);
  const [spining, setSpining] = useState(false);
  const [relayCount, setRelayCount] = useState(5);
  const [repeatId, setRepeatId] = useState(undefined);
  const [repeatBranch, setRepeatBranch] = useState(undefined);
  const [lookResultUrl, setLookResultUrl] = useState(undefined);
  const [openResultTaskId, setOpenResultTaskId] = useState(undefined);
  const [viewBase, setViewBase] = useState('https://cjntest.trustie.net/');
  const [operateTime, setOperateTime] = useState(undefined);

  const { owner, projectsId } = props.match.params;
  const { isManager, projectDetail, history } = 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) {
        if(result.data.code === 501){
          setOperateTime(result.data.data.operate_time);
        }else if (Array.isArray(result.data.data)) {
          setDataSource(result.data.data);
          setRelayCount(result.data.left_tasks_count);
          setLookResultUrl(result.data.view_base);
          setViewBase(result.data.view_base);
          for (const item of result.data.data) {
            if (item.detect_status === "detecting" || item.detect_status === "waiting" || (item.detect_status=="detected"&& item.is_reported=="0")) {
              setTimeout(Init, 2000);
              break;
            }
          }
        } else {
          result && result.data.message && props.showNotification(result.data.message);
        }
        setSpining(false);
      }else{
        setSpining(false);
      }
    }).catch(error => { })
  }

  useEffect(() => {
    if(projectDetail){
      // 更新网页标题
      const { author, name} = projectDetail;
      document.title = `codeanalysis-${author.name}/${name}`;

      if(projectDetail.forked_from_project_id){
        history.go(-1);
      }else{
        setSpining(true);
        Init();
      }
    }
  }, [projectDetail])

  useEffect(() => {
    window.addEventListener("message", iframeHeight, false);
    return () => {
      window.removeEventListener("message", iframeHeight, false);
    }
  })


  function iframeHeight(e){
    if (e && e.data && viewBase && e.origin && viewBase.indexOf(e.origin)>-1) {
      let myHeight = JSON.parse(e.data);
      if (document.querySelector("#htmlIframe")) {
        document.querySelector("#htmlIframe").height = myHeight.height;
      }
    }
  }


  // 重新扫描
  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();
  }

  function lookResult(taskId) {
    if (!openResultTaskId || (openResultTaskId && openResultTaskId !== taskId)) {
      setOpenResultTaskId(taskId);
    } else {
      setOpenResultTaskId(undefined);
    }
  }

  function iframeLoad() {
    try {
      let myIframe = document.getElementById("htmlIframe");
      if (myIframe.contentDocument) {
        myIframe.height = myIframe.contentDocument.querySelector('.el-main').clientHeight + 260;
        // myIframe.contentDocument.querySelector('.admin-body-container').style.overflow = 'hidden';
      }
    } catch (err) {
      console.error(err);
    }
  }
  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>
        {!operateTime && isManager && <a className="btnhover" onClick={createCheck}>新建分析</a>}
      </div>
      <Spin spinning={spining}>
        <div style={{ minHeight: "400px" }}>
          {operateTime && <div className='operateBox mt25'>
            <img src={img} alt='' width={130}/>
            <div className='font-20 mt20 mb5'>系统维护中</div>
            <div className='font-17'>预计<span className='timeBox'>{operateTime}小时后</span>代码溯源服务将恢复正常访问，给您带来不便，敬请谅解!</div>
          </div>}
          {
            !operateTime && 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>
                                  : e.detect_status === "detected" ?
                                    <span className="success">成功</span> : <div className="running">
                                    <span className="percentline" style={{ width: `0%` }}></span>
                                    <span className="percentNum" style={{ left: `5%` }}>0%</span>
                                  </div>
                            }
                          </span>
                          <span>{e.detect_startdate}</span>
                          {
                            isManager &&
                            <span>
                              <div className="operationBtns">
                                {
                                  e.detect_status === "detecting" ||  e.detect_status === "waiting"?
                                    <span>重新扫描</span>
                                    :
                                    <a onClick={() => repeatCheck(e.project_id, e.branch_tag)}>重新扫描</a>
                                }
                                {
                                  (e.detect_status === "fail" || e.detect_status === "detecting" ||  e.detect_status === "waiting") ?
                                    <span>查看<i className="iconfont icon-sanjiaoxing-down"></i></span>
                                    :
                                    <a onClick={() => { lookResult(e.task_id) }}>查看<i className={`iconfont ${openResultTaskId === e.task_id ? 'icon-sanjiaoxing-up' : 'icon-sanjiaoxing-down'}`}></i></a>
                                }
                                {
                                  (e.detect_status === "fail" || e.detect_status === "detecting" ||  e.detect_status === "waiting" || (e.detect_status=="detected"&& e.is_reported=="0")) ?
                                    <span>下载报告</span>
                                    :
                                    <a onClick={() => handleDownExcel(e.task_id)}>下载报告</a>
                                }
                              </div>
                            </span>
                          }
                        </li>
                        {/* lookResultUrl+e.task_id */}
                        {openResultTaskId && openResultTaskId === e.task_id && <iframe title={`htmlIframe_${key}`} src={lookResultUrl + e.task_id} id={`htmlIframe`} frameBorder="0" name={`htmlIframe_${key}`} width="100%" onLoad={iframeLoad} height={'auto'}></iframe>}
                      </div>
                    )
                  })
                }
              </ul>
            </div>
          }
          {
            !operateTime && (dataSource === null || (dataSource && dataSource.length === 0)) &&
            <DataEmpty />
          }
        </div>
      </Spin>
    </div>
  )
}
export default Data;