import React, { useState, useEffect, useCallback } from "react";
import { Button, Checkbox, message, Modal, Radio, Select } from "antd";
import {getBotDetail, installMarketBot, judgeIsIntallBot} from '../api';
import { getImageUrl } from 'educoder';
import './index.scss';
import axios from "axios";
import RenderHtml from "../../components/render-html";
import { Link } from "react-router-dom";

function SoftBotDEtail(props){
  const {match:{params:{id}}, current_user, history, showLoginDialog} = props;
  const [detail, setDetail] = useState(undefined);
  const [visible, setVisible] = useState(false);
  const [checkValue, setCheckValue] = useState(1);
  const [selectValue, setSelectValue] = useState([]);
  const [options, setOptions] = useState([]);
  const [filterOption, setFilterOption] = useState([]);
  const [errTip, setErrTip] = useState(undefined);
  // 是否已安装此bot
  const [isInstall, setIsInstall] = useState(false);
  const [reload, setReload] = useState(undefined);

  useEffect(()=>{
    window.scrollTo(0,0);
    if(current_user && current_user.login){
      // 查询用户创建的仓库信息
      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);
          setFilterOption(projects);
          // judgeInstall需要根据用户具备管理权限的仓库去查询是否安装
          const repoIds = new Set();
          projects.map(item=>{
            const {id} = item;
            id && repoIds.add(id);
          })
          judgeInstall(repoIds);
        }
      }).catch(error=>{
        console.log(error);
      })}
  }, [])

  useEffect(()=>{
    getBotDetail({
      bot_id: id,
      user_id: 36480
    }).then(res=>{
      if(res && res.code === 200){
        const {is_public, developer_id, bot_name} = res.data;
        document.title=`SoftBot-${bot_name}`;
        const {user_id, login} = current_user
        if((login && !is_public && developer_id !== user_id) || (!login && !is_public)){
          message.error(Object.keys(res.data).length ? "私有Bot，无权限访问" : "Bot不存在");
          history.push('/softbot');
          return;
        }
        setDetail(res.data);
      }
    })
  }, [id])

  // 监听已选项selectValue的变化 改变下拉选择框的选择项
  useEffect(()=>{
    const ids = selectValue.map(item=>{return item.id});
    setFilterOption(options.filter(item=>!ids.includes(item.id)));
  }, [selectValue])

  // 判断用户是否安装此bot
  function judgeInstall(repoIds){
    judgeIsIntallBot({
      bot_id: id,
      repoIds: [...repoIds].toString()
    }).then(res=>{
      if(res && res.code === 200){
        const {install_repo_ids} = res.data;
        setIsInstall(!!install_repo_ids.length);
      }
    })
  }

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

  function click(){
    if(isInstall){
      props.history.push(`/settings/installbot/${id}`)
    }else{
      if(current_user && current_user.login){
        // 安装此bot弹窗
        setVisible(true);
      }else{
        showLoginDialog();
      }
    }
  }

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

  function okClick(){
    setErrTip(undefined);
    if(checkValue){
      // 至少选择一个仓库
      if(!selectValue.length){
        setErrTip('请至少选择一个仓库');
      }else{
        installBot();
      }
    }else{
      installBot();
    }
  }

  function installBot(){
    // 仓库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;
      });
    }
    const params = {
      login: current_user.login,
      user_id:current_user.user_id,
      bot_id:parseInt(id),
      state:1,
      store_list: checkValue ? selectValue.map(item=>{return item.id}) : options.map(item=>{return item.id}),
      repo_map,
      repo_owner_map
    }
    installMarketBot(params).then(res=>{
      if(res && res.code === 200){
        message.success("安装成功");
        setVisible(false);
        const repoIds = new Set();
        options.map(item=>{
          const {id} = item;
          id && repoIds.add(id);
        })
        judgeInstall(repoIds);
      }else{
        message.error("安装失败");
      }
    })
  }

  return <div className="softBotDetailBox">
    {detail && <div className="botDetailHead">
      <div className="botDetailHeadCont">
        <div className="botImgBg"><img src={getImageUrl(detail.logo)} alt="" className="botImg"></img></div>
        <div className="centerBox">
          <p className="font-24">{detail.bot_name}</p>
          <div className="userBox font-16">{detail.first_func && <span className="typeBox font-15 mr15">{detail.first_func}</span>}{detail.second_func && <span className="typeBox font-15 mr15">{detail.second_func}</span>}<a href={`/${detail.developer_login}`}>{detail.developer_name}</a></div>
          <div>{detail.market_desc}</div>
        </div>
        {((current_user && !current_user.login) || detail.is_public || (!detail.is_public && detail.developer_id === current_user.user_id))&&<Button type="primary" style={{width: '114px', height: '40px'}} className="font-15" onClick={click}>{isInstall ? '查看详情' : '安装此Bot'}</Button>}
      </div>
    </div>}
    <div className="detailIntroBox">
      <div className="detailIntroCont">
        <div className="detailIntroTitle font-20 mb10">Bot详细介绍</div>
        <RenderHtml value={detail && detail.bot_des} className="detailIntro font-15"/>
      </div>
    </div>
    <Modal
      title={<div><div className="installBotImgBox"><img src={getImageUrl(detail && detail.logo)} alt="" className="installBotImg"/></div><div className="font-18 installBotName">{detail && detail.bot_name}</div></div>}
      visible={visible}
      onOk={okClick}
      onCancel={()=>{setSelectValue([]);setVisible(false)}}
      className="installBotModal"
      width={735}
      closeIcon={<i className="iconfont icon-guanbi font-35 closeIconFont"></i>}
      footer={<Button type="primary" style={{width: '385px', height: '42px'}} className="font-15" onClick={okClick}>确认安装</Button>}
    >
      <div className="installTextBox">
        <div className="installTil font-18">安装位置</div>
        <Radio.Group onChange={(e)=>{setCheckValue(e.target.value)}} value={checkValue}>
          <Radio value={0} className="installRadioBox mt10 font-16">安装到所有仓库<br/><span className="font-15 installRadioBoxTip">安装到用户拥有的所有仓库中</span></Radio>
          <Radio value={1} className="installRadioBox mt15 font-16">安装到指定仓库<br/><span className={`font-15 installRadioBoxTip ${errTip ? 'errTip' :''}`}>请至少选择一个仓库</span></Radio>
        </Radio.Group>
        {checkValue === 1 && <Select
          placeholder="请选择仓库"
          value={selectValue.map(item=>{return item.id})}
          onChange={selectChange}
          className="installSelectBox"
          dropdownClassName="installDropdownClass"
          getPopupContainer={trigger => trigger.parentNode}
        >
          {filterOption.map(item=>(<Select.Option key={item.id} value={item.id}>{`${item.author && item.author.name}/${item.name}`}</Select.Option>))}
        </Select>}
        <div className="repoListBox">
          {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>
            <i className="iconfont icon-guanbi font-12 close ml30" onClick={()=>{deleteSelect(item)}}></i>
          </div>})}
        </div>
        <div className="installTil font-18 mt20 mb10">权限信息</div>
        {detail && <div className="mb10 font-16 greenCol"><i className={`mr8 iconfont ${detail.limit_and_events.juris_diction_code !== 2 ? 'icon-wanchenggouxuan' : 'icon-tishi1 font-16'}`}></i>代码库{detail.limit_and_events.juris_diction_code === 2 ? '无' : detail.limit_and_events.juris_diction_code === 1 ? '读写' : '只读'}权限</div>}
        {detail && <div className="mb10 font-16 greenCol"><i className={`mr8 iconfont ${detail.limit_and_events.juris_diction_pr !== 2 ? 'icon-wanchenggouxuan' : 'icon-tishi1 font-16'}`}></i>合并请求(PR){detail.limit_and_events.juris_diction_pr === 2 ? '无' : detail.limit_and_events.juris_diction_pr === 1 ? '读写' : '只读'}权限</div>}
        {detail && <div className="mb20 font-16 greenCol"><i className={`mr8 iconfont ${detail.limit_and_events.juris_diction_issue !== 2 ? 'icon-wanchenggouxuan' : 'icon-tishi1 font-16'}`}></i>疑修(Issue){detail.limit_and_events.juris_diction_issue === 2 ? '无' : detail.limit_and_events.juris_diction_issue === 1 ? '读写' : '只读'}权限</div>}
      </div>
    </Modal>
  </div>
}
export default SoftBotDEtail;