import React, { Component } from "react";
import { Input, Select , Spin, Alert } from "antd";
import axios from "axios";
import "../Order/order.css";
import "./merge.css";
import MergeForm from "./merge_form";
import MergeFooter from "./merge_footer";
const Option = Select.Option;
class NewMerge extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: undefined,
      branches: undefined,
      merge_branches: undefined,
      merge_projects: undefined,
      merge: "master",
      pull: "master",
      id: undefined,
      is_fork: false,
      projects_names: undefined,
      isSpin: false,
      show_message: true,
      merge_head: false, // 是否向fork后的源项目发起合并请求
      default_message: "必须选择不同的分支",
      project_id: undefined, // 当前项目的id，也即开始发送合并请求的源项目id
      merge_project_user: undefined,
      oldProject:undefined,//保存选择目标分支、跳转页面后会刷新的project
      comparesData:undefined,//提交和文件的内容，保存compare接口返回的数据
    };
  }

  componentDidMount = () => {
    const { projectsId } = this.props.match.params;
    this.getmergelist(projectsId);
    // 监听回退事件
    if (window.history && window.history.pushState) {
      window.addEventListener('popstate', this.handleBack, false);
    }
  };

  componentDidUpdate=(preProps)=>{
    const { project } = this.props;
    let oldProject = preProps.project;
    if(project && oldProject && (oldProject.id !== project.id)){
      this.compareProject(this.state.id,"master","master");
    }
  }
  // 页面销毁取消监听 
  componentWillUnmount () {
    window.removeEventListener('popstate', this.handleBack, false);
  };

  handleBack=()=>{
    const { projectsId } = this.props.match.params;
    this.getmergelist(projectsId);
  }

  //获取新建分支数据
  getmergelist = (projectsId) => {
    this.setState({isSpin: true})
    const { owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/pulls/new.json`;
    axios
      .get(url)
      .then((result) => {
        if (result) {
          this.setState({
            is_fork: result.data.is_fork,
            projects_names: result.data.projects_names,
            merge_projects: result.data.merge_projects,
            branches: result.data.branches,
            merge_branches: result.data.branches,
            project_id: result.data.project_id,
            id: result.data.id
          });
          this.set_default_pull(result.data.branches);
          this.set_default_merge(result.data.merge_projects);
        }
        this.compareProject(result.data.id,"master","master");
        this.setState({isSpin: false})
      })
      .catch((error) => {
        this.setState({isSpin: false})
        console.log(error);
      });
  };

  // 获取compare接口
  compareProject=(baseid , localBranch , mergeBranch)=>{
    const { project } = this.props;
    const { owner , projectsId } = this.props.match.params;
    let url = `/${owner}/${projectsId}/compare`;
    if(project){
      if(baseid === project.id){
        this.setState({
          oldProject:project
        })
        url += `/${localBranch}...${mergeBranch}.json`;
      }else{
        const { oldProject } = this.state;
        const { author , identifier } =oldProject;
        url += `/${mergeBranch}...${author && author.login}/${identifier}:${localBranch}.json`;
      }
      axios.get(url).then(result=>{
        if(result){
          this.setState({
            comparesData:result.data
          })
        }
      }).catch(error=>{})
    }
  }

  set_default_pull = (branches) => {
    if(branches && branches.length>0){
      let default_pull = branches.filter((e) => e.name === "master")
      if (default_pull.length > 0){
        this.setState({
          pull:default_pull[0].name
        })
      }else{
        this.setState({
          pull:"master"
        })
      }
    }
  }

  set_default_merge = (merge_branches) => {
    if(merge_branches && merge_branches.length){
      let default_merge = merge_branches.filter((e) => e.name === "master")
      if (default_merge.length > 0){
        this.setState({
          merge:default_merge[0].name
        })
      }else{
        this.setState({
          merge:"master"
        })
      }
      this.ischeckmerge();
    }
  }

  newMergelist = (login,id) => {
    this.setState({isSpin: true})

    const url = `/${login}/${id}/pulls/get_branches.json`;
    axios.get(url).then((result) => {
      if (result) {
        this.setState({
          merge_branches: result.data
        })
        this.set_default_merge(result.data)
      }
      this.setState({isSpin: false})
    })
    .catch((error) => {
      this.setState({isSpin: false})
      console.log(error);
    });
  };

  selectBrach = (type, value) => {
    this.state[type] = value;
    this.ischeckmerge();
    let { id ,merge , pull } = this.state;
    if(type==="pull"){
      this.compareProject(id,value,merge);
    }else{
      this.compareProject(id,pull,value);
    }
  };

  selectProjectName = (value) => {
    const { projects_names,id } = this.state;
    let arr = projects_names && projects_names.filter(item=>item.id===value);
    let identifier = arr && arr[0].project_id;
    let login = arr && arr[0].project_user_login;
    let is_fork_id = parseInt(value) !== parseInt(id);
    this.setState({
      isSpin: true, 
      merge_head: is_fork_id,
      data: {
        is_original: is_fork_id,
        fork_project_id: is_fork_id ? id : "",
        merge_user_login: is_fork_id ? projects_names[0].project_user_login : undefined
      }
    })
    this.props.history.push(`/projects/${login}/${identifier}/pulls/new`);
    this.newMergelist(login,identifier);
  };

  //判断2分支是否可以合并

  ischeckmerge = () => {
    this.setState({ isSpin: true });
    const { projectsId , owner } = this.props.match.params;
    const { pull, merge , merge_head, id } = this.state;
    const url = `/${owner}/${projectsId}/pulls/check_can_merge.json`;
    axios.post(url, {
      head: pull,
      base: merge,
      is_original: merge_head,
      fork_project_id: merge_head ? id : undefined
    })
    .then((result) => {
      if (result) {
        if (result.data.status === 0) {
          this.setState({
            isSpin: false,
            show_message: false,
          });
        } else {
          this.setState({
            isSpin: false,
            show_message: true,
            default_message: result.data.message,
          });
        }
      } else {
        this.setState({
          isSpin: false,
          show_message: true,
          default_message: "出现错误了",
        });
      }
    })
    .catch((error) => {
      this.setState({ isSpin: false, show_message: true });
      console.log(error);
    });
  };

  render() {
    const {
      data,
      branches,
      merge_branches,
      merge_projects,
      pull,
      merge,
      isSpin,
      show_message,
      default_message,
      merge_head,
      projects_names,id,comparesData
    } = this.state;
    
    const renderBrances = (list, type) => {
      if (list && list.length > 0) {
        return list.map((item, key) => {
          return (
            <Option
              key={key + 1}
              value={item.name}
            >
              {item.name}
            </Option>
          );
        });
      }
    };

    const renderProjectNames = (list) => {
      if (list && list.length > 0) {
        return list.map((item, key) => {
          return (
            <Option key={key + 1} value={item.id}>
              {item.project_name}
            </Option>
          );
        });
      }
    };

    const withHtml = (html) => {
      return <div dangerouslySetInnerHTML={{ __html: html }}></div>;
    };
    let { project } = this.props;
    return (
      <div>
        <div className="main">
          <Spin spinning={isSpin}>
            <div className="merge-header width100 inline-block">
              <div className="width40 pull-left">
                <div className="color-grey-3 mb10 fwb">源分支:</div>
                <Input.Group compact className="display-flex">
                  <Select
                    value={id}
                    className="hide-1 task-hide flex1"
                    disabled
                  >
                    {renderProjectNames(projects_names)}
                  </Select>
                  <Select
                    value={pull}
                    onSelect={(e) => this.selectBrach("pull", e)}
                    showSearch
                    className="merge-flex1 flex1"
                  >
                    {renderBrances(branches, false)}
                  </Select>
                </Input.Group>
              </div>
              <div className="width10 pull-left text-center mt25">
                <i
                  className={"iconfont icon-youjiang color-grey-c font-32"}
                ></i>
              </div>
              <div className="width40 pull-left">
                <div>
                  <div className="color-grey-3 mb10 fwb">目标分支:</div>
                  <Input.Group compact className="display-flex">
                    <Select
                      value={project && project.id}
                      className="hide-1 task-hide flex1"
                      onSelect={(e) => this.selectProjectName(e)}
                    >
                      {renderProjectNames(merge_projects)}
                    </Select>
                    <Select
                      value={merge}
                      onSelect={(e) => this.selectBrach("merge", e)}
                      showSearch
                      className="merge-flex1 flex1"
                    >
                      {renderBrances(merge_branches, merge_head)}
                    </Select>
                  </Input.Group>
                </div>
              </div>
            </div>
            {show_message ? (
              <div className="mb20">
                <Alert description={withHtml(default_message)} type="error" />
              </div>
            ) : (
              <MergeForm
                {...this.props}
                merge_type="new"
                data={data}
                merge={merge}
                pull={pull}
                files_count={comparesData && comparesData.diff && comparesData.diff.files_count}
                commits_count={comparesData && comparesData.commits_count}
              ></MergeForm>
            )}
          </Spin>
        </div>
        <MergeFooter
          order_id={data && data.issue && data.issue.id}
          {...this.props}
          {...this.state}
          merge={merge}
          pull={pull}
          comparesData={comparesData}
        ></MergeFooter>
      </div>
    );
  }
}

export default NewMerge;
