import React , { useEffect , useState } from 'react';
import { WhiteBack } from '../Component/layout';
import { Spin } from 'antd';
import Head from './Dispose/head';
import Menus from './Dispose/menus';
import Init from './Dispose/Init';
import Sure from './Dispose/Sure';
import Stage from './Dispose/Stage';
import axios from 'axios';

function disposePipeline(props){
  const [ spining , setSpining ] = useState(true);
  const [ stage , setStage ] = useState(1);
  const [ pipeLineName , setPipeLineName ] = useState(undefined);
  const [ stepName , setStepName ] = useState(undefined);
  const [ stageId , setStageId ] =useState(undefined);
  const [ menuList , setMenuList ] = useState(undefined);
  const [ stageType , setStageType ] = useState("init");
  const [ datas , setDatas ] = useState(undefined);
  const [ templates , setTemplates] = useState(undefined);
  const [ datasUpdataFlag , setDatasUpdataFlag ] = useState(false);
  const [ loading ,setLoading ] = useState(false);

  const { disposeId } = props.match.params;
  let projectsId = props.match.params.projectsId; 
  let owner = props.match.params.owner; 
  useEffect(()=>{
    if(stageType && stageType !=="confirm"){
      InitTemplates();
    }
  },[stageType])

  // 获取模板
  function InitTemplates(){
    const url = `/ci/templates/templates_by_stage.json`;
    axios.get(url,{
      params:{ stage_type:stageType, id:disposeId }
    }).then(result=>{
      if(result && result.data){
        setTemplates(result.data);
      }
    }).catch(error=>{})
  }

  useEffect(()=>{
    if(disposeId && (stageType && stageType !=="confirm")){
      getData(0);
    }
  },[disposeId])
  // 获取所有阶段默认第一个阶段的数据
  function getData(index){
    const url = `/ci/pipelines/${disposeId}/stages.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        setMenuList(result.data.stages);
        if(index || index === 0){
          let first = result.data.stages[index];
          setStage(first.show_index);
          setStageId(first.id);
          setPipeLineName(`${first.pipeline_name}`);
        }
      }
    })
  }

  useEffect(()=>{
    if(stageId){
      getStageStep(stageId);
    }
  },[stageId])
  // 切换阶段时获取阶段步骤数据（第一次默认查询”初始化“阶段的数据）
  function getStageStep(stageId){
    let url = "";
    if(stageType && stageType === "confirm"){
      url = `/ci/pipelines/${disposeId}/content.json`;
      axios.get(url,{
        params:{
          owner,repo:projectsId
        }
      }).then(result=>{
        if(result && result.data){
          setDatas(result.data);
        }
      }).catch(error=>{})
    }else{
      url = `/ci/pipelines/${disposeId}/${stageId}/steps.json`;
      axios.get(url).then(result=>{
        if(result && result.data){
          let step = result.data.steps;
          setDatas(step);
          let flag = !step || (step && step.length === 0);
          setDatasUpdataFlag(flag);
        }
      }).catch(error=>{})
    }
    setSpining(false);
  }

  // 切换阶段：s：show_index,stage_type:stage_type
  function changestage(show_index,stage_type,stage_id,stage_name){
    if(show_index !== stage){
      saveFunc(show_index,stage_type,stage_id,stage_name);
    }
  }

  // 获取子组件传过来的数据
  function saveDatas(steps){
    setDatas([...steps]);
    setDatasUpdataFlag(true);
  }

  // 检查数组里面是否有空数据
  function checkDatas(){
    if(datas && datas.length > 0){
      for(let i= 0;i< datas.length;i++){
        if(datas[i] && (!datas[i].content || !datas[i].template_id)){
          props.showNotification("请先选择模板！");
          return false;
        }
      }
    }else{
      if(stageType === "init" ){
        props.showNotification("请先选择模板！");
        return false;
      }else if(stageType === "confirm" ){
        return true;
      }else{
        return "";
      }
    }
    return true;
  }

  // 保存步骤
  function saveFunc(show_index,stage_type,stage_id,stageName,btn){
    setSpining(true);
    // 判断数据是否有过更新
    if(datasUpdataFlag && stageType !== "confirm"){
      // 先判断子组件传过来的数据是否有undefined --datas
      let f = checkDatas();
      if(f && (datas && datas.length !== 0)){
        // 数据没问题后先保存数据再切换阶段
        saveDataFunc(btn,show_index,stage_type,stage_id,stageName);
      }
      else{
        setSpining(false);
        f === "" && elseFunc(btn,show_index,stage_type,stage_id,stageName);
      }
    }else{
      elseFunc(btn,show_index,stage_type,stage_id,stageName);
    }
  }

  function saveDataFunc(btn,show_index,stage_type,stage_id,stageName){
    const url = `/ci/pipelines/${disposeId}/${stageId}/stage_step.json`;
        axios.post(url,{
          steps:datas
        }).then(result=>{
          if(result && result.data){
            setDatasUpdataFlag(false);
            if(!btn){
              setStage(show_index);
              setStageType(stage_type);
              setStageId(stage_id);
              setStepName(pipeLineName+`-`+stageName);
            }else{
              enters(btn);
            }
          }else{
            props.showNotification("阶段更新失败，请稍微重试！");
          }
        }).catch(error=>{})
  }

  function elseFunc(btn,show_index,stage_type,stage_id,stageName){
    if(btn){
      enters(btn);
    }else{
      setStage(show_index);
      setStageType(stage_type);
      setStageId(stage_id);
      setStepName(pipeLineName+`-`+stageName);
    }
  }

  // 上一步、下一步
  function enters(btn){
    let s = stage;
    if(btn === "next"){
      // 点击阶段里面的下一步
      s = s+1;
    }else{
      // 上一步
      s = s-1;
    }
    let item = menuList && menuList.filter(i=>i.show_index === (s));
    setStage(s);
    setStageType(item[0].stage_type);
    setStageId(item[0].id);
    setStepName(pipeLineName+`-`+item[0].stage_name);
  }
  // 删除步骤
  function deleteStep(id,index){
    if(id){
      const url =  `/ci/pipelines/${disposeId}/${stageId}/${id}/delete_step.json`;
      axios.delete(url).then(result=>{
        if(result && result.data){
          getStageStep(stageId);
          props.showNotification("阶段步骤删除成功!");
        }
      }).catch(error=>{})
    }else{
      let d = datas.filter(s=>s.show_index !== (index+1));
      setDatas(d);
    }
  }
  function renameFunc(value,id){
    const url = `/ci/pipelines/${disposeId}/${id}/update_stage.json`;
    axios.put(url,{
      stage_name:value
    }).then(result=>{
      if(result && result.data){
        getData();
      }
    }).catch(error=>{})
  }

  // 新增阶段
  function addMenuFunc(name,index){
    const url =  `/ci/pipelines/${disposeId}/create_stage.json`;
    axios.post(url,{
      show_index:index,
      stage_name:name
    }).then(result=>{
      if(result && result.data){
        getData(index-1);
        setStageType("customize");
      }else{
        props.showNotification("阶段新增失败!");
      }
    })
  }

  // 删除阶段
  function deleteStageFunc(){
    let next = menuList && menuList.filter(item=>item.show_index === (stage+1));
    let nextStageType = next && next.length>0 && next[0].stage_type;
    const url = `/ci/pipelines/${disposeId}/${stageId}/delete_stage.json`;
    axios.delete(url,{
      params:{show_index:stage}
    }).then(result=>{
      if(result && result.data){
        getData(stage-1);
        setStageType(nextStageType);
      }else{
        props.showNotification("阶段删除失败!");
      }
    }).catch(error=>{})
  }

  // 确认提交
  function sureSubmit(){
    setLoading(true);
    let params = {
      branch: datas.branch,
      content:datas.content,
      filepath:'.trustie-pipeline.yml',
      message:'',
      sha:datas.sha || undefined,
      owner:owner,
      repo:projectsId
    }
    let url = `/${owner}/${projectsId}/update_trustie_pipeline.json`;
    axios.put(url,{
      ...params
    }).then(result=>{
      if(result){
        props.history.push({
          pathname:`/${owner}/${projectsId}/devops`,
          state:{open_devops:true} 
        });
      }
      setLoading(false);
    }).catch(error=>{
      console.log(error);
      setLoading(false);
    })
  }

  return(
    <div className="disposePanel">
      <Head />
      <WhiteBack style={{padding:"24px 30px"}}>
        <Spin spinning={spining}>
          <div style={{minHeight:"450px"}}>
            <Menus step={stage} checkDatas={checkDatas} changeStep={changestage} menuList={menuList} renameFunc={renameFunc} addFunc={addMenuFunc}/>
            {
              stageType === "init"  ? <Init stage_type={stageType} templates={templates} datas={datas} saveDatas={saveDatas} saveFunc={saveFunc}/>
              :
              stageType === "confirm" ? <Sure sureSubmit={sureSubmit} name={pipeLineName} datas={datas} saveFunc={saveFunc} loading={loading}/>
              :
              <Stage {...props} 
                stepName={stepName} 
                deleteStep={deleteStep} 
                stage_type={stageType} 
                templates={templates} 
                datas={datas} 
                deleteFunc={deleteStageFunc} 
                saveDatas={saveDatas} 
                saveFunc={saveFunc} 
                deleteFlag={menuList && menuList.length === 3}
              />
            }
          </div>
        </Spin>
      </WhiteBack>
    </div>
  )
}
export default disposePipeline;