import React, { useEffect, useState } from "react";
import { Button, Checkbox, message, Radio, Select, Switch, Spin, Tooltip } from "antd";
import axios from "axios";
import { Link } from "react-router-dom";
import { getInstallBot, updateInstallBot } from "../../../../softbot/api";
import { getImageUrl } from 'educoder';
import './index.scss';
import '../exploit/index.scss';

function DispositionDetail(props){
  const {match:{params:{id}}, current_user, current_user:{login, user_id}} = props;
  const [checkValue, setCheckValue] = useState(0);
  const [selectValue, setSelectValue] = useState([]);
  const [botDetail, setBotDetail] = useState(undefined);
  const [options, setOptions] = useState(undefined);
  const [filterOption, setFilterOption] = useState([]);
  // bot状态
  const [botState, setBotState] = useState(true);
  const [error, setError] = useState(false);
  // 保存按钮loading效果
  const [saveLoading, setSaveLoading] = useState(false);

  // 获取bot详情
  useEffect(()=>{
    // 查询用户创建的仓库信息
    current_user && axios.get(`/users/${login}/projects.json`,{
      params:{
        limit: 1000,
        page: 1,
        category:"admin"
      }
    }).then(result=>{
      if(result && result.data){
        const {projects} = result.data;
        setOptions(projects);
        setFilterOption(projects);
        // getInstallBot需要根据用户具备管理权限的所有仓库去查询是否安装
        const repoIds = new Set();
        projects.map(item=>{
          const {id} = item;
          id && repoIds.add(id);
        })
        getInsBotDetail(repoIds);
      }
    }).catch(error=>{
      console.log(error);
    })
  }, [])
  
  // 监听已选项selectValue的变化 改变下拉选择框的选择项
  useEffect(()=>{
    const ids = selectValue.map(item=>{return item.id});
    options && setFilterOption(options.filter(item=>!ids.includes(item.id)));
  }, [selectValue])

  // 比较全部仓库和安装的仓库数组
  useEffect(()=>{
    if(botDetail && options){
      if(botDetail.store_id_list.length === options.length){
        setCheckValue(0);
      }else{
        setCheckValue(1);
        // 把已选择仓库筛选出来
        const {store_id_list} = botDetail;
        const allStoreId = options.map((item)=>{return item.id});
        let newMap = selectValue;
        store_id_list.map(item=>{
          if(allStoreId.includes(item)){
            newMap = newMap.concat(options.filter(i=>{return i.id === item})[0]);
          }
        })
        setSelectValue(newMap);
      }
    }
  }, [options, botDetail])

  function getInsBotDetail(repoIds){
    getInstallBot({
      login: login,
      user_id: user_id,
      bot_id: id,
      repoIds: [...repoIds].toString()
    }).then(res=>{
      if(res && res.code === 200){
        const {state, market_name} = res.data;
        document.title = `${market_name}-Bot配置`
        setBotState(state);
        setBotDetail(res.data);
      }
    })
  }

  function selectChange(e){
    let newMap = selectValue;
    newMap = newMap.concat(options.filter(i=>{return i.id === e})[0]);
    setSelectValue(newMap);
  }

  function deleteSelect(e){
    let newMap = selectValue;
    newMap = newMap.filter(item=>{return item.id !== e.id});
    setSelectValue(newMap);
  }

  function updateInsBot(){
    setError(false);
    if(checkValue && !selectValue.length){
      setError(true);
      return;
    }
    // 仓库id -> 仓库identifier
    const repo_map = {};
    // 仓库id -> 仓库拥有者login
    const repo_owner_map = {};
    if(checkValue){
      selectValue.map(item=>{
        const {author:{login}} = item;
        repo_map[item.id+""] = item.identifier;
        repo_owner_map[item.id+""] = login;
      });
    }else{
      options.map(item=>{
        const {author:{login}} = item;
        repo_map[item.id+""] = item.identifier;
        repo_owner_map[item.id+""] = login;
      });
    }
    setSaveLoading(true);
    current_user && updateInstallBot({
      bot_id: id,
      password: "",
      state: botState ? 1 : 0,
      store_list: checkValue ? selectValue.map(item=>{return item.id}) : options.map(item=>{return item.id}),
      login: login,
      user_id: user_id,
      repo_map,
      repo_owner_map,
      installed_store_list: botDetail.store_id_list
    }).then(res=>{
      if(res && res.code === 200){
        setSaveLoading(false);
        setSelectValue([]);
        const repoIds = new Set();
        options.map(item=>{
          const {id} = item;
          id && repoIds.add(id);
        })
        getInsBotDetail(repoIds);
        message.success('更改成功');
      }else{
        setSaveLoading(false);
        message.error(res.message);
      }
    })
  }

  return <Spin spinning={!Boolean(botDetail)}>
    <div className="dispositionDetailBox">
      <div className="oneLine mb30">
        {botDetail && <div className="oneLine">
          <img src={getImageUrl(botDetail.logo)} alt="" className="botImg imgBox"/>
          <div className="ml40 font-16">
            <div className="font-22">
              <a href={`/softbot/${id}`}>{botDetail && botDetail.market_name}</a>
              <span className={`font-12 ml10 statusBot myInstallBotStatus ${botDetail.is_public ? 'public' : 'private'}`}>{botDetail.is_public ? '公开' : '私有'}</span>
            </div>
            <a className="mr30 color88" href={`/${botDetail.register_login}`}>{botDetail && botDetail.register_name}</a>
            <span className="color88">{botDetail && botDetail.create_time}</span>
          </div>
        </div>}
        <Button style={{width: '53px', padding: '0'}} className="grayBorBut"><Link to={`/settings/installbot`}>返回</Link></Button>
      </div>
      {botDetail && <div className="mb10 greenCol font-16"><i className={`mr8 iconfont ${botDetail.limit_vo.juris_diction_code !== 2 ? 'icon-wanchenggouxuan' : 'icon-tishi1 font-16'}`}></i>代码库{botDetail.limit_vo.juris_diction_code === 2 ? '无' : botDetail.limit_vo.juris_diction_code === 1 ? '读写' : '只读'}权限</div>}
      {botDetail && <div className="mb20 greenCol font-16"><i className={`mr8 iconfont ${botDetail.limit_vo.juris_diction_pr !== 2 ? 'icon-wanchenggouxuan' : 'icon-tishi1 font-16'}`}></i>合并请求(PR){botDetail.limit_vo.juris_diction_pr === 2 ? '无' : botDetail.limit_vo.juris_diction_pr === 1 ? '读写' : '只读'}权限</div>}
      <div className="detailTil font-16">更改安装位置</div>
      <div>
        <Radio.Group onChange={(e)=>{setCheckValue(e.target.value)}} value={checkValue} disabled={botDetail && !botDetail.is_public && login !== botDetail.register_login}>
          <Radio value={0} className="radioBox mt10 font-16">安装到所有仓库<br/><span className="font-15 radioBoxTip">安装到用户拥有的所有仓库中</span></Radio>
          <Radio value={1} className="radioBox mt15 font-16">安装到指定仓库<br/><span className={`font-15 radioBoxTip ${error ? 'errorBot' : ''}`}>请至少选择一个仓库</span></Radio>
        </Radio.Group>
        {checkValue === 1 && <Select
          placeholder="请选择仓库名称"
          value={selectValue.map(item=>{return item.id})}
          onChange={selectChange}
          className="radioBox selectBox"
          disabled={botDetail && !botDetail.is_public && login !== botDetail.register_login}
        >
          {filterOption.map(item=>(<Select.Option key={item.id} value={item.id}>{`${item.author && item.author.name}/${item.name}`}</Select.Option>))}
        </Select>}
        {checkValue === 1 && selectValue.map((item, index)=>{return <div key={index} className="selectValueBox font-14">
          <i className="iconfont icon-daimakuicon1 font-14 mr5"></i>
          <Link className="selectValue" to={`/${item.author && item.author.login}/${item.identifier}`}>{`${item.author && item.author.name}/${item.name}`}</Link>
          {(botDetail && botDetail.is_public === 1 || (botDetail.is_public === 0 && login === botDetail.register_login)) && <i className="iconfont icon-guanbi font-12 close ml30" onClick={()=>{deleteSelect(item)}}></i>}
        </div>})}
      </div>
      <div className="detailTil font-16 mt30 mb10">更改Bot状态</div>
      <div className="ml25">
        {botDetail && <Switch defaultChecked = {botDetail.state} onChange={(checked)=>{setBotState(checked)}} disabled={botDetail && !botDetail.is_public && login !== botDetail.register_login}/>}
        <div className="mt10">
          <div className="font-15">{botState ? '启用' : '挂起'}</div>
          <span className='changeStatusTip'>{botState ? '开始使用该Bot，授予该Bot所需的仓库访问权限' : '暂停停止使用该bot，阻塞该bot拥有的仓库访问权限'}</span>
        </div>
      </div>
      {botDetail && !botDetail.is_public && login !== botDetail.register_login ? <Tooltip title="该bot为私有bot，仅bot开发者有权限更改"><Button type="primary" style={{width: '100px', height: '36px'}} className="mt30" disabled>保存</Button></Tooltip> : <Button type="primary" style={{width: '100px', height: '36px'}} className="mt30" onClick={updateInsBot} loading={saveLoading}>保存</Button>}
    </div>
  </Spin>
}
export default DispositionDetail;