import React, { Component } from "react";
import { Form, Input, Checkbox, Select , Spin } from "antd";
import Title from '../Component/Title';
import {WhiteBack} from '../Component/layout';
import DivertModal from '../Divert/DivertModal';
import { Link } from 'react-router-dom';
import axios from "axios";
import "./setting.scss";
const { TextArea } = Input;
const { Option } = Select;

const menu = [
  {name:"主页",index:"home"},
  {name:"代码库",index:"code"},
  {name:"疑修 (Issue)",index:"issues"},
  {name:"合并请求 (PR)",index:"pulls"},
  {name:"引擎 (Engine)",index:"devops"},
  // {name:"资源库",index:"resources"},
  {name:"里程碑",index:"versions"},
  {name:"维基 (Wiki)",index:"wiki"},
  // {name:"服务",index:"services"},
  {name:"动态",index:"activity"},
]
class Setting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      CategoryList: undefined,
      LanguageList: undefined,
      private_check: undefined,
      loading:true,
      project_units:['home',"activity","code"],
      divertVisible:false,
      is_transfering:undefined,
      projectName:undefined,
      permission:undefined
    };
  }

  componentDidUpdate=(prevPros)=>{

    if(prevPros && this.props && !this.props.checkIfLogin()){
      this.props.history.push("/403")
      return;
    }
  }
  componentDidMount = () => {
    this.getCategory();
    this.getLanguage();
    this.getInfo();
  };
  getLanguage = () => {
    const url = `/project_languages.json`;
    axios
      .get(url)
      .then((result) => {
        if (result) {
          let LanguageList = this.setOptionsList(result.data.project_languages);
          this.setState({
            LanguageList,
          });
        }
      })
      .catch((error) => {});
  };

  getInfo = () => {
    const { projectsId , owner } = this.props.match.params;
    const url = `/${owner}/${projectsId}/edit.json`;
    axios
      .get(url)
      .then((result) => {
        if (result) {
          const { project_units } = this.state;
          let units = result.data.project_units; 
          units.push(...project_units);

          this.props.form.setFieldsValue({
            ...result.data,
            project_units:units
          });
          this.setState({
            projectName:result.data.project_name,
            private_check: result.data.private,
            loading:false,
            project_units:units,
            transfer:result.data.transfer,
            is_transfering:result.data.is_transfering,
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  getCategory = () => {
    const url = `/project_categories.json`;
    axios
      .get(url)
      .then((result) => {
        if (result) {
          let CategoryList = this.setOptionsList(
            result.data.project_categories
          );
          this.setState({
            CategoryList,
          });
        }
      })
      .catch((error) => {});
  };

  setOptionsList = (data) => {
    let list = undefined;
    if (data && data.length > 0) {
      list = data.map((item, key) => {
        return (
          <Option key={item.id} value={item.id}>
            {item.name}
          </Option>
        );
      });
    }
    return list;
  };

  // 更新仓库设置
  resetSetting = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          loading:true
        })
        const { projectsId , owner } = this.props.match.params;
        const navUrl =  `/${owner}/${projectsId}/project_units.json`;

        let unit = values.project_units.filter(item => (item !== "home" && item!== "activity" && item!== "code"));
        axios.post(navUrl, {
          unit_types:unit
        }).then((result) => {
          if (result) {
            this.update(values);
          }
        }).catch(error=>{})
      }
    });
  };

  update=(values)=>{
    const { projectsId , owner } = this.props.match.params;
    const { private_check , project_units } = this.state;
    const url = `/${owner}/${projectsId}.json`;
    axios.put(url, {
      name: values.project_name,
      description: values.project_description,
      private: private_check,
      identifier:values.project_identifier,
      ...values,
    }).then((result) => {
      if (result) {
        this.props.showNotification(`仓库信息修改成功！`);
        if(values.project_identifier !== projectsId){
          this.props.history.push(`/${owner}/${values.project_identifier}/settings`);
        }else{
          const { getDetail } = this.props;
          getDetail && getDetail();
        }
        if(project_units!==values.project_units){
          window.location.reload();
        }
      }
      this.setState({
        loading:false
      })
    }).catch((error) => {
      this.setState({
        loading:false
      })
    });
  }

  // 删除本仓库
  deleteProject = () => {
    const { projectsId , owner } = this.props.match.params;
    const { projectName } = this.state;
    this.props.confirm({
      content: <span style={{display:"block",textAlign:"left"}}>该操作无法撤销！且将会一并删除相关的疑修、合并请求、工作流、里程碑、动态等数据。<br/>是否确认删除 <span style={{fontWeight:"bold"}}>{owner}/{projectName}({projectsId})</span>？</span>,
      onOk: () => {
        const url = `/${owner}/${projectsId}.json`;
        axios.delete(url).then((result) => {
            this.props.showNotification("仓库删除成功！");
            this.props.history.push(`/${owner}`);
          })
          .catch((error) => {
            console.log(error);
          });
      },
    });
  };
  changePrivate = (e) => {
    this.setState({
      private_check: e.target.checked,
    });
  };

  // 转移仓库
  DivertProject=()=>{
    this.setState({
      divertVisible:true
    })
  }
   // 取消仓库转移
  CancelDivertProject=()=>{
    this.props.confirm({
      content: "是否确认取消将此项目转移给他人？",
      onOk: () => {
        const { projectsId , owner } = this.props.match.params;
        const url =  `/${owner}/${projectsId}/applied_transfer_projects/cancel.json`;
        axios.post(url).then(result=>{
          if(result && result.data){
            this.setState({
              is_transfering:false
            })
          }
        }).catch(error=>{})
      },
    });
    
  }
  // 确定转移仓库
  onSuccess=(owner)=>{
    if(owner){
      this.setState({
        is_transfering:true,
        transfer:owner
      })
    }
    this.setState({
      divertVisible:false
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { projectsId , owner } = this.props.match.params;
    const { projectDetail } = this.props;

    const { CategoryList, LanguageList, private_check ,loading , divertVisible , is_transfering, transfer } = this.state;
    let mirror = projectDetail && projectDetail.mirror;
    let type = projectDetail && projectDetail.type;
    const forked_from_project_id = this.props && this.props.projectDetail && this.props.projectDetail.forked_from_project_id;

    return (
      <div>
        <DivertModal 
          owner={owner}
          repo={projectsId}
          visible={divertVisible} 
          onSuccess={this.onSuccess} 
          onCancel={()=>{this.setState({divertVisible:false})}}
        />
        <Spin spinning={loading}>
          <WhiteBack>
            <Title>基本设置</Title>
            <Form className="baseForm">
              <Form.Item label="项目名称">
                {getFieldDecorator("project_name", {
                  rules: [
                    {
                      required: true,
                      message: "请输入项目名称",
                    },
                  ],
                })(<Input placeholder="请输入项目名称" />)}
                {
                    projectDetail && projectDetail.type && projectDetail.type !== 0 ?
                      <span className="color-grey-9">该项目导入于 <a className="color-grey-6" target="_blank" href={projectDetail.mirror_url}>{projectDetail.mirror_url}</a></span>
                      : ""
                }
              </Form.Item>
              <div className="df" style={{ alignItems: "center" }}>
                <span className="mr20 mb15 font-16">可见性</span>
                <Form.Item label="">
                  {getFieldDecorator("private", {
                    rules: [],
                  })(
                    <Checkbox
                      checked={private_check}
                      onChange={this.changePrivate}
                      disabled={forked_from_project_id}
                    >
                      <span className="color-grey-9">将仓库设为私有</span>
                      <span className="color-grey-6">
                        { forked_from_project_id ?`（Fork仓库的可见性实时同步自源仓库，不支持直接修改）`:`（修改仓库的可见性，将会影响到该仓库下所有Fork仓库的可见性）`}
                      </span>
                    </Checkbox>
                  )}
                </Form.Item>
              </div>
              <Form.Item 
                label={<span>项目标识 <span className="color-grey-9">(项目url标识部分，更改项目标识将导致原仓库地址失效)</span></span>}
              >
                {getFieldDecorator("project_identifier", {
                  rules: [
                    {
                      required: true,
                      message: "请输入项目标识",
                    },
                  ],
                })(
                  <Input placeholder="项目标识请使用与项目相关的英文关键字" maxLength="100" />
                )}
              </Form.Item>
              <Form.Item label="项目简介">
                {getFieldDecorator("project_description", {
                  rules: [],
                })(
                  <TextArea
                    placeholder="请输入项目简介"
                    style={{ height: "80px" }} maxLength={200}
                  />
                )}
              </Form.Item>
              <Form.Item label="项目类别">
                {getFieldDecorator("project_category_id", {
                  rules: [],
                })(
                  <Select>
                    <Option key={0} value={""}>未选择项目类别</Option>
                  {CategoryList}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="项目语言">
                {getFieldDecorator("project_language_id", {
                  rules: [],
                })(
                  <Select>
                    <Option key={0} value={""}>未选择项目语言</Option>
                    {LanguageList}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="项目导航">
                {getFieldDecorator("project_units", {
                  rules: [],
                })(
                  <Checkbox.Group>
                    {
                      menu.map((item,key)=>{
                        return(
                          <Checkbox 
                            key={key} 
                            value={item.index} 
                            disabled={item.index === "home" || item.index === "activity" || item.index === "code" || (mirror && (type && type===2) && item.index === "pulls")}
                          >{item.name}</Checkbox>
                        )
                      })
                    }
                  </Checkbox.Group>
                )}
              </Form.Item>
              <p className="clearfix">
                <a className="submitBtn" onClick={this.resetSetting}>
                  更新仓库设置
                </a>
              </p>
            </Form>
            {/* 镜像设置部分，暂无接口，先不显示 */}
            {/* <Mirror /> */}
          </WhiteBack>
          {
            projectDetail && projectDetail.permission && (projectDetail.permission === "Admin" || projectDetail.permission === "Owner")?
            <WhiteBack className="dangerousBox mb20">
              <div>
                <div className="dangerousTitle">危险操作区</div>
                <div className="flex-a-center padding15-10" style={{borderBottom:"1px solid #f9edbe"}}>
                  <div>
                    <p className="font-bd font-16">转移仓库</p>
                    <p className="mt10">
                      {
                        is_transfering ?
                        <span>此仓库正在转移给【
                          {transfer && <Link to={transfer.login}>{transfer.name}</Link>}
                          】，请联系对方接收此仓库。</span>
                        :
                        `将此仓库转移给其他用户或组织`
                      }
                    </p>
                  </div>
                  {
                    is_transfering ? 
                    <a onClick={this.CancelDivertProject} className="red_deleteBtn">取消转移</a>
                    :
                    <a onClick={this.DivertProject} className="red_deleteBtn">转移</a>
                  }
                </div>
                <div className="flex-a-center padding15-10">
                  <div>
                    <p className="font-bd font-16">删除本仓库</p>
                    <p className="mt10">
                      删除仓库是永久性的,
                      无法撤消，且删除后，与仓库关联的项目/任务/合并请求/版本发布等，均会被删除
                    </p>
                  </div>
                  <a onClick={this.deleteProject} className="red_deleteBtn">
                    删除本仓库
                  </a>
                </div>
              </div>
            </WhiteBack>
            :""
          }
        </Spin>
      </div>
    );
  }
}
const WrappedSettingIndexForm = Form.create({ name: "settingForm" })(Setting);
export default WrappedSettingIndexForm;
