import React, { forwardRef, useState, useEffect } from "react";
import { Button, Checkbox, Col, Form, Input, message, Radio, Row, Select } from "antd";
import { Link } from "react-router-dom";
import MDEditor from '../../../../../modules/tpm/challengesnew/tpm-md-editor';
import './index.scss';
import { registerBot } from "../../../../../softbot/api";
const {Option} = Select;

function Disposition(props){
  const {form, current_user} = props;
  const { getFieldDecorator, validateFields , setFieldsValue, getFieldsValue } = form;
  const resource = [{value: 2, name: '无权限'}, {value: 0, name: '只读'}, {value: 1, name: '读写'}];

  const [ content , setContent ] = useState(undefined);
  const [ codeSelectValue , setCodeSelectValue ] = useState(resource[0].value);
  const [ prSelectValue , setPrSelectValue ] = useState(resource[0].value);
  const [ issueSelectValue , setIssueSelectValue ] = useState(resource[0].value);

  useEffect(()=>{
    document.title='注册新的Bot';
  }, [])

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

  function codeControl(e){
    setCodeSelectValue(e);
    return e;
  }

  function prControl(e){
    setPrSelectValue(e);
    return e;
  }

  function issueControl(e){
    setIssueSelectValue(e);
    return e;
  }

  // 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();
  }

  // 校验仓库访问权限
  function jurisDictionPrValidator(rule, value, callback){
    const {juris_diction_code, juris_diction_pr} = getFieldsValue();
    if(juris_diction_code === 2 && value === 2 && juris_diction_pr === 2){
      callback('请至少选择一个权限');
      return;
    }
    callback();
  }

  // 校验用户必选一个订阅事件
  function eventValidator(rule, value, callback){
    const {event_code, event_pr, event_issue} = getFieldsValue();
    if(event_code || event_pr || event_issue){
      callback();
    }else{
      callback("请至少选择一个订阅事件");
    }
  }

  // 注册新的bot
  function submit(e){
    e.preventDefault();
    validateFields((err, fieldsValue)=>{
      if(err){
        return;
      }
      const {bot_name, bot_des, webhook, is_public, juris_diction_code, juris_diction_pr, event_code, event_pr, oauth_callback_url, event_issue, juris_diction_issue} = fieldsValue;
      const param = {
        bot_name, bot_des, webhook, is_public,
        login: current_user && current_user.login,
        user_id: current_user && current_user.user_id,
        logo: `/api/attachments/${window.location.host !== 'www.gitlink.org.cn' ? 347246 : 412603}`,
        limit_and_events: {
          event_code: event_code ? event_code.toString() : '',
          event_pr: event_pr ? event_pr.toString() : '',
          event_issue: event_issue ? event_issue.toString(): '',
          juris_diction_code,
          juris_diction_pr,
          juris_diction_issue
        },
        oauth_callback_url
      }
      registerBot(param).then(res=>{
        if(res && res.code === 200){
          message.success('注册成功');
          props.history.push('/settings/mybot/configuration/'+res.data.bot_id);
        }else{
          message.success('注册失败: '+res.data);
        }
      })
    })
  }

  return <div className="createExploitBox">
    <div className="ceHead pb5 font-16 mb10">
      <Link to={`/settings/mybot`} className="blue-Purple">我的Bot</Link><span className="ceTitle font-18"><i className="iconfont icon-youjiantou ml5 mr5 font-12"></i>注册新的Bot</span>
    </div>
    <Form className="createExploitForm" onSubmit={submit}>
      <Form.Item label="Bot名称" className="width50 botItem">
        {getFieldDecorator("bot_name",{
          rules:[{required:true,message:"请输入Bot名称"}, {min: 3, max: 50, message: "Bot名称3-50个字符"}]
        })(
          <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"
          ></MDEditor>
        )}
      </Form.Item>
      <Form.Item label="Webhook地址" className="width50 botItem">
        {getFieldDecorator("webhook",{
          rules:[{required:true,message:"请输入Webhook地址"},{validator:checkAddr}]
        })(
          <Input.TextArea placeholder="请输入Webhook地址" maxLength={200} className="height36" autoSize={true}/>
        )}
      </Form.Item>
      <Form.Item label="回调地址" className="width50 botItem">
        {getFieldDecorator("oauth_callback_url",{
          rules:[{required:true,message:"请输入回调地址"},{validator:checkAddr}]
        })(
          <Input.TextArea placeholder="请输入回调地址" maxLength={200} className="height36" autoSize={true}/>
        )}
      </Form.Item>
      <div className="resourceTitle font-16 pb15 mb10">仓库访问权限</div>
      <Form.Item label="代码库权限" className="resourceBox botItem dashedBorder">
        <div className="color-99">代码库git推送、分支的创建与删除</div>
        {getFieldDecorator("juris_diction_code",{initialValue: resource[0].value, getValueFromEvent: codeControl})(
          <Select>
            {resource.map(item=>{return <Option value={item.value} key={item.value}>{item.name}</Option>})}
          </Select>
        )}
      </Form.Item>
      <div className="dashedBor"></div>
      <Form.Item label="合并请求(PR)权限" className="resourceBox botItem">
        <div className="color-99">合并请求的打开、关闭、编辑、分配</div>
        {getFieldDecorator("juris_diction_pr",{initialValue: resource[0].value, getValueFromEvent: prControl})(
          <Select>
            {resource.map(item=>{return <Option value={item.value} key={item.value}>{item.name}</Option>})}
          </Select>
        )}
      </Form.Item>
      <div className="dashedBor"></div>
      <Form.Item label="疑修(Issue)权限" className="resourceBox botItem">
        <div className="color-99">疑修的打开、关闭、编辑、分配、评论</div>
        {getFieldDecorator("juris_diction_issue",{rules:[{validator: jurisDictionPrValidator}],initialValue: resource[0].value, getValueFromEvent: issueControl})(
          <Select>
            {resource.map(item=>{return <Option value={item.value} key={item.value}>{item.name}</Option>})}
          </Select>
        )}
      </Form.Item>
      {(codeSelectValue !== resource[0].value || prSelectValue !== resource[0].value) && <div className="resourceTitle font-16 pb15 mb10">订阅事件</div>}
      {codeSelectValue !== resource[0].value && <Form.Item label="代码库事件" className="botItem width50 checkBox dashedBorder">
        {getFieldDecorator("event_code",{
          rules:[{validator: (rule, value, callback)=>{eventValidator(rule, value, callback)}}]
        })(
          <Checkbox.Group>
            <Row>
              <Col span={16}><Checkbox value={0}>推送<br/><span className="color-99">git推送到存储库</span></Checkbox></Col>
              <Col span={8}><Checkbox value={1}>创建<br/><span className="color-99">创建分支或标签</span></Checkbox></Col>
              <Col span={16}><Checkbox value={2}>删除<br/><span className="color-99">删除分支或标签</span></Checkbox></Col>
            </Row>
          </Checkbox.Group>
        )}
      </Form.Item>}
      {(codeSelectValue !== resource[0].value && prSelectValue !== resource[0].value) && <div className="dashedBor"></div>}
      {prSelectValue !== resource[0].value && <Form.Item label="合并请求事件" className="botItem width50 checkBox">
        {getFieldDecorator("event_pr",{
          rules:[{validator: (rule, value, callback)=>{eventValidator(rule, value, callback)}}]
        })(
          <Checkbox.Group>
            <Row>
              <Col span={16}><Checkbox value={3}>合并请求<br/><span className="color-99">合并请求被打开、被关闭或被编辑</span></Checkbox></Col>
              <Col span={8}><Checkbox value={4}>合并请求分配<br/><span className="color-99">合并请求被分配或取消分配</span></Checkbox></Col>
              <Col span={16}><Checkbox value={6}>合并请求被评论<br/><span className="color-99">合并请求评论被创建或删除</span></Checkbox></Col>
            </Row>
          </Checkbox.Group>
        )}
      </Form.Item>}
      {(codeSelectValue !== resource[0].value || prSelectValue !== resource[0].value) && issueSelectValue !== resource[0].value && <div className="dashedBor"></div>}
      {issueSelectValue !== resource[0].value && <Form.Item label="疑修事件" className="botItem width50 checkBox">
        {getFieldDecorator("event_issue",{
          rules:[{validator: (rule, value, callback)=>{eventValidator(rule, value, callback)}}]
        })(
          <Checkbox.Group>
            <Row>
              <Col span={16}><Checkbox value={7}>疑修<br/><span className="color-99">疑修已打开、已关闭、已重新打开或编辑</span></Checkbox></Col>
              <Col span={8}><Checkbox value={8}>疑修已指派<br/><span className="color-99">疑修已被指派或取消指派</span></Checkbox></Col>
              <Col span={16}><Checkbox value={9}>已标记疑修<br/><span className="color-99">疑修标记被更新或清除</span></Checkbox></Col>
              <Col span={8}><Checkbox value={10}>疑修评论<br/><span className="color-99">疑修评论被创建、编辑或删除</span></Checkbox></Col>
            </Row>
          </Checkbox.Group>
        )}
      </Form.Item>}
      <Form.Item label="公/私有设置" className="botItem resourceTitleItem">
        {getFieldDecorator("is_public",{initialValue: 0})(
          <Radio.Group>
            <Radio value={1}>公开</Radio>
            <Radio value={0}>私有</Radio>
          </Radio.Group>
        )}
      </Form.Item>
      <Form.Item><Button style={{width:"129px", height: '36px'}} type="primary" htmlType="submit">注册Bot</Button></Form.Item>
    </Form>
  </div>
}
export default Form.create()(forwardRef(Disposition));