import React, { Component } from "react";
import { Form, Input, Select, Spin } from 'antd';
import { getImageUrl } from 'educoder';
import UploadComponent from '../Upload/Index';
import MDEditor from '../../modules/tpm/challengesnew/tpm-md-editor';

import './order.css';

import axios from 'axios';
import { Link } from "react-router-dom";

const Option = Select.Option;
class New extends Component {
  constructor(props) {
    super(props);
    this.state = {
      branch_name: "",
      issue_tag_ids: "",
      fixed_version_id: "",
      tracker_id: "缺陷",
      issue_type: "普通",
      status_id: '新增',
      assigned_to_id: "",
      priority_id: "正常",
      done_ratio: "0%",
      issue_chosen: undefined,
      branches: undefined,
      fileList: undefined,
      description: undefined,
      isSpin: false
    }
  }

  componentDidMount = () => {
    if (!this.props.checkIfLogin()) {
      this.props.showLoginDialog();
      return;
    }
    this.InitData();
    this.getSelectList();
  }

  InitData = () => {
    this.props.form.setFieldsValue({
      ...this.state
    });
  }

  getSelectList = () => {
    let projectsId = ""
    if (this.props.match.params.milepostId) {
      projectsId = this.props.match.params.projectsId;
      this.props.form.setFieldsValue({
        fixed_version_id: this.props.match.params.milepostId
      });
    } else {
      projectsId = this.props.match.params.projectsId;
    }

    const url = `/projects/${projectsId}/issues/new.json`;
    axios.get(url).then((result) => {
      if (result) {
        this.setState({
          issue_chosen: result.data.issue_chosen,
          branches: result.data.branches
        })
      }
    }).catch((error) => {
      console.log(error);
    })
  }

  renderSelect = (list) => {
    if (list && list.length > 0) {
      return (
        list.map((item, key) => {
          return (
            <Option key={key + 1} value={item.id + ""}>{item.name}</Option>
          )
        })
      )
    }
  }

  // 创建
  handleSubmit = () => {
    this.setState({
      isSpin: true
    })
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {

        const { projectsId } = this.props.match.params;
        const { fileList } = this.state;
        const url = `/projects/${projectsId}/issues.json`;
        if (values.status_id === "新增") {
          values.status_id = "1"
        }
        // if(values.issue_type==="普通"){
        //   values.issue_type="1"
        // }
        if (values.tracker_id === "缺陷") {
          values.tracker_id = "1"
        }
        if (values.priority_id === "正常") {
          values.priority_id = "2"
        }
        if (values.done_ratio === "0%") {
          values.done_ratio = "0"
        }
        if (values.issue_tag_ids.length > 0) {
          values.issue_tag_ids = [values.issue_tag_ids]
        }
        const { description } = this.state;

        axios.post(url, {
          ...values,
          description: description,
          attachment_ids: fileList
        }).then(result => {
          if (result) {
            this.props.showNotification("任务创建成功！");
            this.props.history.push(`/projects/${projectsId}/orders`);
            this.setState({
              description: '',
              isSpin: false
            })
          }
        }).catch(error => {
          this.setState({
            isSpin: false
          })
          console.log(error);
        })
      }else{
        this.setState({
          isSpin: false
        })
      }
    })
  }

  // 获取上传后的文件id数组
  UploadFunc = (fileList) => {
    this.setState({
      fileList
    })
  }

  onContentChange = (value) => {
    this.setState({
      description: value
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { current_user } = this.props;
    const { description, issue_chosen, branches, isSpin } = this.state;

    return (
      <div className="main">
        <Form>
          <div className="f-wrap-between mt20" style={{ alignItems: "flex-start" }}>
            <div className="list-right df">
              <Link to={`/users/${current_user && current_user.login}/projects`} className="show-user-link">
                <img className="user_img" src={getImageUrl(`images/${current_user && current_user.image_url}`)} alt="" />
              </Link>

              <div className="new_context">
                <Form.Item>
                  {getFieldDecorator('subject', {
                    rules: [{
                      required: true, message: '请填写任务标题'
                    }],
                  })(
                    <Input placeholder="标题" />
                  )}
                </Form.Item>
                <div className="quillContent" style={{ marginBottom: "20px" }}>
                  <MDEditor placeholder={'请输入描述信息'} height={350}
                    mdID={'order-new-description'} initValue={description} onChange={this.onContentChange} ></MDEditor>
                </div>
                <UploadComponent load={this.UploadFunc} showNotification={this.props.showNotification} isComplete={true}></UploadComponent>
                <p className="clearfix mt15">
                  <Spin spinning={isSpin}>
                    <a className="topWrapper_btn fr" type="submit" onClick={this.handleSubmit}>创建任务</a>
                  </Spin>
                </p>
              </div>
            </div>
            <div className="list-left mt10" style={{ paddingRight: "0px", paddingLeft: "0px", width: "25%", backgroundColor: "#fff" }}>
              <div className="list-l-panel">
                <Form.Item>
                  {getFieldDecorator('branch_name', {
                    rules: [],
                  })(
                    <Select>
                      <Option value={''}>分支未指定</Option>
                      {
                        branches && branches.length > 0 && branches.map((item, key) => {
                          return (
                            <Option value={item}>{item}</Option>
                          )
                        })
                      }
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="标签"
                >
                  {getFieldDecorator('issue_tag_ids', {
                    rules: [],
                  })(
                    <Select>
                      <Option value={""}>{issue_chosen && issue_chosen.issue_tag.length > 0 ? '未选择标签' : '请在仓库设置里添加标签'}</Option>
                      {this.renderSelect(issue_chosen && issue_chosen.issue_tag)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="里程碑"
                >
                  {getFieldDecorator('fixed_version_id', {
                    rules: [],

                  })(
                    <Select>
                      <Option value={""}>{issue_chosen && issue_chosen.issue_version.length > 0 ? '未选择里程碑' : '请添加里程碑'}</Option>
                      {this.renderSelect(issue_chosen && issue_chosen.issue_version)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="状态"
                >
                  {getFieldDecorator('status_id', {
                    rules: [{
                      required: true, message: '请选择完成状态'
                    }],
                  })(
                    <Select>
                      {this.renderSelect(issue_chosen && issue_chosen.issue_status)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="分类"
                >
                  {getFieldDecorator('tracker_id', {
                    rules: [{
                      required: true, message: '请选择分类'
                    }],
                  })(
                    <Select>
                      {this.renderSelect(issue_chosen && issue_chosen.tracker)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="指派成员"
                >
                  {getFieldDecorator('assigned_to_id', {
                    rules: [{
                    }],
                  })(
                    <Select>
                      <Option value={""}>未指派成员</Option>
                      {this.renderSelect(issue_chosen && issue_chosen.assign_user)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="优先度"
                >
                  {getFieldDecorator('priority_id', {
                    rules: [{
                      required: true, message: '请选择优先度'
                    }],
                  })(
                    <Select>
                      {this.renderSelect(issue_chosen && issue_chosen.priority)}
                    </Select>
                  )}
                </Form.Item>
                <Form.Item
                  label="完成度"
                >
                  {getFieldDecorator('done_ratio', {
                    rules: [{
                      required: true, message: '请选择完成度'
                    }],
                  })(
                    <Select>
                      {this.renderSelect(issue_chosen && issue_chosen.done_ratio)}
                    </Select>
                  )}
                </Form.Item>
              </div>
            </div>
          </div>
        </Form>
      </div>
    )
  }
}
const WrappedNewForm = Form.create({ name: 'NewOrderForm' })(New);
export default WrappedNewForm;