import React, { forwardRef, useCallback, useEffect, useState } from 'react';
import { Form, Input, Radio, Checkbox, Switch, Button, Spin } from 'antd';
import { Banner, WhiteBack, AlignCenter, Cancel } from '../../Component/layout';
import styled from 'styled-components';
import axios from 'axios';
const TextArea = Input.TextArea;
const Div = styled.div`{
  padding:20px 30px;
}`
const OptionStyle = {
  lineHeight: "25px",
  height: '25px',
  display: 'block'
}
const addStyle = {
  ...OptionStyle,
  marginBottom: "7px"
}

export default Form.create()(
  forwardRef(({ form , match, showNotification, history, GroupDetail }) => {
    
    const [isSpin, setIsSpin] = useState(false);
    const [check_box, setCheckBox] = useState(false);
    const [switch_box, setSwtichBox] = useState([]);
    const [onwers, setOnwers] = useState(false);
    const [auth, setAuth] = useState("");
    const [ descNum , setDescNum ] = useState(0);
    const [switch_box_code, setSwtichBoxCode] = useState(false);
    const [switch_box_pull, setSwtichBoxPull] = useState(false);
    const [switch_box_issue, setSwtichBoxIssue] = useState(false);
    const [switch_box_release, setSwtichBoxRelease] = useState(false);
    const [switch_box_wiki, setSwtichBoxWiki] = useState(false);
    const { getFieldDecorator, validateFields, setFieldsValue } = form;
    const { OIdentifier, groupId } = match.params;

    useEffect(() => {
      if (GroupDetail) {
        setOnwers(GroupDetail.authorize === "owner");
        setAuth(GroupDetail.authorize);
        setCheckBox(GroupDetail.can_create_org_project)
        setSwtichBox(GroupDetail.units)
        setFieldsValue({
          ...GroupDetail,
          includes_all_project:GroupDetail.includes_all_project ? 1 :0
        })
        setDescNum(GroupDetail.description ? GroupDetail.description.length : 0);
      }
    }, [GroupDetail])

    useEffect(() => {
      if (switch_box && switch_box.length > 0) {
        setSwtichBoxCode(switch_checked("code"))
        setSwtichBoxPull(switch_checked("pulls"))
        setSwtichBoxIssue(switch_checked("issues"))
        setSwtichBoxRelease(switch_checked("releases"))
        setSwtichBoxWiki(switch_checked("wiki"))
      }
    }, [switch_box])

    const helper = useCallback(
      (label, name, rules, widget, isRequired, mbValue,className) => (
        <div className={className}>
          <span className={isRequired ? `required` : ``}>{label}</span>
          <Form.Item style={{ marginBottom: `${mbValue}px` || "20px" }}>
            {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
          </Form.Item>
        </div>
      ),
      []
    );
    function saveGroupFrom() {
      setIsSpin(true)
      validateFields((error, values) => {
        if (!error) {
          // values.unit_types = switch_box
          values.unit_types = ['code','pulls','issues','releases','wiki'];
          if (groupId) { // 表示编辑，否则为新建
            const url = `/organizations/${OIdentifier}/teams/${groupId}.json`;
            axios.put(url, {
              ...values,
              includes_all_project:values.includes_all_project === 1?true:false
            }).then(result => {
              if (result && result.data) {
                showNotification("基本设置更新成功！");
                history.push(`/${OIdentifier}/teams/${groupId}`);
              }
            }).catch(error => { })
          } else {
            const url = `/organizations/${OIdentifier}/teams.json`;
            axios.post(url, {
              ...values,
              includes_all_project:values.includes_all_project === 1?true:false
            }).then(result => {
              if (result && result.data) {
                showNotification("团队创建成功！");
                history.push(`/${OIdentifier}/teams/${result.data.id}`);
              }
            }).catch(error => { })
          }
        }
      });
      setIsSpin(false)
    }

    function change_check_box_status() {
      setCheckBox(!check_box)
    }

    function switch_checked(code) {
      return switch_box.indexOf(code) > -1
    }

    function switch_unit_types(checked, code) {
      const switch_index = switch_box.indexOf(code)
      if (checked) {
        switch_box.push(code)
      } else {
        switch_box.splice(switch_index, 1)
      }
    }

    function switch_code_types(checked, event) {
      switch_unit_types(checked, "code")
      setSwtichBoxCode(checked)
    }

    function switch_issue_types(checked, event) {
      switch_unit_types(checked, "issues")
      setSwtichBoxIssue(checked)
    }

    function switch_pull_types(checked, event) {
      switch_unit_types(checked, "pulls")
      setSwtichBoxPull(checked)
    }

    function switch_releas_types(checked, event) {
      switch_unit_types(checked, "releases")
      setSwtichBoxRelease(checked)
    }

    function switch_wiki_types(checked, event) {
      switch_unit_types(checked, "wiki");
      setSwtichBoxWiki(checked);
    }

    function cancelEdit(){
      if(groupId){
        history.push(`/${OIdentifier}/teams/${groupId}`);
      }else{
        history.push(`/${OIdentifier}`);
      }
    }

    function changeAuth(params) {
      setAuth(params.target.value)
    }

    function checkname(rule, value, callback){
      if(!value){
        callback();
      }
      if(value && !value.match(/^[a-zA-Z][a-zA-Z\d]{3,14}$/)){
        callback("只能使用英文字母和数字，以字母开头，长度为4到15个字符");
      }
      callback();
    }
    return (
      <Spin spinning={isSpin}>
        <WhiteBack className="mb30" style={{border:groupId?"none":"1px solid #eee"}}>
          <Banner>{groupId ? "基本设置" : "新建团队"}</Banner>
          <Div>
            <Form>
              {helper(
                '团队标识：',
                "name",
                [
                  { required: true, message: "请输入团队标识" },
                  {
                    validator:checkname
                  }
                ],
                <Input placeholder="请输入团队标识" disabled={onwers}/>, true
              )}
              {helper(
                '团队名称：',
                "nickname",
                [{ required: true, message: "请输入团队名称" }],
                <Input placeholder="请输入团队名称"/>, true
              )}
              <div className="pr">
                <span className="toprightNum">{descNum}/200</span>
                {helper(
                  <span className="mb5">团队描述：<span className="color-grey-8">(描述团队的目的或作用)</span></span>,
                  "description",
                  [],
                  <TextArea
                    placeholder="请输入团队描述"
                    maxLength={200}
                    onChange={(e)=>{setDescNum(e.target.value ? e.target.value.length :0)}}
                  />
                )}
              </div>
              
              {helper(
                '项目权限：',
                "includes_all_project",
                [],
                <Radio.Group>
                  <Radio value={0} style={addStyle}>指定项目<span className="color-grey-8 ml10">(团队成员将只能访问添加到团队的项目。 选择此项 <span className="color-grey-3">将不会</span> 自动删除已经添加的项目)</span></Radio>
                  <Radio value={1} style={OptionStyle}>所有项目<span className="color-grey-8 ml10">(团队可以访问所有项目。选择此选项将 <span className="color-grey-3">添加所有现有的</span> 项目到指定团队)</span></Radio>
                </Radio.Group>, false, 0,onwers ? "hide":""
              )}
              {helper(
                '',
                "can_create_org_project",
                [],
                <Checkbox checked={check_box} onChange={change_check_box_status} style={OptionStyle}>新建项目<span className="color-grey-8 ml10">(成员可以在组织中新建项目。创建者将自动获得新建的项目的管理员权限)</span></Checkbox>, false, 20,onwers ? "hide":""
              )}
              {/* {helper(
                '版本库权限：',
                "authorize",
                [],
                <Radio.Group onChange={changeAuth}>
                  <Radio value="read" style={addStyle}>读取权限<span className="color-grey-8 ml10">(成员可以查看和克隆团队项目)</span></Radio>
                  <Radio value="write" style={addStyle}>写入权限<span className="color-grey-8 ml10">(成员可以查看和推送提交到团队项目)</span></Radio>
                  <Radio value="admin" style={OptionStyle}>管理员权限<span className="color-grey-8 ml10">(成员可以拉取和推送到团队项目同时可以添加协作者)</span></Radio>
                </Radio.Group>, false, 20,onwers ? "hide":""
              )} */}
            </Form>
            {/* <div className={(auth!=="owner" && auth !=="admin") ? "" :"hide"}>
              <p className="required">允许访问项目单元：</p>
              <AlignCenter className="mb10">
                <Switch checked={switch_box_code} onClick={switch_code_types} />
                <span className="ml30 color-grey-3">代码库<span className="color-grey-8 ml15">(查看源码、文件、提交和分支)</span></span>
              </AlignCenter>
              <AlignCenter className="mb10">
                <Switch checked={switch_box_issue} onClick={switch_issue_types} />
                <span className="ml30 color-grey-3">任务<span className="color-grey-8 ml15">(组织 bug 报告、任务和里程碑)</span></span>
              </AlignCenter>
              <AlignCenter className="mb10">
                <Switch checked={switch_box_pull} onClick={switch_pull_types} />
                <span className="ml30 color-grey-3">合并请求<span className="color-grey-8 ml15">(启用合并请求和代码评审)</span></span>
              </AlignCenter>
              <AlignCenter className="mb10">
                <Switch checked={switch_box_release} onClick={switch_releas_types} />
                <span className="ml30 color-grey-3">版本发布<span className="color-grey-8 ml15">(跟踪项目版本和下载)</span></span>
              </AlignCenter>
              <AlignCenter className="mb20">
                <Switch checked={switch_box_wiki} onClick={switch_wiki_types} />
                <span className="ml30 color-grey-3">wiki<span className="color-grey-8 ml15">(编辑此仓库的相关文档说明)</span></span>
              </AlignCenter>
            </div> */}
             <Button type={"primary"} onClick={saveGroupFrom}>{groupId ? "更新团队设置" : "新建团队"}</Button>
            <Cancel className="ml30" onClick={() => cancelEdit()}><span>取消</span></Cancel>
          </Div>
        </WhiteBack>
      </Spin>
    )
  })
)