import React, { useEffect, useState } from "react";
import { Button, message, Modal } from "antd";
import { Link } from "react-router-dom";
import { getImageUrl } from 'educoder';
import nullBot from '../../../../softbot/image/notBot.png';
import { getAllInstallBots, deleteInstallBot } from "../../../../softbot/api";
import './index.scss';
import axios from "axios";

// 配置已安装的bot
function DispositionBot(props){
  const {current_user} = props;
  const [botList, setBotList] = useState(undefined);
  const [delBotId, setDelBotId] = useState(undefined);
  const [visible, setVisible] = useState(false);
  const [options, setOptions] = useState(undefined);

  useEffect(()=>{
    window.scrollTo(0,0);
    document.title='Bot安装';
    // 查询用户创建的仓库信息
    current_user && axios.get(`/users/${current_user.login}/projects.json`,{
      params:{
        limit: 1000,
        page: 1,
        category:"admin"
      }
    }).then(result=>{
      if(result && result.data){
        const {projects} = result.data;
        setOptions(projects);
        // getAllInstallBots需要根据用户具备管理权限的仓库去查询是否安装
        const repoIds = new Set();
        projects.map(item=>{
          const {id} = item;
          id && repoIds.add(id);
        })
        getAllInsBots(repoIds)
      }
    }).catch(error=>{
      console.log(error);
    })
  }, [])

  function getAllInsBots(repoIds){
    getAllInstallBots({
      user_id: current_user && current_user.user_id,
      repoIds: [...repoIds].toString()
    }).then(res=>{
      if(res && res.code === 200){
        setBotList(res.data.install_bots);
      }
    })
  }

  function delInstallBot(){
    if(current_user && delBotId){
      const repoIds = new Set();
      options.map(item=>{
        const {id} = item;
        id && repoIds.add(id);
      })
      deleteInstallBot({
        login: current_user.login,
        user_id: current_user.user_id,
        bot_id: delBotId.bot_id,
        store_repo_ids: delBotId.store_repo_ids,
        password: ""
      }).then(res=>{
        if(res && res.code === 200){
          message.success('卸载成功');
          setDelBotId(undefined);
          setVisible(false);
          getAllInsBots(repoIds);
        }else{
          message.error(res.message);
        }
      })
    }
  }

  return <div>
    <div className="dispositionHead font-18">Bot安装</div>
    {/* bot列表显示区域 */}
    {botList && (botList.length > 0 ? <div className="setBotListBox">
      {botList.map((item, index)=>{return <div className="disBotItem" key={index}>
        <div className="botNameLeft">
          <img src={getImageUrl(item.logo)} alt="" className="imgBox mr20"/>
          <Link className="font-15 botName" to={`/settings/installbot/${item.bot_id}`}>{item.bot_name}</Link>
          <span className={`statusBox font-12 ml10 ${item.state === 0 ? '' : 'active'}`}>{item.state === 0 ? '挂起' : '启用'}</span>
        </div>
        <div>
          <Button className="themeCorBorBut" style={{width: '68px', height: '36px'}}><Link to={`/settings/installbot/${item.bot_id}`}>配置</Link></Button>
          <Button className="dangerBorBut ml20" style={{width: '68px', height: '36px'}} onClick={()=>{setDelBotId(item);setVisible(true)}}>卸载</Button>
        </div>
      </div>})}
    </div> : <div className="nullBotsBox mt80">
      <img src={nullBot} alt="" width={62}/>
      <p className="font-18 showBigTip">您当前暂未安装任何Bot</p>
      <div className="showTip font-14">您可以将Bot配置到仓库来处理一些繁杂的项目任务，比如自动化关闭疑修、合并请求等，以节约时间精力提升开发效率。快去<Link to="/softbot">  Bot市场  </Link>中挑选一个适合您项目的Bot吧!</div>
      <div className="borTip"></div>
      <Button type="primary" style={{width: '112px', height: '36px', padding: 0}}><Link to={'/softbot'}>去Bot市场逛逛</Link></Button>
    </div>)}
    <Modal
      className="f8HeadModal"
      width="485px"
      title="卸载Bot"
      visible={visible}
      maskClosable={false}
      footer={[
        <Button onClick={()=>{setVisible(false)}} className="mr30 grayBorBut whiteBackBut" style={{width:"104px", height: '36px'}}>取消</Button>,
        <Button className="redFontBut grayBorBut whiteBackBut" style={{width:"104px", height: '36px'}} onClick={delInstallBot}>确认卸载</Button>
      ]}
      onCancel={()=>{setVisible(false)}}
    >
        <div className="font-16 titleTip mt20"><span className="circleRed font-18">!</span>您确定要卸载此Bot吗？</div>
        <div className="deleteTip">卸载后，将回收所有分配给该bot的权限</div>
    </Modal>
  </div>
}
export default DispositionBot;