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

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

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,

      categoreFlag:false,
      languageFlag:false,
      ignoreFlag:false,
      licenseFlag:false,
    }
  }
  componentDidMount = () => {
    // 获取拥有者列表
    this.getOwner();
    //判断是否为删除新建项目失败后返回，并执行对应逻辑
    this.isDeleteProjectBack();
  }
  componentDidUpdate=(prevPros)=>{
    if(prevPros && this.props && !this.props.checkIfLogin()){
      this.props.history.push("/403")
      return
    }
  }

  getOwner=()=>{
    const { OIdentifier } = this.props.match.params;
    const { user_id } = this.props && this.props.current_user;
    
    const url = `/owners.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        let owner = result.data.owners;
        this.setState({
          OwnerList: owner,
        })
        if(OIdentifier){
          owner = owner.filter(item=>item.login === OIdentifier);
        }else if(user_id){
          owner = owner.filter(item=>item.id === user_id);
        }
        this.props.form.setFieldsValue({
          user_id:owner && owner[0].name
        })
        owner && this.setState({
          owners_id:owner[0].id,
          owners_name:owner[0].name
        })
        this.setOptionsList(owner, 'owners');
      }
    }).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) => { })
  }

  isDeleteProjectBack = () => {
    let mirror_status = this.props.history.location.mirror_status;
    if (mirror_status === 2 && sessionStorage.newProjectValue) {
      Modal.warning({
        title: '警告',
        content: '项目导入失败！请按操作规范重新导入项目！',
      });
      let newProjectValue = JSON.parse(sessionStorage.newProjectValue);
      if (newProjectValue) {
        this.setState({
          project_language_id: newProjectValue.project_language_id,
          project_category_id: newProjectValue.project_category_id,
          license_id: newProjectValue.license_id,
          ignore_id: newProjectValue.ignore_id
        });
        delete newProjectValue.project_language_id;
        delete newProjectValue.project_category_id;
        delete newProjectValue.license_id;
        delete newProjectValue.ignore_id;
        this.props.form.setFieldsValue(newProjectValue);
      }

    }
  }

  // 设置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) => {
      console.log(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 , 
          ignoreFlag,licenseFlag,categoreFlag,languageFlag
        } = this.state;
        const decoderPass = Base64.encode(values.password);
        const url = (projectsType && projectsType === "mirror") ? "/projects/migrate.json" : "/projects.json";
        // 新建项目的时候，暂存数据，如果失败，返回的时候可以重新赋值
        sessionStorage.newProjectValue=JSON.stringify({...values,project_language_id,project_category_id,license_id,ignore_id});
        axios.post(url, {
          ...values,
          auth_password:decoderPass,
          project_language_id:languageFlag ? project_language_id : undefined,
          project_category_id:categoreFlag ? project_category_id : undefined,
          license_id:licenseFlag ? license_id : undefined,
          ignore_id:ignoreFlag ? ignore_id : undefined,
          user_id:owners_id
        }).then((result) => {
          if (result && result.data.id) {
            projectsType && projectsType !== "mirror" && this.props.showNotification(`项目创建成功!`);
            this.props.history.push(`/${result.data.login}/${result.data.identifier}`);
          }
          this.setState({
            isSpin: false
          })
        }).catch((error) => {
          this.setState({
            isSpin: false
          })
        })
      } 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(".") > -1){
        let second = first.split('.')[0];
        if(!second)return;
        this.props.form.setFieldsValue({
          repository_name:second,
          name:second
        })
      }else{
        this.props.form.setFieldsValue({
          repository_name:first
        })
      }
    }
  }

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

  showCateFunc =(e)=>{
    const { CategoryList } = this.state;
    this.setState({categoreFlag:e.target.checked});
    // 获取项目类别
    if(e.target.checked && (!CategoryList || (CategoryList && CategoryList.length===0))){
      this.getCategory();
    }
  }
  showLanguageFunc =(e)=>{
    const { LanguageList } = this.state;
    this.setState({languageFlag:e.target.checked});
    // 获取项目语言
    if(e.target.checked && (!LanguageList || (LanguageList && LanguageList.length===0))){
      this.getLanguage();
    }
  }
  showIgnoreFunc =(e)=>{
    const { GitignoreList } = this.state;
    this.setState({ignoreFlag:e.target.checked})
    if(e.target.checked && (!GitignoreList || (GitignoreList && GitignoreList.length===0))){
      // 获取Gitignore
      this.getGitignore();
    }
  }
  showLicenseFunc =(e)=>{
    const { LicensesList } = this.state;
    this.setState({licenseFlag:e.target.checked})
    if(e.target.checked && (!LicensesList || (LicensesList && LicensesList.length===0))){
      // 获取开源许可证
      this.getLicenses();
    }
  }

  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,

      ignoreFlag,
      licenseFlag,
      languageFlag,
      categoreFlag
    } = 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">

              {
                  projectsType && projectsType === "mirror" &&
                  <React.Fragment>
                    <Form.Item
                      label="导入仓库URL"
                      style={{ marginBottom: "0px" }}
                      colon={false}
                    >
                      {getFieldDecorator('clone_addr', {
                        rules: [{
                          required: true, message: '请填写镜像版本库地址'
                        }],
                      })(
                        <Input placeholder="请输入需要导入到本项目的仓库地址" onBlur={this.ChangeAddr} />
                      )}
                    </Form.Item>
                    <p className="formTip color-orange">示例：https://github.com/facebook/reack.git</p>
                  </React.Fragment>
                }
                {
                  projectsType && projectsType === "mirror" &&
                  <div className="pb10">
                    <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>
                      <span className="ml20 font-12 color-red">如果导入项目为私有仓库，则必须填写相应平台正确的用户名和密码</span>
                    </p>
                    {
                      mirrorCheck &&
                      <div className="df mb10" style={{alignItems:'center'}}>
                        <span className="mr10">用户名</span>
                        <input type="password" style={{display:"none"}} />
                        <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" }}
                        >
                          {getFieldDecorator('password', {
                            rules: [],
                          })(
                            <Input.Password placeholder="请输入对应平台的登录密码" autocomplete='new-password' style={{width:"240px"}}/>
                          )}
                        </Form.Item>
                      </div>
                    }
                  </div>
                }
                <AlignCenter>
                  <Form.Item
                    label="拥有者"
                    style={{width:"260px"}}
                    colon={false}
                    className="explainPos"
                  >
                    {getFieldDecorator('user_id', {
                      rules: [{
                        required: true, message: '请选择拥有者'
                      },{
                        validator:(rule, value, callback) => this.checkId(rule, value, callback, OwnerList, '拥有者')
                      }],
                    })(
                      <AutoComplete 
                        style={{width:"260px",height:"35px"}}
                        placeholder="请选择拥有者"
                        onChange={(value, e) => this.ChangePlatform(value, e, 'owners', OwnerList)}
                        className="plateAutoComplete"
                        onBlur={(value) => this.blurCategory(value, OwnerList, "owners")}
                        >
                        {owners_list}
                      </AutoComplete>
                    )}
                  </Form.Item>
                  <span className="ml10 mr10 mt10 font-18">/</span>
                  <Form.Item
                    label="项目名称"
                    className="flex1 explainPos"
                    colon={false}
                  >
                    {getFieldDecorator('name', {
                      rules: [{
                        required: true, message: '请填写项目名称'
                      }],
                    })(
                      <Input placeholder="例如：团队协作方法与研究" maxLength={50}/>
                    )}
                  </Form.Item>
                </AlignCenter>
                <Form.Item
                  label={<span>项目标识 <span className="color-grey-9">(项目url标识部分)</span></span>}
                  colon={false}
                >
                  {getFieldDecorator('repository_name', {
                    rules: [{
                      required: true, message: '请填写项目标识'
                    }],
                  })(
                    <Input placeholder="项目标识请使用与项目相关的英文关键字" maxLength={100} />
                  )}
                </Form.Item>
                <div className="pr">
                  <span className="toprightNum">{descNum}/200</span>
                  <Form.Item
                    label="项目简介"
                    colon={false}
                    style={{marginBottom:"0px"}}
                  >
                    {getFieldDecorator('description', {
                      rules: [],
                    })(
                      <Input.TextArea maxLength={200} placeholder="项目的介绍" autoSize={{ minRows: 2, maxRows: 6 }} onChange={this.changeDesc}/>
                    )}
                  </Form.Item>
                </div>
                
                {
                  (projectsType === "deposit" || !projectsType) &&
                  <React.Fragment>
                    <Form.Item
                      className="privatePart"
                    >
                      {getFieldDecorator('ignoreFlag')(
                        <Checkbox checked={ignoreFlag} onChange={(e)=>this.showIgnoreFunc(e)}>.gitignore</Checkbox>
                      )}
                    </Form.Item>
                    { ignoreFlag &&
                      <Form.Item>
                        {getFieldDecorator('ignore', {
                          rules: [{
                            required: ignoreFlag, 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
                      className="privatePart"
                    >
                      {getFieldDecorator('licenseFlag')(
                        <Checkbox checked={licenseFlag} onChange={(e)=>this.showLicenseFunc(e)}>开源许可证</Checkbox>
                      )}
                    </Form.Item>
                    { licenseFlag &&
                      <Form.Item>
                        {getFieldDecorator('license', {
                          rules: [{
                            required: licenseFlag, 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
                  className="privatePart"
                >
                  {getFieldDecorator('private')(
                    <Checkbox value="limit">将项目设为私有<span className="font-13 color-grey-9">(只有项目所有人或拥有权限的项目成员才能看到)</span></Checkbox>
                  )}
                </Form.Item >
                {
                  projectsType && projectsType === "mirror" &&
                  <Form.Item
                    className="privatePart"
                  >
                    {getFieldDecorator('is_mirror')(
                      <Checkbox value="limit">该仓库将是一个<span className="color-blue">镜像</span>(设置为镜像后，该项目为只读，不能进行push等相关操作)</Checkbox>
                    )}
                  </Form.Item >
                }
                <Form.Item
                  style={{ margin: "0px" }}
                  className="privatePart"
                >
                  {getFieldDecorator('categoreFlag')(
                    <Checkbox checked={categoreFlag} onChange={(e)=>this.showCateFunc(e)}>项目类别</Checkbox>
                  )}
                </Form.Item>
                {categoreFlag &&
                    <Form.Item
                    className="privatePart"
                    >
                      {getFieldDecorator('project_category', {
                        rules: [{
                          required: categoreFlag, 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
                  className="privatePart"
                >
                  {getFieldDecorator('languageFlag')(
                    <Checkbox checked={languageFlag} onChange={(e)=>this.showLanguageFunc(e)}>项目语言</Checkbox>
                  )}
                </Form.Item>
                {languageFlag && 
                  <Form.Item>
                    {getFieldDecorator('project_language', {
                      rules: [{
                        required: languageFlag, 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>
                }
                <div className="mt20">
                  注：<span className="ant-form-item-required"></span> 为必填项，否则为选填
                </div>
                <Form.Item className="formTip mt20">
                  <Button type="primary" onClick={this.subMitFrom} className="mr20">{projectsType && projectsType === "mirror" ? "导入" : "创建"}项目</Button>
                  <Link to={'/explore'} className="btn_32">取消</Link>
                </Form.Item>
              </div>
            </Form>
          </Spin>
        </div>
      </div>
    )
  }
}
const WrappedIndexForm = Form.create({ name: 'NewWorkForm' })(Index);
export default WrappedIndexForm;