import React, { Component } from "react";
import { Button, Form, Menu, Input, Select, Tag, Checkbox, Spin } from "antd";
import axios from "axios";

import "../Order/order.css";
import "./merge.css";
import MDEditor from "../../modules/tpm/challengesnew/tpm-md-editor";

const Option = Select.Option;

class MergeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      desc: undefined,
      issue_tag_ids: undefined,
      fixed_version_id: undefined,
      assigned_to_id: undefined,
      titledata: undefined,
      isSpin: false,
      mergedata: undefined,
      priority_id: undefined,
      title: undefined,
      members: undefined,
      issue_tags: undefined,
      issue_versions: undefined,
      issue_priories: undefined,
    };
  }

  componentDidMount = () => {
    // this.check_is_login();
    this.get_default_selects();
    this.set_defatul();
  };
  componentDidUpdate=(prevPros)=>{
    if(prevPros && this.props && !this.props.checkIfLogin()){
      this.props.history.push("/403")
      return
    }
  }
  // check_is_login =() =>{
  //   if(!this.props.checkIfLogin()){
  //     this.props.history.push("/403")
  //     return
  //   }
  // };
  get_default_selects = () => {
    const { projectsId ,owner } = this.props.match.params;
    this.setState({ isSpin: true });
    axios
      .get(`/${owner}/${projectsId}/pulls/create_merge_infos.json`)
      .then((result) => {
        if (result) {
          this.setState({
            members: result.data.members,
            issue_tags: result.data.issue_tags,
            issue_versions: result.data.issue_versions,
            issue_priories: result.data.issue_priories,
          });
        }
        this.setState({ isSpin: false });
      })
      .catch((error) => {
        this.setState({ isSpin: false });
        console.log(error);
      });
  };
  set_defatul = () => {
    const { data, merge_type } = this.props;
    if (data && merge_type === "edit") {
      this.setState({
        desc: data.body,
        issue_tag_ids: data.issue_tag_ids ? data.issue_tag_ids[0] : undefined,
        fixed_version_id: data.fixed_version_id ? String(data.fixed_version_id) : undefined,
        assigned_to_id: data.assigned_to_id ? String(data.assigned_to_id) : undefined,
        priority_id: data.priority_id ? String(data.priority_id) :undefined,
        title: data.title,
      });
    }
    this.InitData();
  };
  InitData = () => {
    setTimeout(() => {
      this.props.form.setFieldsValue({
        ...this.state,
      });
    }, 100);
  };

  onPanelChange = (time, mode) => {
    this.setState({
      value: time,
    });
  };

  onSelect = (time) => {
    this.setState({
      value: time,
      selectedValue: time,
    });
  };

  renderMenu = (array, id) => {
    return (
      <Menu>
        {array &&
          array.length > 0 &&
          array.map((item, key) => {
            return (
              <Menu.Item key={item} onClick={() => this.getOption(item, id)}>
                {item}
              </Menu.Item>
            );
          })}
      </Menu>
    );
  };

  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, mergeId , owner } = this.props.match.params;
        const { merge, pull, merge_type, data } = this.props;
        if (values.issue_tag_ids && values.issue_tag_ids.length > 0) {
          values.issue_tag_ids = [parseInt(values.issue_tag_ids)];
        } else {
          values.issue_tag_ids = [];
        }
        const { desc } = this.state;        
        if (merge_type === "new") {
          let url = `/${owner}/${projectsId}/pulls.json`;
          axios.post(url, {
            ...values,
            body: desc,
            head: pull,
            base: merge,
            is_original: data && data.is_original,
            fork_project_id: data && data.fork_project_id,
            merge_user_login: data && data.merge_user_login
          })
          .then((result) => {
            if (result) {
              this.setState({
                isSpin: false,
              });
              this.props.history.push(`/projects/${owner}/${projectsId}/pulls`);
              const { getDetail } = this.props;
              getDetail && getDetail();
            } else {
              this.setState({
                isSpin: false,
              });
            }
          })
          .catch((error) => {
            this.setState({
              isSpin: false,
            });
            console.log(error);
          });
      } else {
        let url = `/${owner}/${projectsId}/pulls/${mergeId}.json`;
        axios
          .put(url, {
            ...values,
            body: desc,
            head: pull,
            base: merge,
          })
          .then((result) => {
            if (result) {
              this.setState({
                isSpin: false,
              });
              this.props.history.push(
                `/projects/${owner}/${projectsId}/pulls/${mergeId}/Messagecount`
              );
            } else {
              this.setState({
                isSpin: false,
              });
            }
          })
          .catch((error) => {
            this.setState({
              isSpin: false,
            });
            console.log(error);
          });
        }
      } else {
        this.setState({
          isSpin: false,
        });
      }
    });
  };

  onContentChange = (value) => {
    this.setState({
      desc: value,
    });
  };

  render() {
    const { merge_type, data } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { projectsId, mergeId ,owner } = this.props.match.params;
    const {
      issue_tag_ids,
      fixed_version_id,
      assigned_to_id,
      priority_id,
      desc,
      isSpin,
      title,
      members,
      issue_tags,
      issue_versions,
      issue_priories,
    } = this.state;
    return (
      <div>
        <Spin spinning={isSpin}>
          <div className="mb20">
            <span className="font-16 fwb mr10 ver-middle">
              {merge_type === "new" ? "新建" : "编辑"}合并请求:
            </span>
            <Tag color="#28BD6C" className="ver-middle">
              可合并的
            </Tag>
          </div>
          <Form>
            <div className="width100 inline-block">
              <div className="width70 pull-left">
                <Form.Item>
                  {getFieldDecorator("title", {
                    rules: [
                      {
                        required: true,
                        message: "请填写请求标题",
                      },
                    ],
                    initialValue: title,
                  })(<Input placeholder="标题" />)}
                </Form.Item>
                <MDEditor
                  placeholder={"请输入合并请求的描述..."}
                  height={350}
                  mdID={"merge-new-description"}
                  initValue={desc}
                  onChange={this.onContentChange}
                ></MDEditor>
                <p className="clearfix mt20">
                  <Button
                    type="primary"
                    loading={isSpin}
                    onClick={this.handleSubmit}
                  >
                    <span className="plr10">
                      {merge_type === "new" ? "创建" : "提交"}
                    </span>
                  </Button>
                  <Button
                    type="default"
                    className="ml30"
                    onClick={()=>{
                      this.props.history.push(merge_type === "new" ? `/projects/${owner}/${projectsId}/pulls` : `/projects/${owner}/${projectsId}/pulls/${mergeId}/detail`)
                    }}
                  >
                    <span className="plr10">取消</span>
                  </Button>
                </p>
              </div>
              <div className="width30 pull-left">
                <div className="pl30">
                  <Form.Item>
                    {getFieldDecorator("assigned_to_id", {
                      initialValue: assigned_to_id,
                    })(
                      <Select placeholder="审查人员" showSearch>
                        {this.renderSelect(members)}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator("fixed_version_id", {
                      initialValue: fixed_version_id,
                    })(
                      <Select
                        placeholder={
                          issue_versions && issue_versions.length > 0
                            ? "未选择里程碑"
                            : "请添加里程碑"
                        }
                        showSearch
                      >
                        {this.renderSelect(issue_versions)}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator("issue_tag_ids", {
                      initialValue: issue_tag_ids,
                    })(
                      <Select
                        placeholder={
                          issue_tags && issue_tags.length > 0
                            ? "未选择标签"
                            : "请在仓库设置里添加标签"
                        }
                        showSearch
                      >
                        {this.renderSelect(issue_tags)}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator("priority_id", {
                      initialValue: priority_id,
                    })(
                      <Select placeholder="优先级" showSearch>
                        {this.renderSelect(issue_priories)}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item name="checkbox-group" label="其他">
                    <Checkbox.Group>
                      <div>
                        <Checkbox value="A">必须审查代码</Checkbox>
                      </div>
                      <div>
                        <Checkbox value="B">合并后删除提交分支</Checkbox>
                      </div>
                      <div>
                        <Checkbox value="C">合并后关闭提到的任务</Checkbox>
                      </div>
                    </Checkbox.Group>
                  </Form.Item>
                </div>
              </div>
            </div>
          </Form>
        </Spin>
      </div>
    );
  }
}
const WrappedNewMerge = Form.create({ name: "NewMergeForm" })(MergeForm);
export default WrappedNewMerge;
