import React , { useState , useEffect } from 'react';
import { Spin , Pagination } from 'antd';
import { Blueback } from '../Component/layout';
import List from './Dispose/List';
import Head from './Dispose/head';
import axios from 'axios';
import PipelineName from './Dispose/PipelineName';

import styled from 'styled-components';

const Div = styled.div`{
  padding:24px 30px;
}`;
const limit = 15;
function Dispose(props){
  const [ spining , setSpining ] =  useState(true);
  const [ updateInfo , setUpdateInfo ] = useState(undefined);
  const [ list , setList ] = useState(undefined);
  const [ permission , setPermission ] = useState(undefined);
  const [ visible , setVisible ] = useState(false);
  const [ page , setPage ] = useState(1);
  const [ totalCount , setTotalCount ] = useState(0);
  const [ branchList , setBranchList ] =useState(undefined);


  const projectDetail = props.projectDetail;
  const current_user = props.current_user;
  let projectsId = props.match.params.projectsId; 
  let owner = props.match.params.owner; 

  // 获取用户的身份角色
  useEffect(()=>{
    if(projectDetail){
      setPermission(props.projectDetail.permission);
    }
  },[projectDetail])

  function Init(){
    const url = `/ci/pipelines/list.json`;
    axios.get(url,{
      params:{
        identifier:projectsId,owner,
        page,limit
      }
    }).then(result=>{
      if(result && result.data){
        setList(result.data.pipelines);
      }
      setSpining(false);
    }).catch(error=>{setSpining(false);})
  }

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

  useEffect(()=>{
    if(owner && projectsId){
      const url = `/${owner}/${projectsId}/branches.json`;
      axios.get(url).then(result=>{
        if(result && result.data){
          setBranchList(result.data);
        }
      }).catch(error=>{})
    }
  },[owner,projectsId])

  // 新增/编辑流水线
  function addNew(pipeline_name,id,branch,event){
    setVisible(true);
    setUpdateInfo(undefined);
    if(pipeline_name){
      let eventA = event.split(",");
      let l = {pipeline_name,id,branch,event:eventA}
      setUpdateInfo(l);
    }else{
      setUpdateInfo(undefined);
    }
  }

  function onOk(pipeline_name,updateId,branch,event){
    if(pipeline_name){
      let eventStr = "";
      for(var i = 0;i<event.length;i++){
        eventStr +=event[i]+",";
      }
      eventStr = eventStr.substring(0,eventStr.length-1);
      if(!updateId){
        // 新增
        const url = `/ci/pipelines.json`;
        axios.post(url,{
          pipeline_name,
          file_name:".trustie-pipeline.yml",
          repo:projectsId,branch,event:eventStr,owner
        }).then(result=>{
          setVisible(false);
          if(result && result.data){
            props.showNotification("流水线新增成功，请进行工作流配置！");
            props.history.push(`/projects/${owner}/${projectsId}/devops/dispose/${result.data.id}`);
          }else{
            props.showNotification("流水线新增失败，请稍后再试！");
          }
        }).catch(error=>{})
      }else{
        // 修改
        const url = `/ci/pipelines/${updateId}.json`;
        axios.put(url,{
          pipeline_name,repo:projectsId,branch,event:eventStr,owner
        }).then(result=>{
          if(result && result.data){
            setVisible(false);
            Init();
            props.showNotification("流水线名称更新成功！");
          }else{
            props.showNotification("流水线名称更新失败，请稍后再试！");
          }
        }).catch(error=>{})
      }
    }else{
      props.showNotification("请输入流水线名称！");
    }
  }

  // 删除
  function deleteFunc(id){
    const url = `/ci/pipelines/${id}.json`;
    axios.delete(url).then(result=>{
      if(result && result.data){
        props.showNotification("流水线删除成功！");
        Init();
      }
    }).catch(error=>{})
  }

  // 模板管理
  function toModalManage(){
    props.history.push(`/projects/${owner}/${projectsId}/devops/mould`);
  }

  // 参数管理
  function toparameter(){
    props.history.push(`/projects/${owner}/${projectsId}/devops/params`);
  }

  const operate = current_user && (permission && permission !== "Reporter");
  return(
    <Spin spinning={spining}>
      <PipelineName branchList={branchList} visible={visible} value={updateInfo} onCancel={()=>setVisible(false)} onOk={onOk}/>
      <div className="disposePanel">
        <Head manager={ operate ? toModalManage : undefined} parameter={operate ? toparameter :undefined}/>
        <Div>
          { operate &&  <Blueback onClick={()=>addNew(undefined,undefined)}>新增流水线</Blueback> }
          <div className="mt20 disposeList">
            <List list={list} operate={operate} projectsId={projectsId} owner={owner} showModal={addNew} deleteFunc={deleteFunc}/>
            {
              totalCount > limit &&
              <div className="mt20 pb20" style={{textAlign:'center'}}>
                <Pagination simple current={page} pageSize={limit} total={totalCount} onChange={(page)=>setPage(page)}/>
              </div>
            }
          </div>
        </Div>
      </div>
    </Spin>
  )
}
export default Dispose;