import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Input , Form , Select , Checkbox , Button , Spin , AutoComplete } from 'antd';
import { Base64 } from 'js-base64';

import '../css/index.scss';
import './new.css'

import axios from 'axios';
const Option = Select.Option;
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      preType: "0",
      languageValue: "0",
      gitignoreType: "0",
      LicensesType: "0",

      mirrorCheck:false,

      CategoryList: undefined,
      LanguageList: undefined,
      GitignoreList: undefined,
      LicensesList: undefined,
      OwnerList: undefined,
      isSpin: false,

      project_language_id: undefined,
      project_category_id: undefined,
      license_id: undefined,
      ignore_id: undefined,
      owners_id:undefined,
      owners_name:undefined,

      project_language_list: undefined,
      project_category_list: undefined,
      license_list: undefined,
      ignore_list: undefined,

      owners_list:undefined,

      project_language_name: undefined,
      project_category_name: undefined,
      license_name: undefined,
      ignore_name: undefined,
      descNum:0
    }
  }
  componentDidMount = () => {
    // 获取拥有者列表
    this.getOwner();
    // 获取项目类别
    this.getCategory();
    // 获取项目语言
    this.getLanguage();
    // 获取Gitignore
    this.getGitignore();
    // 获取开源许可证
    this.getLicenses();
  }
  componentDidUpdate=(prevPros)=>{
    if(prevPros && this.props && !this.props.checkIfLogin()){
      this.props.history.push("/403")
      return
    }
  }

  getOwner=()=>{
    const { OIdentifier } = this.props.match.params;
    const url = `/owners.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        let owner = result.data.owners;
        if(OIdentifier){
          owner = owner.filter(item=>item.name === OIdentifier);
          this.props.form.setFieldsValue({
            user_id:OIdentifier
          })
          owner && this.setState({
            owners_id:owner[0].id,
            owners_name:owner[0].name
          })
        }
        this.setOptionsList(owner, 'owners');
        this.setState({
          OwnerList: owner,
        })
      }
    }).catch(error=>{})
  }

  getCategory = () => {
    const url = `/project_categories.json`
    axios.get(url).then((result) => {
      if (result) {
        this.setOptionsList(result.data.project_categories, 'project_category');
        this.setState({
          CategoryList: result.data.project_categories
        })
      }
    }).catch((error) => { })
  }

  getLanguage = () => {
    const url = `/project_languages.json`
    axios.get(url).then((result) => {
      if (result) {
        this.setOptionsList(result.data.project_languages, 'project_language')
        this.setState({
          LanguageList: result.data.project_languages
        })
      }
    }).catch((error) => { })
  }

  getGitignore = () => {
    const url = `/ignores.json`
    axios.get(url).then((result) => {
      if (result) {
        this.setOptionsList(result.data.ignores, 'ignore');
        this.setState({
          GitignoreList: result.data.ignores
        })
      }
    }).catch((error) => { })
  }

  getLicenses = () => {
    const url = `/licenses.json`
    axios.get(url).then((result) => {
      if (result) {
        this.setOptionsList(result.data.licenses, 'license');
        this.setState({
          LicensesList: result.data.licenses
        })
      }
    }).catch((error) => { })
  }

  // 设置option
  setOptionsList = (data, _head, name) => {
    if (data && data.length > 0) {
      let _data = data;
      if (name) {
        _data = data.filter(item => item.name.toLowerCase().indexOf(name.toLowerCase()) > -1);
      }
      let list = _data && _data.map((item) => (
        <Option key={item.id} value={item.name}>
          {item.name}
        </Option>
      ));
      this.setState({
        [_head + "_list"]: list
      })
    }
  }

  subMitFrom = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({
          isSpin: true
        })
        const { projectsType } = this.props.match.params;
        const { project_language_id, project_category_id, license_id, ignore_id , owners_id , owners_name } = this.state;
        const decoderPass = Base64.encode(values.password);
        const url = (projectsType && projectsType === "mirror") ? "/projects/migrate.json" : "/projects.json";
        axios.post(url, {
          ...values,
          auth_password:decoderPass,
          project_language_id,
          project_category_id,
          license_id,
          ignore_id,
          user_id:owners_id
        }).then((result) => {
          if (result) {
            if (result.data.id) {
              this.setState({
                isSpin: false
              })
              this.props.showNotification(`${projectsType && projectsType === "mirror" ? "镜像" : "托管"}项目创建成功!`);
              this.props.history.push(`/projects/${owners_name}/${result.data.identifier}`);
            }
          }
        }).catch((error) => {
          this.setState({
            isSpin: false
          })
          console.log(error);
        })
      } else {
        this.setState({
          isSpin: false
        })
      }
    })
  }

  ChangePlatform = (value, e, name, list) => {
    this.setOptionsList(list, name, value)
    this.setState({
      [name + "_id"]: e.key,
      [name + "_name"]: value,
    })
  }

  blurCategory = (value, list, name) => {
    let filter = list && list.filter(item => item.name === value);
    if (!filter || filter.length === 0) {
      this.props.form.setFieldsValue({
        [name]: undefined
      })
      this.setState({
        [name + "_name"]: undefined,
        [name + "_id"]: undefined
      })
      this.setOptionsList(list, name);
    }
  }

  checkId = (rule, value, callback, list, title) => {
    let filter = list.filter(item => item.name === value);
    if(!value){
      callback();
    }
    if (filter && filter.length > 0) {
      callback();
    } else {
      callback('请在下拉选项中选择正确的' + title + "!");
    }
    callback();
  }

  changeMirrorCheck=()=>{
    const { mirrorCheck } = this.state;
    this.setState({
      mirrorCheck:!mirrorCheck
    })
  }

  ChangeAddr=(e)=>{
    let value = e.target.value;
    if(value.indexOf("/") > -1){
      let arr = value.split("/");
      let first = arr[arr.length-1];
      if(first.indexOf(".git") > -1){
        let second = first.split('.')[0];
        if(!second)return;
        this.props.form.setFieldsValue({
          repository_name:second
        })
      }
    }
  }

  changeDesc=(e)=>{
    let value = e.target.value;
    this.setState({
      descNum:value ? value.length :0
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    // 项目类型：deposit-托管项目，mirror-镜像项目
    const { projectsType } = this.props.match.params;

    const {
      CategoryList,
      LanguageList,
      GitignoreList,
      LicensesList,
      isSpin,
      owners_list,
      OwnerList,

      project_language_list,
      project_category_list,
      license_list,
      ignore_list,

      mirrorCheck,

      descNum
    } = this.state;
    return (
      <div className="main back-white" style={{padding:"0px",border:"none"}}>
        <div className="newPanel">
          <div className="newPanel_title">创建{projectsType && projectsType === "mirror" ? "镜像" : "托管"}项目</div>
          <Spin spinning={isSpin}>
            <Form>
              <div className="newPanel_content">
                <Form.Item
                  label="拥有者"
                >
                  {getFieldDecorator('user_id', {
                    rules: [{
                      required: true, message: '请选择拥有者'
                    },{
                      validator:(rule, value, callback) => this.checkId(rule, value, callback, OwnerList, '拥有者')
                    }],
                  })(
                    <AutoComplete 
                      placeholder="请选择拥有者"
                      onChange={(value, e) => this.ChangePlatform(value, e, 'owners', OwnerList)}
                      className="plateAutoComplete"
                      onBlur={(value) => this.blurCategory(value, OwnerList, "owners")}
                      >
                      {owners_list}
                    </AutoComplete>
                  )}
                </Form.Item>
                {
                  projectsType && projectsType === "mirror" &&
                  <React.Fragment>
                    <Form.Item
                      label="镜像版本库地址"
                      style={{ marginBottom: "0px" }}
                    >
                      {getFieldDecorator('clone_addr', {
                        rules: [{
                          required: true, message: '请填写镜像版本库地址'
                        }],
                      })(
                        <Input placeholder="输入需要同步到本项目的镜像版本库地址" onChange={this.ChangeAddr} />
                      )}
                    </Form.Item>
                    <p className="formTip color-orange">示例：https://github.com/facebook/reack.git</p>
                  </React.Fragment>
                }
                {
                  projectsType && projectsType === "mirror" &&
                  <React.Fragment>
                    <p className="mt10 mb10 color-grey-3 pointer" onClick={this.changeMirrorCheck}>需要授权验证<i className={mirrorCheck?"iconfont icon-xiajiantou font-13 ml10 color-grey-8":"iconfont icon-youjiantou font-13 ml10 color-grey-8"}></i></p>
                    {
                      mirrorCheck &&
                      <div className="df mb20" style={{alignItems:'center'}}>
                        <span className="mr10">用户名</span>
                        <Form.Item
                          style={{ marginBottom: "0px" }}
                          label=""
                        >
                          {getFieldDecorator('auth_username', {
                            rules: [],
                          })(
                            <Input placeholder="请输入对应平台的登录用户名" style={{width:"240px"}} />
                          )}
                        </Form.Item>
                        <span className="mr10">密码</span>
                        <Form.Item
                          style={{ marginBottom: "0px" }}
                          label=""
                        >
                          {getFieldDecorator('password', {
                            rules: [],
                          })(
                            <Input placeholder="请输入对应平台的登录密码" type="password" style={{width:"240px"}}/>
                          )}
                        </Form.Item>
                      </div>
                    }
                  </React.Fragment>
                }
                <Form.Item
                  label="项目名称"
                >
                  {getFieldDecorator('name', {
                    rules: [{
                      required: true, message: '请填写项目名称'
                    }],
                  })(
                    <Input placeholder="例如：团队协作方法与研究" maxLength={50}/>
                  )}
                </Form.Item>
                <div className="pr">
                  <span className="toprightNum">{descNum}/200</span>
                  <Form.Item
                    label="项目简介"
                  >
                    {getFieldDecorator('description', {
                      rules: [{
                        required: true, message: '请填写项目简介'
                      }],
                    })(
                      <Input.TextArea maxLength={200} placeholder="项目的介绍" autoSize={{ minRows: 2, maxRows: 6 }} onChange={this.changeDesc}/>
                    )}
                  </Form.Item>
                </div>
                <Form.Item
                  label="仓库名称"
                >
                  {getFieldDecorator('repository_name', {
                    rules: [{
                      required: true, message: '请填写仓库名称'
                    }],
                  })(
                    <Input placeholder="仓库名称请使用与项目相关的英文关键字" maxLength={100} />
                  )}
                </Form.Item>
                <Form.Item
                  label="项目类别"
                >
                  {getFieldDecorator('project_category', {
                    rules: [{
                      required: true, message: '请选择大类别',
                    }, {
                      validator: (rule, value, callback) => this.checkId(rule, value, callback, CategoryList, '项目类别')
                    }],
                  })(
                    <AutoComplete
                      placeholder="请选择项目类别"
                      onChange={(value, e) => this.ChangePlatform(value, e, 'project_category', CategoryList)}
                      className="plateAutoComplete"
                      onBlur={(value) => this.blurCategory(value, CategoryList, "project_category")}
                    >
                      {project_category_list}
                    </AutoComplete>
                  )}
                </Form.Item>
                <Form.Item
                  label="项目语言"
                >
                  {getFieldDecorator('project_language', {
                    rules: [{
                      required: true, message: '请选择项目语言'
                    }, {
                      validator: (rule, value, callback) => this.checkId(rule, value, callback, LanguageList, '项目语言')
                    }],
                  })(
                    <AutoComplete
                      placeholder="请选择项目语言"
                      onChange={(value, e) => this.ChangePlatform(value, e, 'project_language', LanguageList)}
                      className="plateAutoComplete"
                      onBlur={(value) => this.blurCategory(value, LanguageList, "project_language")}
                    >
                      {project_language_list}
                    </AutoComplete>
                  )}
                </Form.Item>
                {
                  (projectsType === "deposit" || !projectsType) &&
                  <React.Fragment>
                    <Form.Item
                      label=".gitignore"
                    >
                      {getFieldDecorator('ignore', {
                        rules: [{
                          required: true, message: '请选择gitignore'
                        }, {
                          validator: (rule, value, callback) => this.checkId(rule, value, callback, GitignoreList, 'gitignore')
                        }],
                      })(
                        <AutoComplete
                          placeholder="请选择gitignore，用来定义哪些文件不需要添加到版本管理中"
                          onChange={(value, e) => this.ChangePlatform(value, e, 'ignore', GitignoreList)}
                          className="plateAutoComplete"
                          onBlur={(value) => this.blurCategory(value, GitignoreList, "ignore")}
                        >
                          {ignore_list}
                        </AutoComplete>
                      )}
                    </Form.Item>
                    <Form.Item
                      label="开源许可证"
                    >
                      {getFieldDecorator('license', {
                        rules: [{
                          required: true, message: '请选择开源许可证'
                        }, {
                          validator: (rule, value, callback) => this.checkId(rule, value, callback, LicensesList, '开源许可证')
                        }],
                      })(
                        <AutoComplete
                          placeholder="请选择开源许可证"
                          onChange={(value, e) => this.ChangePlatform(value, e, 'license', LicensesList)}
                          className="plateAutoComplete"
                          onBlur={(value) => this.blurCategory(value, LicensesList, "license")}
                        >
                          {license_list}
                        </AutoComplete>
                      )}
                    </Form.Item>
                  </React.Fragment>
                }
                <Form.Item
                  label="可见性"
                  style={{ margin: "0px" }}
                  className="privatePart"
                >
                  {getFieldDecorator('private')(
                    <Checkbox value="limit">将项目设为私有<span className="ml15 font-13 color-grey-9">(只有项目所有人或拥有权限的项目成员才能看到)</span></Checkbox>
                  )}
                </Form.Item >
                {
                  projectsType && projectsType === "mirror" &&
                  <Form.Item
                    label="迁移类型："
                    style={{ margin: "0px" }}
                    className="privatePart"
                  >
                    {getFieldDecorator('is_mirror')(
                      <Checkbox value="limit">该仓库将是一个<span className="color-blue">镜像</span>(设置为镜像后，该项目为只读，不能进行push等相关操作)</Checkbox>
                    )}
                  </Form.Item >
                }
                <div>
                  注：<span className="ant-form-item-required"></span> 为必填项，否则为选填
                </div>
                <Form.Item className="formTip mt20">
                  <Button type="primary" onClick={this.subMitFrom} className="mr20">创建项目</Button>
                  <Link to={'/projects'} className="btn_32">取消</Link>
                </Form.Item>
              </div>
            </Form>
          </Spin>
        </div>
      </div>
    )
  }
}
const WrappedIndexForm = Form.create({ name: 'NewWorkForm' })(Index);
export default WrappedIndexForm;