import React, { forwardRef, useCallback, useState, useEffect } from "react";
import { Form, InputNumber , Select, Button , Checkbox , Radio } from "antd";
import Title from "../Component/Title";
import { Cancel } from "../Component/layout";
import axios from "axios";

export default Form.create()(
  forwardRef(({ form, match, history , showNotification }) => {
    const [ protect , setProtect ] = useState(false);
    const [ protects , setProtects ] = useState(false);
    const [ mergeOptions , setMergeOptions ] = useState(undefined);
    const [ approveOptions , setApproveOptions ] = useState(undefined);
    const [ options , setOptions ] =  useState(undefined);
    const [ list, setList ] = useState(undefined);

    const { projectsId, owner , branch } = match.params;
    const { getFieldDecorator, validateFields , setFieldsValue , getFieldsValue } = form;

    useEffect(() => {
      const url = `/${owner}/${projectsId}/collaborators.json`;
      axios.get(url).then((result) => {
        setList(result.data.members);
      })
      .catch((error) => {});
    }, []);

    useEffect(()=>{
      if(branch){
        // 需要设置分支保护的分支名，获取分支保护详情
        getGuardDetail(owner,projectsId,branch);
      }
    },[]);

    function getGuardDetail(owner,projectsId,branch){
      const url = `/${owner}/${projectsId}/protected_branches/${branch}/edit.json`;
      axios.get(url).then((result)=>{
        if(result){
          setProtect(result.data.protected);
          setProtects(result.data.protected);
          let protected_branch = result.data.protected_branch;

          if(protected_branch){
            let enable_push = protected_branch.enable_push_whitelist ? 2 : protected_branch.enable_push ? 1 : 0;
            
            setFieldsValue({
              ...protected_branch,
              enable_push
            })
            setOptions(enable_push);
            setMergeOptions(protected_branch.enable_merge_whitelist);
            setApproveOptions(protected_branch.enable_approvals_whitelist);
          }
        }
      }).catch(error=>{});
    }


    function saveBranchRule() {
      validateFields((error, values) => {
        if (!error) {
          let url = "";
          if(protects){
            // 为true则修改
            url = `/${owner}/${projectsId}/protected_branches/${branch}.json`;
          }else{
            // 否则是保存
            url = `/${owner}/${projectsId}/protected_branches.json`;
          }
          axios({
            method:!protects ? "post" : (protect ? "patch" : "delete"),
            url,
            params:
            {
              branch_name:branch,
              enable_push:values.enable_push !== 0 ?false : true,
              enable_push_whitelist:values.enable_push === 2 ? true : false,
              ...values
            }
          }).then(result=>{
            if(result){
              showNotification("保存成功！");
            }
          }).catch(error=>{})
        }
      });
    }

    const helper = useCallback(
      (label, name, rules, widget, className, isRequired,flag) => (
        <div className={className}>
          <span className={isRequired ? "required" : ""}>{label}</span>
          <Form.Item>
            {getFieldDecorator(name,  { rules, validateFirst: true , valuePropName:flag ? "checked":"value" })(widget)}
          </Form.Item>
        </div>
      ),
      []
    );
    // 启用分支保护
    function changeProtect(e){
      setProtect(e.target.checked);
    }
    // 切换保护选线
    function changeProtectOption(e){
      setOptions(e.target.value);
    }
    // 切换是否启用合并白名单
    function changeMergeOption(e){
      setMergeOptions(e.target.checked);
    }

    // 是否启用批准仅限列入白名单的用户或团队
    function changeWhitelistUsernameOption(e){
      setApproveOptions(e.target.checked);
    }
    return (
      <div style={{backgroundColor:"#fff"}}>
        <Title>新建'{branch}'保护分支规则</Title>
        <Form>
          <div style={{padding:"20px 30px"}}>
          {helper(
            "",
            "branchProtect",
            [],
            <Checkbox checked={protect} onChange={changeProtect}>
              启用分支保护<span className="color-grey-9 ml5 font-12">组织删除并限制Git推送和合并到分支</span>
            </Checkbox>,
            "setStyleRule"
          )}
          <div className="pl25 shortStyle">
            {helper(
              "",
              "enable_push",
              [],
              <Radio.Group disabled={!protect} onChange={changeProtectOption}>
                <Radio className="columsRadio" value={0}>
                  禁用推送<span className="color-grey-9 ml5 font-12">此分支不允许推送</span>
                </Radio>
                <Radio className="columsRadio" value={1}>
                  启用推送<span className="color-grey-9 ml5 font-12">任何拥有写访问权限的人将被允许推送到此分支(但不能强行推送)</span>
                </Radio>
                <Radio className="columsRadio" value={2}>
                  启用推送白名单<span className="color-grey-9 ml5 font-12">只有列入白名单的用户或团队才能被允许推送到此分支(但不能强行推送)</span>
                </Radio>
              </Radio.Group>,
              ""
            )}
            <div className="pl25 pt5 pb5 mb15">
              {helper(
                "",
                "push_whitelist_usernames",
                [],
                <Select
                  mode="multiple"
                  placeholder="搜索用户"
                  style={{ width: '100%' }}
                  disabled={!protect ||  (options ===undefined || options !== 2)}
                >
                  {list && list.map(item => (
                    <Select.Option key={item.id} value={item.login}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>,
                "setStyleRule"
              )}
            </div>
            {helper(
              "",
              "enable_merge_whitelist",
              [],
              <Checkbox disabled={!protect} checked={mergeOptions} onChange={changeMergeOption}>
                启用合并白名单<span className="color-grey-9 ml5 font-12">仅允许白名单用户或团队合并合并请求到此分支</span>
              </Checkbox>,
              "setStyleRule"
            )}
            <div className="pl25 pt5 pb5">
              {helper(
                "",
                "merge_whitelist_usernames",
                [],
                <Select
                  mode="multiple"
                  placeholder="搜索用户"
                  style={{ width: '100%' }}
                  disabled={!protect || !mergeOptions}
                >
                  {list && list.map(item => (
                    <Select.Option key={item.id} value={item.login}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>,
                "setStyleRule"
              )}
            </div>
            {helper(
              "",
              "enable_status_check",
              [],
              <Checkbox disabled={!protect}>
                启用状态检查
              </Checkbox>,
              "setStyleRule",false,true
            )}
            <div style={{display:"flex",alignItems:"center"}}>
              {helper(
                "所需的批准数",
                "required_approvals",
                [],
                <InputNumber min={0} style={{width:"140px"}}/>,
                "inlineFlex"
              )}
              <span className="color-grey-9 ml5 font-12">只允许合并有足够审核人数的拉取请求</span>
            </div>

            {helper(
              "",
              "enable_approvals_whitelist",
              [],
              <Checkbox name="enable_approvals_whitelist" disabled={!protect} checked={approveOptions} onChange={changeWhitelistUsernameOption}>
                批准仅限列入白名单的用户或团队<span className="color-grey-9 ml5 font-12">只有白名单用户或团队的审核才能计数 没有批准的白名单,任何有写访问权限的人的审核都将计数</span>
              </Checkbox>,
              "setStyleRule"
            )}
            <div className="pl25 pt5 pb5 mb15">
              {helper(
                "",
                "approvals_whitelist_usernames",
                [],
                <Select
                  mode="multiple"
                  placeholder="搜索用户"
                  style={{ width: '100%' }}
                  disabled={!protect || !approveOptions}
                >
                  {list && list.map(item => (
                    <Select.Option key={item.id} value={item.login}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>,
                "setStyleRule"
              )}
            </div>

            {helper(
              "",
              "block_on_rejected_reviews",
              [],
              <Checkbox disabled={!protect} name="block_on_rejected_reviews">
                拒绝审核阻止了合并<span className="color-grey-9 ml5 font-12">如果官方审查人员要求作出改动，即使有足够的批准，合并也不允许</span>
              </Checkbox>,
              "setStyleRule",false,true
            )}

            {helper(
              "",
              "dismiss_stale_approvals",
              [],
              <Checkbox disabled={!protect} name="dismiss_stale_approvals">
                取消过时的批准<span className="color-grey-9 ml5 font-12">当新的提交更改合并请求内容被推送到分支时，旧的批准将被撤销</span>
              </Checkbox>,
              "setStyleRule",false,true
            )}
            {helper(
              "",
              "require_signed_commits",
              [],
              <Checkbox disabled={!protect} name="require_signed_commits">
                需要签名提交
              </Checkbox>,
              "setStyleRule",false,true
            )}
            {helper(
              "",
              "block_on_outdated_branch",
              [],
              <Checkbox disabled={!protect} name="block_on_outdated_branch">
                如果拉取请求已经过时，阻止合并<span className="color-grey-9 ml5 font-12">当头部分支落后基础分支时，不能合并</span>
              </Checkbox>,
              "setStyleRule",false,true
            )}
          </div>
          
          <div className="df pb30 pt20">
            <Button type="primary" onClick={saveBranchRule}>
              保存
            </Button>
            <Cancel
              className="ml30"
              onClick={() => {
                history.push(`/projects/${owner}/${projectsId}/setting/branch`);
              }}
            >
              取消
            </Cancel>
          </div>
        </div>
        </Form>
      </div>
    );
  })
);
