import React, { useEffect, useState } from "react";
import Meditor from "../Newfile/m_editor";
import moment from "moment"
import codesmell from '../Images/quality/codesmell.svg'
import bug from '../Images/quality/bug.svg'
import semibold from '../Images/quality/semibold.svg'
import bugRed from '../Images/quality/bug-red.svg'
import {Button, Spin, Empty} from "antd";

import axios from "axios";
import './index.scss'

function Quality(props){
    var timer = null;
    const { projectsId , owner } = props.match.params;
    const [sonarList,setSonarList] = useState({}) //问题列表分析
    const [statuts,setStatus] = useState(-1)
    const [questionList,setQuestionList] = useState([]) //对应问题列表
    const [isDetail,setDetail] = useState(false) // 是否为查看对应问题
    const [codeDetailValue,setCodeDetailValue] = useState({}) //问题详情 单个数据
    const [indexValue,setIndexValue] = useState(null)
    const severityList = {
        'BLOCKER':  "致命缺陷",
        "MINOR":"严重缺陷",
        "CRITICAL":"重要",
        "INFO":"建议缺陷",
        "MAJOR":"一般缺陷",
    }
    const {projectDetail} = props;
    useEffect(()=>{
        if(projectDetail){
            const { author, name} = projectDetail;
            document.title = `质量分析-${author.name}/${name}`;
        }
    },[projectDetail])

    useEffect(()=>{
        getTask()
        return () => {
            clearInterval(timer)
        }
    },[])

    useEffect(()=>{
        if(indexValue){
            // document.getElementById('htmlDOM').innerHTML
            const divs =  document.createElement("div");
            const key = indexValue.line
            divs.innerHTML = questionList[indexValue.index].message;
            const domBox = document.getElementsByClassName('CodeMirror-code')[0].childNodes[key]
            domBox.prepend(divs)
            divs.style.cssText='border:1px solid red; padding: 5px;border-radius: 10px;color: black;background: lemonchiffon;'
        }
    },[indexValue])
    const getTask = () => {
        axios.get(`/${owner}/${projectsId}/sonar_tasks.json`)
       .then(({data:{data,message,status}}) => {
        if(status===-1){
            setStatus(-1)
        }
        if(status === 0){
            setSonarList(data)
            clearInterval(timer)
            if(data.complete_status === 1) {
                setStatus(0)
                getTaskDetail(data.task_id)
            }
            if(data.complete_status === 0){
                setStatus(2)
                timer = setInterval(()=>{
                    getTask()
                },5000)
            }
        }
        }).catch(function (error) {
         console.log(error);

       });
    }

    const getTaskData = () => {
        axios.post(`/${owner}/${projectsId}/sonar_tasks.json`)
       .then(({data:{data,message,status}}) => {
            if(status===0){
                getTask()
            }
        }).catch(function (error) {
         console.log(error);
       });
    }

    const getTaskDetail = (task_id) => {
        axios.get(`/${owner}/${projectsId}/sonar_tasks/type_detail.json?task_id=${task_id}&type=ALL`)
        .then(({data:{data,message,status}})=>{
            document.body.scrollIntoView()
            setQuestionList(data);
        }).catch(function (error) {
            console.log(error);
        });
    }
    const handlecheck = () => {
        if(statuts === 2 ) return 
        getTaskData()
        setStatus(2)
    }
    const getCodeDetailData = (item,index) => {
        axios.get(`/${owner}/${projectsId}/sonar_tasks/code_source.json?component=${item.component}&task_id=${sonarList.task_id}`)
        .then(({data:{data,message,status}})=>{
            document.body.scrollIntoView()
            // data.splice(item.line,0,{code:document.getElementById('htmlDOM').innerHTML,line:item.line})
            const text = data.map(item => item.code).join("\n")
            const dom = document.createElement("div");
            dom.innerHTML = text;
            setDetail(true)
            setCodeDetailValue({content:dom.innerText,
                line:item.line + 5
            })
            setIndexValue({
                line:item.line,
                index
            })
        })
    }
    const handleCodeDetail = (item,index) => {
        getCodeDetailData(item,index)
    }
    const handleBack = () => {
        setDetail(false)
        setIndexValue(null)
    }

    return (
      <React.Fragment>
        <div className="wrap">
            {!isDetail?<div>
            <div className="wrap-header">
            <div className="quality">
                <div className="quality-fill mr35"><img alt='' src={bug}/>Bug<span className="ml3">{sonarList.bugs}</span></div>
                <div className="quality-fill mr35"><img alt='' src={semibold}/>Security<span className="ml3">{sonarList.vulnerability}</span></div>
                <div className="quality-fill mr35"><img alt='' src={codesmell}/>Codesmell<span className="ml3">{sonarList.codeSmell}</span></div>
                <div>
                    <div className="quality-total mr20">代码量统计：{sonarList.codeLines}</div>
                    <div className="quality-total mr20">检测语言：{sonarList.language}</div>
                    {statuts !== -1 && <div className="quality-total mr20">最后检测时间：{moment(sonarList.updated_at).format("YYYY-MM-DD HH:mm")}</div>}
                </div>
            </div>
            <div className={`wrap-header-btn ${statuts===-1?'blue':statuts===0?'green':'orange'}`} onClick={handlecheck}>{(statuts===-1)?"开始检测":(statuts===0)?"重新检测":"正在检测"}</div>
            </div>
            <div>
                {sonarList.complete_status >0 ?questionList.map((item,index)=>{
                    return <div key={index} className='message-item' onClick={()=>handleCodeDetail(item,index)}>
                                {item.component}
                                <div className="message-item-content mb30 mt10" >
                                    <img alt="" src={bugRed}/><span id="htmlDOM">{item.message}&nbsp;&nbsp;&nbsp;</span>
                                    <div className="message-item-content-serverity">缺陷类型：{severityList[item.severity]}<span className="ml15">line：{item.line}行</span></div>
                                </div>
                            </div>
                }):<div className="empty-status">{statuts === -1?<Empty/>:<Spin size="large" >正在检测中,可能需要几分钟...</Spin>}</div>}
            </div>
            </div>:
            <div className="wrap-code">
                <Button type="primary" style={{marginBottom:20}} onClick={handleBack} >返回</Button>
                <Meditor
                 content={codeDetailValue.content || "" }
                 readOnly={true}
                 goLine={codeDetailValue.line || ""}
                 editorType="update"
                />
            </div>
            }
        </div>
      </React.Fragment>
    );
}
export default Quality;
