import React, { useState, useEffect , useImperativeHandle ,forwardRef } from "react";
import { FlexAJ, AlignCenter , Banner } from "../Component/layout";
import { Table, Pagination, Popconfirm } from "antd";
import { truncateCommitId } from "../common/util";
import { getImageUrl } from 'educoder';
import axios from "axios";
import { Link } from 'react-router-dom';

import styled from 'styled-components';

const Div = styled.div`{
  padding:24px 30px;
}`;
const STATUS = [
  { name: "所有"},
  { name: "运行中", value: "running" },
  { name: "已撤销", value: "killed" },
  { name: "构建失败", value: "failure" },
  { name: "已完成", value: "success" },
];
const LIMIT = 15;
function Structure(props,ref){
  const [status, setStatus] = useState(undefined);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [data, setData] = useState(undefined);
  const [tableLoading, setTableLoading] = useState(true);

  let projectsId = props.match.params.projectsId;
  let owner = props.match.params.owner;
  let branch = props.match.params.branch;
  const permission = props.projectDetail && props.projectDetail.permission;

  useImperativeHandle(ref, () => ({
    changeVal: () => {
      setTableLoading(true);
      Init();
    }
  }))

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

  let current_user = props.current_user;
  function Init(status) {
    const url = `/${owner}/${projectsId}/builds.json`;
    axios.get(url,{
      params:{
        search:status,
        page,limit:LIMIT,branch
      }
    }).then((result) => {
      if (result && result.data) {
        let list = result.data.builds && result.data.builds.map((item, key) => {
          return {
            ...item,
            author:item.author && item.author.name,
            image_url:item.author && item.author.image_url,
            message: {
              branch: item.branch_target,
              message: item.message,
              sha: truncateCommitId(item.build_after_sha),
            },
            started: item.started || "--"
          };
        });
        setTotal(result.data.total_count);
        setData(list);
        setTableLoading(false);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  }

  function ChangeStatus(value) {
    setStatus(value);
    Init(value);
  }
  // 切换分页
  function ChangePage(page) {
    setPage(page);
  }
  function renderStatus() {
    return (
      <ul className="listNav">
        {STATUS.map((item, key) => {
          return (
            <li
              onClick={() => ChangeStatus(item.value)}
              className={status === item.value ? "active" : ""}
            >
              {item.name}
            </li>
          );
        })}
      </ul>
    );
  }
  function renderStatusBtn(status, number) {
    if (status === "error" || status === "success") {
      return "";
    }else if(status === "killed" || status === "failure"){
      return(
        <Popconfirm
          title="确认重新构建？"
          onConfirm={(e) => repeatSet(e,number)}
          onCancel={(e)=>{e.stopPropagation()}}
          cancelText="取消"
          okText="确定"
        >
          <a className="color-blue" onClick={(e)=>{e.stopPropagation()}}>重新构建</a>
        </Popconfirm>
      );
    } else {
      return (
        <Popconfirm
          title="确认撤销构建？"
          onConfirm={(e) => cancelSet(e,number)}
          onCancel={(e)=>{e.stopPropagation()}}
          cancelText="取消"
          okText="确定"
        >
          <a className="color-red" onClick={(e)=>{e.stopPropagation()}}>撤销构建</a>
        </Popconfirm>
      );
    }
  }
  // 重新构建
  function repeatSet(e,number) {
    e.stopPropagation();
    setTableLoading(true);
    const url = `/${owner}/${projectsId}/builds/${number}/restart.json`;
    axios.post(url).then((result) => {
      if (result) {
        props.showNotification("工作流正在重新构建！");
        Init();
      }
    })
    .catch((error) => {
      console.log(error);
    });
  }

  // 撤销构建
  function cancelSet(e,number) {
    e.stopPropagation();
    setTableLoading(true);
    const url = `/${owner}/${projectsId}/builds/${number}/stop.json`;
    axios.delete(url).then((result) => {
      if (result) {
        props.showNotification("撤销构建成功！");
        Init(projectsId);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  }

  function renderTableStatus(status) {
    switch (status) {
      case "running":
        return (
          <span className="statusTag running">
            <i className="iconfont icon-yunhangzhong"></i>运行中
          </span>
        );
      case "failure": case 'error':
        return (
          <span className="statusTag failed">
            <i className="iconfont icon-weitongguo"></i>未通过
          </span>
        );
      case "success":
        return (
          <span className="statusTag pass">
            <i className="iconfont icon-yitongguo"></i>已通过
          </span>
        );
      case 'killed':
        return (
          <span className="statusTag killed">
            <i className="iconfont icon-weitongguo"></i>已撤销
          </span>
        );
      default:
        return (
          <span className="statusTag Preparing">
            <i className="iconfont icon-zhunbeizhong"></i>准备中
          </span>
        );
    }
  }

  function clickRows(event,e){
    props.history.push(`/${owner}/${projectsId}/devops/${e.number}/detail`);
  }
  const column = [
    {
      title: "序号",
      dataIndex: "number",
      key: "number",
      width: "8%",
      render: ( value, item, key) => {
        return <span>#{value}</span>;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      width: "12%",
      render: (value, item, key) => {
        return renderTableStatus(value);
      },
    },
    {
      title: "构建人",
      dataIndex: "author",
      key: "author",
      width: "12%",
      align: "center",
    },
    {
      title: "提交信息",
      dataIndex: "message",
      key: "message",
      width: "30%",
      render: (value, item, key) => {
        let meg = item.message;
        return (
          <React.Fragment>
            <div>
              {meg.branch && (
                <span className="mr10 color-grey-8">
                  <i className="iconfont icon-fenzhi1 font-16 mr5"></i>分支
                  {meg.branch}
                </span>
              )}
              {meg.sha && <span className="color-orange">{meg.sha}</span>}
            </div>
            <AlignCenter>
              <img style={{borderRadius:"50%",marginRight:"10px",width:"25px",height:"25px"}} alt="" src={`${item.image_url && getImageUrl(`/${item.image_url}`)}`} />
              <div className="task-hide ml5" style={{ maxWidth: "300px" }}>
                {meg.message}
              </div>
            </AlignCenter>
          </React.Fragment>
        );
      },
    },
    {
      title: "开始时间",
      dataIndex: "started",
      key: "started",
      width: "15%",
      render: (value, item, key) => {
        return <span>{value || "--"}</span>;
      },
    },
    {
      title: "运行时间",
      dataIndex: "duration_time",
      key: "duration_time",
      width: "15%",
      render: (value, item, key) => {
        return <span>{value || "--"}</span>;
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render: (value, item, key) => {
        if(permission === "Admin" || permission === "Owner"){
          return renderStatusBtn(item.status, item.number);
        }else{
          return "--";
        }
      },
    },
  ];
  return (
    <div className="disposePanel">
      <Banner>
        <FlexAJ>
          <span>构建列表</span>
          <Link to={{pathname:`/${owner}/${projectsId}/devops`,state:{open_devops:true}}} className="font-15 color-grey-9">返回</Link>
        </FlexAJ>
      </Banner>
      <Div>
        <div className="listPart">
          <FlexAJ>
            {renderStatus()}
            <a onClick={()=>Init(status)} className="color-red font-16">刷新</a>
          </FlexAJ>
          <Table
            onRow={(record,index)=>{
              return{
                onClick:(event)=>clickRows(event,record)
              }
            }}
            columns={column}
            className="normalTable"
            dataSource={data}
            pagination={false}
            loading={tableLoading}
          ></Table>
          {total > LIMIT ? 
            <div style={{ textAlign: "center", margin: "30px 50px" }}>
              <Pagination
                showQuickJumper
                defaultCurrent={page}
                total={total}
                pageSize={LIMIT}
                onChange={ChangePage}
              ></Pagination>
            </div> 
            : 
          "" }
        </div>
      </Div>
    </div>
  );
};
export default forwardRef(Structure);
