import React, { useEffect, useState } from 'react';
import { Banner , AlignCenter } from '../../Component/layout';
import DeleteBox from '../../Component/DeleteModal/Index';
import './Index.scss';
import { Button , List, Pagination, Modal, Tooltip, Popover } from 'antd';
import axios from 'axios';

const limit = 15;
function Index(props) {
  const [ data , setData ] = useState(undefined);
  const [ page , setPage ] = useState(1);
  const [ total , setTotal ] = useState(1);
  const [ deleteId , setDeleteId ] = useState(undefined);
  const [ visible , setVisible ] = useState(false);
  const [ editVisible , setEditVisible ] = useState(false);
  const [ editId , setEditId ] = useState(undefined);
  const [ deleteWebHookModTitle, setDeleteWebHookModTitle] = useState(undefined);
  const [ deleteWebHookModSubTitle, setDeleteWebHookModSubTitle] = useState(undefined);
  const [ totalByUserCreate, setTotalByUserCreate] = useState(undefined);

  const { owner , projectsId } = props.match.params;
  const { projectDetail } = props;

  useEffect(()=>{
    if(projectDetail && document.title.indexOf('网络钩子-') === -1){
      const { author, name} = projectDetail;
      document.title = `网络钩子-${author.name}/${name}`;
    }
  }, [projectDetail])

  useEffect(()=>{
    if(owner && projectsId){
      getData();
    }
  },[owner,projectsId,page])

  function getData() {
    const url = `/${owner}/${projectsId}/webhooks.json`;
    axios.get(url,{
      params:{page,limit}
    }).then(result=>{
      if(result && result.data){
        const reg1 = new RegExp("https://(.*?)jianmuhub.com(.*?)");
        const reg2 = new RegExp("https://jianmu.gitlink.org.cn(.*?)");
        let totalByUserCreate = 0;
        result.data.webhooks.map(item=>{
          item.isJianMu = reg1.test(item.url) || reg2.test(item.url);
          !(reg1.test(item.url) || reg2.test(item.url)) && totalByUserCreate++;
        })
        setTotalByUserCreate(totalByUserCreate);
        setData(result.data.webhooks);
        setTotal(result.data.total_count);
      }
    }).catch(error=>{})
  }

  function deleteFunc(webhook) {
    setDeleteWebHookModTitle(webhook.isJianMu ? '请谨慎删除此Webhook' : '删除Webhook');
    setDeleteWebHookModSubTitle(webhook.isJianMu ? '该Webhook由流水线创建, 删除此Webhook后, 将导致本仓库相关流水线失效。确定要删除此Webhook?' :  `删除后未来事件将不会推送至此Webhook地址: ${webhook.url}`);
    setDeleteId(webhook.id);
    setVisible(true);
  }

  function onSuccess() {
    if(deleteId){
      const url = `/${owner}/${projectsId}/webhooks/${deleteId}.json`;
      axios.delete(url).then(result=>{
        if(result){
          props.showNotification("webhook删除成功！");
          if(page>1 && data.length === 1){
            setPage(page-1);
          }else{
            getData();
          }
          setVisible(false);
        }
      }).catch(error=>{})
    }
  }

  function addFunc() {
    if(totalByUserCreate >= 20){
      return props.showNotification("您创建的Webhook数量已达到上线！请删除部分Webhook以进行添加操作");
    }
    props.history.push(`/${owner}/${projectsId}/settings/webhooks/new`)
  }

  function gotoEditWebhook(webhook){
    props.history.push(`/${owner}/${projectsId}/settings/webhooks/${webhook.id}`);
    // if(webhook.isJianMu){
    //   setEditId(webhook.id);
    //   setEditVisible(true);
    // }else{
    //   props.history.push(`/${owner}/${projectsId}/settings/webhooks/${webhook.id}`);
    // }
  }

  return(
    <div>
      <DeleteBox
        visible={visible}
        onCancel={()=>setVisible(false)}
        onSuccess={onSuccess}
        title={deleteWebHookModTitle}
        content="您确定要删除此Webhook吗？"
        subTitle={deleteWebHookModSubTitle}
      />
      {/* <Modal
        visible={editVisible}
        onCancel={()=>{setEditVisible(false)}}
        title="请谨慎编辑此Webhook"
        width={"520px"}
        wrapClassName={"deleteBox"}
        centered={true}
        onOk={()=>{props.history.push(`/${owner}/${projectsId}/settings/webhooks/${editId}`)}}
      >
        <AlignCenter className="editWebhookModalTitle font-20 mb10"><i className="iconfont icon-shanchu_tc_icon mr10 font-36" style={{color: '#ca0002'}}></i>您确定要编辑此Webhook吗？</AlignCenter>
        <p className="task-hide-2" style={{WebkitLineClamp:5}}>该Webhook由流水线创建, 编辑此Webhook后, 将大概率导致本仓库相关流水线失效。确定要修改此Webhook?</p>
      </Modal> */}
      <Banner>
        <span>Webhooks(网络钩子)</span>
        <Button type="primary" size="large" onClick={addFunc}>添加Webhook</Button>
      </Banner>
      <div className="hookpanel">
        <p className="color-grey-3">每当特定事件（如push代码，合并请求被编辑）发生时，我们将通过webhook给您提供的远程URL发送post请求。您可以在我们的<a className="color-blue hoverLine" target="_blank" href="https://forum.trustie.net/forums/3408/detail">webhooks指南</a>中了解更多信息</p>
        {
          data && data.length> 0 &&
          <List>
            {data.map((i,k)=>{
              return(
                <List.Item key={k}>
                  <i className={`iconfont mr12 font-17 color-grey-6 ${i.isJianMu ? 'icon-gongzuoliuicon' : i.type === "softbot" ? 'icon-a-zu37 font-20' : 'icon-a-xuanzhongwebhookicon'}`}></i>
                  <span className="webName">{i.isJianMu ? <Tooltip title="该Webhook由流水线创建，请勿编辑或删除以防流水线失效"><span className="webName spanBox">{i.url}</span></Tooltip> : i.url}</span>
                  {!i.isJianMu && i.type !== "softbot" && <span>
                    <Button ghost type={"primary"} onClick={()=>{gotoEditWebhook(i)}}>编辑</Button>
                    <Button ghost className="ml20" type="danger" onClick={()=>{deleteFunc(i)}}>删除</Button>
                  </span>}
                  {(i.isJianMu || i.type === "softbot") && <span>
                    <Popover content={`该webhook由${i.isJianMu ? '流水线创建，不可编辑或删除，更改配置将导致流水线失效' : '已安装的Bot创建，请勿编辑或删除以防Bot失效'}`} title="无法编辑此Webhook" overlayClassName="disabledButPopover"><Button ghost type={"primary"} onClick={()=>{gotoEditWebhook(i)}}>查看</Button></Popover>
                    <Popover content={`该webhook由${i.isJianMu ? '流水线创建，不可编辑或删除，更改配置将导致流水线失效' : '已安装的Bot创建，请勿编辑或删除以防Bot失效'}`} title="无法删除此Webhook" overlayClassName="disabledButPopover"><Button className="ml20" type="danger" disabled>删除</Button></Popover>
                  </span>}
                </List.Item>
              )
            })}
          </List>
        }
        {
          total > limit &&
          <div className="edu-txt-center mt20 mb20">
            <Pagination current={page} total={total} onChange={e=>{setPage(e)}} pageSize={limit}/>
          </div>
        }
      </div>
    </div>
  )
}
export default Index;