import React, { useEffect, useState } from "react";
import { Button, Form, Input, message } from "antd";
import MDEditor from '../../../../../../modules/tpm/challengesnew/tpm-md-editor';
import { Box } from "../../../../../Component/layout";
import miyao from '../../../../img/miyao.png';
import './index.scss';
import { Link } from "react-router-dom";
import { getImageUrl } from 'educoder';
import { registerUpdateBot } from "../../../../../../softbot/api";
import UploadImage from '../../../../../../forge/Team/Component/UploadImage.jsx';
import {CopyToClipboard} from 'react-copy-to-clipboard';
// 修改Bot
function BasicInformation(props){
  const {form, botDetail, match:{params:{id}}, setReload, current_user} = props;
  const { getFieldDecorator, validateFields , setFieldsValue } = form;
  const [ content , setContent ] = useState(undefined);
  const [ avatarVisible , setAvatarVisible ] = useState(false);
  const [ image , setImage ] = useState(undefined);
  const [ imageFlag , setImageFlag ] = useState(false);
  const [ imageId, setImageId] = useState(undefined);

  function getImage(image){
    setImageFlag(true);
    setImage(image);
  }

  function getImageId(id){
    setImageId(id);
  }

  function onContentChange(value){
    setContent(value);
  };

  useEffect(()=>{
    if(botDetail){
      setContent(botDetail.bot_des);
      setImage(botDetail.logo)
    }
  },[botDetail])

  // 修改Bot
  function submit(e){
    e.preventDefault();
    validateFields((err, fieldsValue)=>{
      if(err){
        return;
      }
      const params = {
        ...botDetail,
        ...fieldsValue,
        bot_id: parseInt(id),
        user_id: current_user && current_user.user_id,
      }
      registerUpdateBot(params).then(res=>{
        if(res && res.code === 200){
          message.success("更改成功");
          setReload(Math.random());
        }else{
          message.error(res.message);
        }
      })
    })
  }

  // 修改头像点击函数
  function saveUpdateImage(){
    if(imageId){
      const params = {
        ...botDetail,
        bot_id: parseInt(id),
        logo: '/api/attachments/'+imageId,
        user_id: current_user && current_user.user_id,
      }
      registerUpdateBot(params).then(res=>{
        if(res && res.code === 200){
          message.success("成功修改头像");
          setReload(Math.random());
        }
      })
    }else{
      message.error('请先上传图片');
    }
  }

  // webhooks校验
  function checkAddr(rule, value, callback) {
    let reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    if(!value){
      callback();
    }
    if (!reg.test(value)){
      callback("请输入有效的URL");
    }
    callback();
  }

  return <Box>
    {botDetail && <div className="basicInformationBox">
      <p className="informationHead pb15 mb10">注册信息</p>
      <div className="labelBox"><span className="label">Bot所有者</span><Link to={`/${current_user.login}`}>{current_user.username}</Link></div>
      <div className="labelBox"><span className="label">Bot ID</span>{id}</div>
      <div className="labelBox"><span className="label">客户端ID</span>{botDetail.client_id}</div>
      <div className="labelBox"><span className="label">主页URL</span><Link to={`/softbot/${id}`} className="blueSpan">{window.location.origin + `/softbot/${id}`}</Link></div>
      <div className="informationHead disFlex pb15 mt20 mb10">
        客户端密钥
      </div>
      <div className="disFlex miYaoBoxItem">
        <div className="disFlex">
          <img src={miyao} alt="" className="imgBox"/>
          <div className="copyBotInfo">
            <span className="font-13 oneLineSpan">{botDetail.client_secret}</span>
            <CopyToClipboard text={botDetail.client_secret} onCopy={()=>{message.success('复制成功')}}>
              <i className="iconfont icon-fuzhiicon ml5 font-16" style={{color: '#466aff'}}></i>
            </CopyToClipboard>
          </div>
        </div>
      </div>
      <div className="informationHead disFlex pb15 mt20 mb10">
      私钥
      </div>
      <div className="disFlex miYaoBoxItem">
        <div className="disFlex">
          <img src={miyao} alt="" className="imgBox"/>
          <div className="copyBotInfo">
            <span className="font-13 oneLineSpan">{botDetail.private_key}</span>
            <CopyToClipboard text={botDetail.private_key} onCopy={()=>{message.success('复制成功')}}>
              <i className="iconfont icon-fuzhiicon ml5 font-16" style={{color: '#466aff'}}></i>
            </CopyToClipboard>
          </div>
        </div>
      </div>
      <p className="informationHead mt30 pb15">Bot信息</p>
      <Form className="basicInformationForm mt10" onSubmit={submit}>
        <Form.Item label="Bot名称" className="width80 botItem">
          {getFieldDecorator("bot_name",{
            rules:[{required:true,message:"请输入Bot名称"}, {min: 3, max: 50, message: "Bot名称3-50个字符"}],
            initialValue: botDetail.bot_name
          })(
            <Input.TextArea placeholder="请输入Bot名称" maxLength={51} className="height36" autoSize={true}/>
          )}
        </Form.Item>
        <Form.Item label="详细介绍" className="botItem introduce">
          {getFieldDecorator("bot_des",{
            rules:[]
          })(
            <MDEditor
              placeholder={"请输入详细介绍"}
              height={500}
              mdID={"order-new-description"}
              initValue={content}
              onChange={onContentChange}
              className="mt20"
              isFocus={false}
            ></MDEditor>
          )}
        </Form.Item>
        <Form.Item label="Webhook地址" className="width80 botItem">
          {getFieldDecorator("webhook",{
            rules:[{required:true,message:"请输入Webhook地址"},{validator:checkAddr}],
            initialValue: botDetail.webhook
          })(
            <Input.TextArea placeholder="请输入Webhook地址" maxLength={200} className="height36" autoSize={true}/>
          )}
        </Form.Item>
        <Form.Item label="回调地址" className="width80 botItem">
          {getFieldDecorator("oauth_callback_url",{
            rules:[{required:true,message:"请输入回调地址"},{validator:checkAddr}],
            initialValue: botDetail.oauth_callback_url
          })(
            <Input.TextArea placeholder="请输入回调地址" maxLength={200} className="height36" autoSize={true}/>
          )}
        </Form.Item>
        <Form.Item className="mt30"><Button style={{width:"129px", height: '36px'}} type="primary" htmlType="submit">保存修改</Button></Form.Item>
      </Form>
    </div>}
    <div className="headPortraitBox">
      <UploadImage url={image && image.startsWith('/api/attachments/') ? getImageUrl(`${image}`) : image} getImage={getImage} getImageId = {getImageId}/>
      <Button className="themeCorBorBut ml5" onClick={saveUpdateImage}>保存头像</Button>
    </div>
  </Box>
}
export default Form.create()(BasicInformation);