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

import '../css/index.css';
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",

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

      project_language_id: undefined,
      project_category_id: undefined,
      license_id: undefined,
      ignore_id: undefined,

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

      project_language_name: undefined,
      project_category_name: undefined,
      license_name: undefined,
      ignore_name: undefined
    }
  }
  getUserInfo = () => {
    const url = `/users/me.json`;
    axios.get(url).then(result => {
      if (result && result.data.login) {
        this.setState({
          current_user: result.data
        })
        this.getDetail();
      }
    }).catch(error => {
      console.log(error)
    })
  }
  componentDidMount = () => {
    // this.getUserInfo();
    // 获取项目类别
    this.getCategory();
    // 获取项目语言
    this.getLanguage();
    // 获取Gitignore
    this.getGitignore();
    // 获取开源许可证
    this.getLicenses();
  }
  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.setState({
      isSpin: true
    })
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { current_user } = this.props;
        const { projectsType } = this.props.match.params;
        const { project_language_id, project_category_id, license_id, ignore_id } = this.state;
        const url = projectsType === "deposit" ? "/projects.json" : "/projects/migrate.json";
        axios.post(url, {
          ...values,
          project_language_id,
          project_category_id,
          license_id,
          ignore_id,
          user_id: current_user.user_id
        }).then((result) => {
          if (result) {
            if (result.data.id) {
              this.setState({
                isSpin: false
              })
              this.props.showNotification(`${projectsType === "deposit" ? "托管" : "镜像"}项目创建成功!`);
              this.props.history.push(`/projects/${result.data.id}/coders`);
            }
          }
        }).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 (filter && filter.length > 0) {
      callback();
    } else {
      callback('请在下拉选项中选择正确的' + title + "!");
    }
    callback();
  }

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

      CategoryList,
      LanguageList,
      GitignoreList,
      LicensesList,
      isSpin,
      project_language_name,
      project_category_name,
      license_name,
      ignore_name,

      project_language_list,
      project_category_list,
      license_list,
      ignore_list,
    } = this.state;
    return (
      <div className="main back-white">
        <div className="newPanel">
          <div className="newPanel_title">创建{projectsType === "deposit" ? "托管" : "镜像"}项目</div>
          <Spin spinning={isSpin}>
            <Form>
              <div className="newPanel_content">
                {
                  projectsType !== "deposit" &&
                  <React.Fragment>
                    <Form.Item
                      label="镜像版本库地址"
                      style={{ marginBottom: "0px" }}
                    >
                      {getFieldDecorator('clone_addr', {
                        rules: [{
                          required: true, message: '请填写镜像版本库地址'
                        }],
                      })(
                        <Input placeholder="输入需要同步到本项目的镜像版本库地址" />
                      )}
                    </Form.Item>
                    <p className="formTip">示例：https://github.com/facebook/reack.git</p>
                  </React.Fragment>
                }
                <Form.Item
                  label="项目名称"
                >
                  {getFieldDecorator('name', {
                    rules: [{
                      required: true, message: '请填写项目名称'
                    }],
                  })(
                    <Input placeholder="例如：团队协作方法与研究" />
                  )}
                </Form.Item>

                <Form.Item
                  label="项目简介"
                >
                  {getFieldDecorator('description', {
                    rules: [{
                      required: true, message: '请填写项目简介'
                    }],
                  })(
                    <Input.TextArea placeholder="项目的介绍" autoSize={{ minRows: 2, maxRows: 6 }} />
                  )}
                </Form.Item>
                <Form.Item
                  label="仓库名称"
                >
                  {getFieldDecorator('repository_name', {
                    rules: [{
                      required: true, message: '请填写仓库名称'
                    }],
                  })(
                    <Input placeholder="仓库名称请使用与项目相关的英文关键字" />
                  )}
                </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")}
                    >
                      {/* {this.setOptionsList(CategoryList,project_category_name)} */}
                      {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")}
                    >
                      {/* {this.setOptionsList(LanguageList,project_language_name)} */}
                      {project_language_list}
                    </AutoComplete>
                  )}
                </Form.Item>
              </div>
              <Divider />
              <div className="newPanel_content">
                {
                  projectsType === "deposit" &&
                  <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")}
                        >
                          {/* {this.setOptionsList(GitignoreList,ignore_name)} */}
                          {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")}
                        >
                          {/* {this.setOptionsList(LicensesList,license_name)} */}
                          {license_list}
                        </AutoComplete>
                      )}
                    </Form.Item>
                  </React.Fragment>
                }
                <Form.Item
                  label="可见性"
                  style={{ marginBottom: "0px" }}
                >
                  {getFieldDecorator('private')(
                    <Checkbox value="limit">将项目设为私有<span className="ml15 font-13 color-grey-9">(只有项目所有人或拥有权限的项目成员才能看到)</span></Checkbox>
                  )}
                </Form.Item >
                <div className="ant-row ant-form-item">
                  <div className="ant-col ant-form-item-label">
                    注：
                  </div>
                  <div className="ant-col ant-form-item-control-wrapper color-grey-9">
                    <div className="ant-form-item-control">
                      <span className="ant-form-item-required"></span> 为必填项，否则为选填
                    </div>
                  </div>
                </div>
                <Form.Item className="formTip">
                  <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;