import React, { Component } from "react";
import { Link } from "react-router-dom";

import axios from "axios";
import { getImageUrl } from "educoder";
import {
  Form,
  Input,
  Spin,
  Dropdown,
  Icon,
  Menu,
  Select,
  Tag,
  Button,
  Alert,
} from "antd";
import "./merge.css";
import RenderHtml from "../../components/render-html";
import "../Order/order.css";
import MergeFooter from "./merge_footer";

const Option = Select.Option;
const TextArea = Input.TextArea;

class MessageCount extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: undefined,
      isSpin: false,
      ismesrge: false,
      buttonshow: "none",
      mergename: "合并请求",
      mergekey: "merge",
      title: "",
      body: "",
      SpinFlag: true,
      SpinMerge: false,
      edit_spin: false,
      pr_status: undefined,
    };
  }

  componentDidMount = () => {
    this.setState({
      SpinFlag: true,
    });
    this.getDetail();
  };

  getDetail = () => {
    const { projectsId, mergeId, owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/pulls/${mergeId}.json`;
    axios
      .get(url)
      .then((result) => {
        if (result) {
          this.setState({
            data: result.data,
            SpinFlag: false,
            pr_status: result.data.pull_request.status,
          });
        } else {
          this.setState({ SpinFlag: false });
        }
      })
      .catch((error) => {
        this.setState({
          SpinFlag: false,
        });
        console.log(error);
      });
  };

  //关闭任务
  closedetail = () => {
    this.setState({ isSpin: true });
    const { projectsId, mergeId , owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/pulls/${mergeId}/refuse_merge.json`;
    axios
      .post(url)
      .then((result) => {
        if (result) {
          this.setState({
            isSpin: false,
            pr_status: 2,
          });
        } else {
          this.setState({
            isSpin: false,
          });
        }
      })
      .catch((error) => {
        this.setState({
          isSpin: false,
        });
        console.log(error);
      });
  };

  //合并请求
  prmerge = () => {
    this.setState({
      SpinMerge: true,
    });
    const { projectsId , owner } = this.props.match.params;
    const { data, title, body, mergekey, pr_status } = this.state;
    const url = `/${owner}/${projectsId}/pulls/${data.pull_request.id}/pr_merge.json`;
    axios
      .post(url, {
        project_id: projectsId,
        id: data.pull_request.id,
        do: mergekey,
        body: body,
        title: title,
      })
      .then((result) => {
        if (result) {
          this.setState({
            SpinMerge: false,
            pr_status: 1,
          });
        } else {
          this.setState({ SpinMerge: false });
        }
      })
      .catch((error) => {
        this.setState({
          SpinMerge: false,
        });
        console.log(error);
      });
  };

  changtitlepr = (e) => {
    this.setState({
      title: e.target.value,
    });
  };

  changbodypr = (e) => {
    this.setState({
      body: e.target.value,
    });
  };

  submitmerge = () => {
    if (this.state.mergekey === "rebase") {
      this.setState({
        buttonshow: "block",
        ismesrge: true,
      });
    } else {
      this.setState({
        ismesrge: "block",
        buttonshow: false,
      });
    }
  };

  nonemerge = () => {
    this.setState({
      ismesrge: false,
      buttonshow: "none",
    });
  };

  getOption = (e) => {
    if (e.key === "rebase") {
      this.setState({
        mergename: e.item.props.value,
        mergekey: e.key,
        title: "",
        body: "",
        buttonshow: "block",
      });
    } else {
      this.setState({
        mergename: e.item.props.value,
        mergekey: e.key,
        title: "",
        body: "",
        ismesrge: true,
        buttonshow: "block",
      });
    }
  };

  cancelSubmit = () => {
    this.setState({
      editMerge: false,
    });
  };

  commentCtx = (v) => {
    return <RenderHtml className="break_word_comments imageLayerParent" value={v} />;
  };

  render() {
    const { projectsId, mergeId , owner } = this.props.match.params;
    
    const {
      data,
      SpinMerge,
      pr_status,
      isSpin,
      ismesrge,
      SpinFlag,
    } = this.state;
    const { current_user, projectDetail } = this.props;
    const menu = (
      <Menu onClick={(e) => this.getOption(e)}>
        <Menu.Item key={"merge"} value="合并请求">
          合并请求
        </Menu.Item>
        <Menu.Item key={"rebase"} value="变基并合并">
          变基并合并
        </Menu.Item>
        <Menu.Item key={"rebase-merge"} value="变基合并 --no-ff">
          变基合并 --no-ff
        </Menu.Item>
        <Menu.Item key={"squash"} value="压缩提交并合并">
          压缩提交并合并
        </Menu.Item>
      </Menu>
    );

    return (
      <div className="">
        {data ? (
          <div>
            <div className="main">
              <div>
                <div className="grid-item-top pb20 border-1f">
                  <div>
                    <div className="ver-middle">
                      <span className="mr10 ver-middle">
                        <span className="font-18 fwb">
                          {data.issue.subject}
                        </span>
                      </span>

                      {data.pull_request && (
                        <Tag
                          className={`pr_tags_${data.pull_request.pull_request_staus}`}
                        >
                          {pr_status === 1
                            ? "已合并"
                            : pr_status === 2
                            ? "已拒绝"
                            : "开启的"}
                        </Tag>
                      )}
                    </div>
                    {
                      <div className="mt15">
                        <Tag className="pr-branch-tag">
                          <Link
                            to={`/projects/${owner}/${data.pull_request.is_original?data.pull_request.fork_project_id:projectsId}?branch=${data.pull_request.head}`}
                            className="ver-middle"
                          >
                            {data.pull_request.is_original ? data.pull_request.fork_project_user : data.issue.project_author_name}:{data.pull_request.head}
                          </Link>
                        </Tag>
                        <span className="mr8 ver-middle">
                          <i
                            className={
                              "iconfont icon-youjiang color-grey-c font-16"
                            }
                          ></i>
                        </span>
                        <Tag className="pr-branch-tag">
                          <Link
                            to={`/projects/${owner}/${projectsId}?branch=${data.pull_request.base}`}
                            className="ver-middle"
                          >
                            {/* {data.pull_request.is_fork ? data.pull_request.base : `${data.pull_request.pull_request_user}:${data.pull_request.base}`} */}
                            {data.issue.project_author_name}:{data.pull_request.base}
                          </Link>
                        </Tag>
                      </div>
                    }

                    <div className="mt15">
                      <Link
                        to={`/users/${data.issue.author_login}`}
                        className="show-user-link"
                      >
                        <img
                          className="mr5"
                          src={getImageUrl(
                            `images/${data.issue.author_picture}`
                          )}
                          alt=""
                          width="24"
                          height="24"
                        />
                      </Link>
                      <span className="ver-middle">
                        <span className="color-grey-8 mr5">由</span>
                        <Link
                          to={`/users/${data.issue.author_login}`}
                          className="show-user-link color-blue"
                        >
                          {data.issue.author_name}
                        </Link>
                        <span className="ml5 color-grey-8">
                          {pr_status === 0
                            ? "创建于"
                            : pr_status === 1
                            ? "合并于"
                            : "更新于"}
                        </span>
                        <span className="color-grey-8 ml5">{data.pr_time}</span>
                        <span className="ml25">
                          <span className="color-grey-8">审查人员：</span>
                          {data.issue.assign_user_name ? (
                            <Link
                              to={`/users/${data.issue.assign_user_login}`}
                              className="show-user-link color-blue"
                            >
                              {data.issue.assign_user_name}
                            </Link>
                          ) : (
                            "--"
                          )}
                        </span>
                        <span className="ml25">
                          <span className="color-grey-8">里程碑：</span>
                          <span className="color-grey-3">
                            {data.issue.version ? data.issue.version : "--"}
                          </span>
                        </span>
                        <span className="ml25">
                          <span className="color-grey-8">标签：</span>
                          <span className="color-grey-3">
                            {data.issue.issue_tags &&
                            data.issue.issue_tags.length > 0
                              ? data.issue.issue_tags[0].name
                              : "--"}
                          </span>
                        </span>
                        <span className="ml25">
                          <span className="color-grey-8">优先级：</span>
                          <span className="color-grey-3">
                            {data.issue.priority ? data.issue.priority : "--"}
                          </span>
                        </span>
                      </span>
                    </div>
                  </div>
                  <div className="ml10">
                    <div className="mt15 text-right">
                      {current_user && projectDetail &&
                        pr_status !== 2 &&
                        projectDetail.permission !=="Reporter" && (
                          <Button
                            type="success"
                            ghost
                            onClick={()=>{this.props.history.push(`/projects/${owner}/${projectsId}/pulls/${mergeId}/UpdateMerge`);}}
                          >
                            编辑
                          </Button>
                        )}
                      {projectDetail && projectDetail.permission !=="Reporter" && pr_status === 0 && (
                        <Button
                          type="danger"
                          ghost
                          onClick={() => this.closedetail()}
                          className="ml15"
                          loading={isSpin}
                        >
                          拒绝
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
                {
                data.issue.description ? 
                  <div className="mt15">{this.commentCtx(data.issue.description)}</div>
                :
                  <p className="color-grey-9 ml3 mr3 mt15">没有描述</p>
                }
              </div>
              <div className="mt15">
                {pr_status === 2 && (
                  <Alert
                    message="提示"
                    description="该合并请求已被拒绝"
                    type="error"
                  />
                )}
                {pr_status === 1 && (
                  <Alert
                    message="提示"
                    description="该合并请求已被合并"
                    type="success"
                  />
                )}
                {pr_status === 0 && projectDetail && projectDetail.permission !=="Reporter" && (
                  <Spin spinning={SpinFlag}>
                    <div
                      style={{
                        display:
                          this.state.mergekey === "rebase"
                            ? this.state.buttonshow === "none"
                              ? "block"
                              : "none"
                            : !ismesrge
                            ? "block"
                            : "none",
                      }}
                    >
                      <p className="mb15">
                        <Dropdown.Button
                          overlay={menu}
                          type="primary"
                          onClick={this.submitmerge}
                          icon={<Icon type="caret-down" />}
                        >
                          {this.state.mergename}
                        </Dropdown.Button>
                      </p>
                      <Alert
                        message="该合并请求可以进行自动合并操作"
                        type="success"
                        showIcon
                      />
                    </div>
                    <div>
                      <div
                        style={{
                          display: ismesrge ? "block" : "none",
                          marginTop: 15,
                        }}
                      >
                        <Input
                          placeholder="标题"
                          value={this.state.title}
                          onChange={this.changtitlepr}
                        />
                        <TextArea
                          placeholder="请输入合并描述..."
                          style={{ height: "170px", marginTop: 20 }}
                          value={this.state.body}
                          onChange={this.changbodypr}
                        />
                      </div>
                      <p
                        className="clearfix mt15"
                        style={{ display: this.state.buttonshow }}
                      >
                        <Spin spinning={SpinMerge}>
                          <Button type="primary" onClick={() => this.prmerge()}>
                            确认合并
                          </Button>
                          <Button
                            onClick={() => this.nonemerge()}
                            className="ml15"
                          >
                            取消
                          </Button>
                        </Spin>
                      </p>
                    </div>
                  </Spin>
                )}
              </div>
            </div>

            <div className=" main">
              <MergeFooter
                footer_type="show"
                order_id={data && data.issue.id}
                {...this.props}
                {...this.state}
              ></MergeFooter>
            </div>
          </div>
        ) : (
          ""
        )}
      </div>
    );
  }
}

const MessageCountForm = Form.create({ name: "MessageCountForm" })(
  MessageCount
);
export default MessageCountForm;
