import { AutoComplete, Button, message, Modal } from "antd";
import React from "react";
import { useState, useEffect } from "react";
import { getImageUrl } from 'educoder';
import './index.scss';
import axios from "axios";
import { Link } from "react-router-dom";
import { deleteBot, transferBot, registerUpdateBot, downMarket, getMarketBotById, cancelTransferBot } from "../../../../../../softbot/api";
const { Option } = AutoComplete;

// 注册一个新的Bot
function AdvancedInformation(props){
  const {match, current_user, match:{params:{id}}, botDetail, setReload} = props;
  const [ visibleMakeOver, setVisibleMakeOver] = useState(false);
  const [ newId , setNewId] = useState(undefined);
  const [ source , setSource ] = useState(undefined);
  const [ searchKey , setSearchKey ] = useState(undefined);
  // bot删除0、公开1、私有2
  const [ type, setType] = useState(undefined);
  const [ visibleDelete, setVisibleDelete] = useState(false);
  // 转让bot错误提示
  const [makeOverErrortTip, setMakeOverErrortTip] = useState(undefined);
  // 是否已经上架
  const [isMarket, setIsMarket] = useState(false);
  // 上下架刷新
  const [marketReload, setMarketReload] = useState(undefined);

  useEffect(()=>{
    // 获取bot是否已经上架
    getMarketBotById({bot_id: id}).then(res=>{
      res && setIsMarket(res.code === 200);
    })
  }, [marketReload])

  useEffect(()=>{
    getUserList();
  },[searchKey])

  function getUserList(e){
    const url = `/users/list.json`;
    axios.get(url, {
      params: {
        search: searchKey,
      },
    }).then((result) => {
      if (result) {
        sourceOptions(result.data.users);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  };

  function changeInputUser(e){
    setSearchKey(e);
  };

  // 选择用户
  function selectInputUser(e, option){
    setNewId(option.props);
    setSearchKey(option.props.name);
  };

  function sourceOptions(userDataSource){
    const s = userDataSource && userDataSource.map((item, key) => {
      return (
        <Option
          key={key}
          value={`${item.user_id}`}
          login={`${item.login}`}
          name={item.username}
        >
          <img
            className="user_img radius"
            width="28"
            height="28"
            src={getImageUrl(`/${item && item.image_url}`)}
            alt=""
          />
          <span className="ml10" style={{ verticalAlign: "middle" }}>
            {item.username}
            <span className="color-grey ml10">({item.login})</span>
          </span>
        </Option>
      );
    });
    setSource(s);
  }

  // 确定转让点击函数
  function makeOver(){
    setMakeOverErrortTip(undefined);
    if(newId){
      const {value, login} = newId
      transferBot({
        login: current_user && current_user.login,
        user_id: current_user && current_user.user_id,
        bot_id: parseInt(id),
        transfer_to_user_id: parseInt(value),
        to_logn: login
      }).then(res=>{
        if(res && res.code === 200){
          message.success('操作成功');
          setSearchKey(undefined);
          setNewId(undefined);
          setVisibleMakeOver(false);
          setReload(Math.random());
        }
      })
    }else{
      setMakeOverErrortTip("请选择被转让者");
    }
  }

  // 删除/公开/私有/下架Bot弹框
  function submitModal(){
    if(type === '3'){
      // 下架市场
      downMarket(parseInt(id), {}).then(res=>{
        if(res && res.code === 200){
          message.success('下架成功');
          setVisibleDelete(false);
          setMarketReload(Math.random());
        }
      })
    }else if(type === '0'){
      // 删除bot
      const params = {
        login: current_user && current_user.login,
        user_id: current_user && current_user.user_id,
        bot_id: parseInt(id)
      }
      deleteBot(params).then(res=>{
        if(res && res.code === 200){
          message.success('删除成功');
          setVisibleDelete(false);
          props.history.push("/settings/mybot/configuration");
        }
      })
    }else{
      // 公开/私有bot
      const params = {
        ...botDetail,
        bot_id: parseInt(id),
        is_public: type === '1' ? 1 : 0,
        user_id: current_user && current_user.user_id,
      }
      registerUpdateBot(params).then(res=>{
        if(res && res.code === 200){
          setVisibleDelete(false);
          message.success("更改成功");
          setReload(Math.random());
        }else{
          setVisibleDelete(false);
          message.error(res.message);
        }
      })
    }
  }

  function cancelTra(){
    current_user && cancelTransferBot({
      bot_id: parseInt(id),
      login: current_user.login,
      user_id: current_user.user_id
    }).then(res=>{
      if(res && res.code === 200){
        message.success("操作成功");
        setReload(Math.random());
      }
    })
  }

  return <div className="advancedInformationBox">
    <div className="informationHead pb15">高级选项</div>
    {/* 提示：转让中状态 */}
    {botDetail && botDetail.is_transfer_success === 2 && <div className="transferBotStatus mt15"><i className="iconfont icon-yuyue-lishi-shijian font-18 mr5 ml10"></i>此Bot正在等待转移至<a href={`/${botDetail.transfer_to_login}`}>{botDetail.transfer_to_name +'  (' + botDetail.transfer_to_login +')'}</a></div>}
    <div className="disFlex itemBox">
      <div className="font-15">
        转让该Bot的所有权至其他用户
        <p className="grayBox font-14">转让可能会推迟，直到新的所有者批准转让</p>
      </div>
      {botDetail && (botDetail.is_transfer_success !== 2 ? <Button className="themeCorBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={()=>{setVisibleMakeOver(true)}}>转让所有权</Button> :
      <Button className="themeCorBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={cancelTra}>取消转让</Button>)}
    </div>
    <div className="disFlex itemBox">
      <div className="font-15">
        删除Bot
        <p className="grayBox font-14">该操作无法撤销，请慎重</p>
      </div>
      <Button className="dangerBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={()=>{setType('0');setVisibleDelete(true)}}>删除Bot</Button>
    </div>
    {botDetail && !botDetail.is_public && <div className="disFlex itemBox">
      <div className="font-15">
        私有Bot
        <p className="grayBox font-14">目前您的bot将不能被其他用户安装</p>
      </div>
      <Button className="themeCorBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={()=>{setType('1');setVisibleDelete(true)}}>公开此Bot</Button>
    </div>}
    {botDetail && !!botDetail.is_public && !isMarket && <div className="disFlex itemBox">
      <div className="font-15">
        公开Bot
        <p className="grayBox font-14">目前您的Bot所有用户都能安装</p>
      </div>
      <div>
        <Button type="primary" style={{width:"88px", height: '36px', padding: '0'}} className="mr20"><Link to={`/settings/mybot/configuration/${id}/advanced/putaway`}>上架市场</Link></Button>
        <Button className="themeCorBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={()=>{setType('2');setVisibleDelete(true)}}>私有此Bot</Button>
      </div>
    </div>}
    {botDetail && !!botDetail.is_public && isMarket && <div className="disFlex itemBox">
      <div className="font-15">
        公开Bot
        <p className="grayBox font-14">目前您的Bot所有用户都能安装</p>
      </div>
      <div>
        <Button type="primary" style={{width:"88px", height: '36px', padding: '0'}} className="mr20"><Link to={`/settings/mybot/configuration/${id}/advanced/putaway/edit`}>编辑</Link></Button>
        <Button className="themeCorBorBut" style={{width:"88px", height: '36px', padding: '0'}} onClick={()=>{setType('3');setVisibleDelete(true)}}>下架市场</Button>
      </div>
    </div>}
    {/* 转让bot弹框 */}
    <Modal
      className="themeHeadModal"
      width="430px"
      title="转让可能会推迟，直到新的所有者批准转让"
      visible={visibleMakeOver}
      maskClosable={false}
      footer={null}
      onCancel={()=>{setVisibleMakeOver(false);setMakeOverErrortTip(undefined)}}>
        <div className="font-15 mt5 mb10 makeOverTip">新的所有者账号</div>
        {makeOverErrortTip && <div className="font-15 mt5 mb10 makeOverErrorTip">{makeOverErrortTip}</div>}
        <AutoComplete
          dataSource={source}
          value={searchKey}
          style={{ width: '100%' }}
          onChange={changeInputUser}
          onSelect={selectInputUser}
          placeholder="请输入账户名称"
          allowClear
        />
        <Button type="primary" onClick={makeOver} className="makeOverSubmit" style={{width:"104px", height: '36px'}}>确认转让</Button>
    </Modal>
    {/* 删除/公开/私有Bot弹框 */}
    <Modal
      className="f8HeadModal"
      width="550px"
      title={`${type === '0' ? '删除' : type === '1' ? '公开' : type === '2' ? '私有' : '下架'}Bot`}
      visible={visibleDelete}
      maskClosable={false}
      footer={[
        <Button onClick={()=>{setVisibleDelete(false)}} className="mr30 grayBorBut whiteBackBut" style={{width:"104px", height: '36px'}}>取消</Button>,
        <Button className="redFontBut grayBorBut whiteBackBut" style={{width:"104px", height: '36px'}} onClick={submitModal}>确认{type === '0' ? '删除' : type === '1' ? '公开' : type === '2' ? '私有' : '下架'}</Button>
      ]}
      onCancel={()=>{setVisibleDelete(false)}}
    >
        <div className="font-16 titleTip mt20"><span className="circleRed font-18">!</span>您确定要{type === '0' ? '删除此Bot' : type === '1' ? `公开` : type === '2' ? '私有' : '下架'}{botDetail && botDetail.bot_name}吗？</div>
        <div className="deleteTip">{type === '0' ? `该操作无法撤销，将会永久删除${botDetail && botDetail.bot_name}` : type === '1' ? `公开后，任何用户都可以安装此Bot` : type === '2' ? '私有后，此Bot将只能被‘Bot开发者账户’安装' : '下架后，社区用户将无法在市场搜索到此Bot'}</div>
    </Modal>
  </div>
}
export default AdvancedInformation;