import React, { useState, useEffect, useCallback, forwardRef } from "react";
import styled from "styled-components";
import { AutoComplete, Select, Input, Checkbox, Button, Form } from "antd";

import Editor from "../../modules/tpm/challengesnew/tpm-md-editor";
import Upload from "../Upload/Index";
import Attachments from "../Upload/attachment";
import axios from "axios";
import "./version.css";
import UploadImg from "../Images/upload.png";
import { getBranch } from '../GetData/getData';

const { Option } = AutoComplete;

export default Form.create()(
  forwardRef(
    (
      { form, projectDetail , match, showNotification, history },
      ref
    ) => {
      const { getFieldDecorator, validateFields, setFieldsValue } = form;
      const [tagList, setTagList] = useState(undefined);
      const [branchList, setBranchList] = useState(undefined);
      const [desc, setDesc] = useState(null);
      const [fileList, setFileList] = useState(undefined);
      const [attachment, setAttachment] = useState(undefined);
      const [options , setOptions] = useState(undefined);


      const repo_id = projectDetail && projectDetail.repo_id;
      const { projectsId, versionId , owner } = match.params;
      useEffect(()=>{
        getBranchs(projectsId,owner);
      },[projectsId])
    
      async function getBranchs(id,owner){
        let result = await getBranch(id,owner);
        setBranchList(result);
      }
      
      const Span = styled.span`
        margin: 0px 15px;
        color: #bbb;
        line-height: 35px;
      `;


      useEffect(() => {
        if (versionId) {
          const url = `/${owner}/${projectsId}/releases/${versionId}/edit.json`;
          axios.get(url).then(result => {
            if (result) {
              setFieldsValue(result.data);
              setDesc(result.data.body);
              setAttachment(result.data.attachments);
            }
          });
        }
      }, [versionId]);

      useEffect(() => {
        if (projectsId) {
          const url = `/${owner}/${projectsId}/tags.json`;
          axios
            .get(url,{params:{
              limit:1000
            }})
            .then(result => {
              if (result) {
                setTagList(result.data);
                setOptions(renderTagList(result.data));
              }
            })
            .catch(error => {
              console.log(error);
            });
        }
      }, [projectsId]);

      function renderTagList(list) {
        if (list) {
          let array = list.map((item, key) => {
            return (
              <Option key={key} value={item.name}>
                {item.name}
              </Option>
            );
          });
          return array || undefined;
        }
      }
      function submit() {
        validateFields((err, value) => {
          if(err)return;
          if (versionId) {
            let url = `/${owner}/${projectsId}/releases/${versionId}.json`;
            axios
              .put(url, {
                ...value,
                body: desc,
                attachment_ids: fileList
              })
              .then(result => {
                if (result) {
                  showNotification("版本修改成功！");
                  history.push(`/projects/${owner}/${projectsId}/releases`);
                }
              });
          } else {
            let url = `/${owner}/${projectsId}/releases.json`;
            axios.post(url, {
              ...value,
              body: desc,
              attachment_ids: fileList
            })
            .then(result => {
              if (result) {
                showNotification("版本发布成功！");
                history.push(`/projects/${owner}/${projectsId}/releases`);
              }
            });
          }
        });
      }

      const helper = useCallback(
        (label, name, rules, widget, isRequired = true) => (
          <React.Fragment>
            <span required={isRequired}>{label}</span>
            <Form.Item>
              {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
            </Form.Item>
          </React.Fragment>
        ),
        []
      );
      // 输入标签名
      function changeAuto(value){
        let l = tagList.filter(item=>item.name.indexOf(value) > -1);
        setOptions(renderTagList(l));
      }
      return (
        <div className="main df">
          <Form className="versionForm">
            <div>
              <p className="font-16 color-grey-3 mb15">{versionId?"编辑":"创建"}发行版</p>
              <div>
                <div className="itemInline">
                  {helper(
                    "",
                    "tag_name",
                    [{ required: true, message: "请输入获取或选择一个标签" }],
                    <AutoComplete
                      placeholder="标记一个版本"
                      onChange={changeAuto}
                      style={{ width: "200px" }}
                    >
                      {options}
                    </AutoComplete>
                  )}
                  <Span>@</Span>
                  {helper(
                    "",
                    "target_commitish",
                    [{ required: true, message: "请选择一个分支" }],
                    <Select
                      placeholder="请选择一个分支"
                      style={{ width: "200px" }}
                      showArrow={false}
                    >
                      {renderTagList(branchList)}
                    </Select>
                  )}
                </div>
                <p className="font-13 color-grey-8">
                  选择一个已经存在的标签，或者在发布时新建一个标签
                </p>
              </div>
              <div className="pt20">
                {helper(
                  "",
                  "name",
                  [{ required: true, message: "请输入发行版的标题" }],
                  <Input placeholder="发行版的标题" />
                )}
              </div>
              <div>
                <Editor
                  placeholder={"描述此发行版"}
                  height={200}
                  mdID={`version-comments-description`}
                  initValue={desc}
                  onChange={setDesc}
                />
              </div>
              <div className="set-ant-row">
                {helper(
                  "",
                  "prerelease",
                  [],
                  <Checkbox>这是一个预览版本</Checkbox>
                )}
              </div>
              <div>
                <Upload
                  className="versionStyle"
                  isComplete={true}
                  load={setFileList}
                  icon={
                    <img
                      src={UploadImg}
                      width="58"
                      alt=""
                      style={{ marginBottom: 15 }}
                    />
                  }
                  size={100}
                  showNotification={showNotification}
                />
                {versionId && attachment && attachment.length > 0 ? (
                  <Attachments
                    attachments={attachment}
                    showNotification={showNotification}
                    canDelete={true}
                  />
                ) : (
                  ""
                )}
              </div>
              <p className="pt20">
                <Button onClick={submit} type="primary" className="mr30">
                  {versionId ? "保存" : "创建"}发行版
                </Button>
                <Button
                  onClick={() =>
                    history.push(`/projects/${owner}/${projectsId}/releases`)
                  }
                  style={{
                    backgroundColor: "rgba(187,187,187,1)",
                    color: "#fff"
                  }}
                >
                  取消
                </Button>
              </p>
            </div>
          </Form>
          <div className="versionTips">
            <div className="infosTip">
              <p className="font-16 mb15">标签命名建议</p>
              <p className="mb15">
                通常的做法是在版本名称前加上字母 v 前缀， v1.0 或者 v2.3.4。
              </p>
              <p>
                如果标签不适合在生产环境下使用，请在版本名称后添加预发行版本。例如：v0.2-alpha
                或者 v5.9-beta.3。
              </p>
            </div>
            <div className="infosTip">
              <p className="font-16 mb15">语义化版本</p>
              <p className="mb15">
                如果你是第一次发布版本，我们强烈建议你阅读语义化版本。
              </p>
            </div>
            <div className="infosTip">
              <p className="font-16 mb15">附件大小说明</p>
              <p className="mb15">
                单个附件不能超过 100M（GVP 项目200M），每个仓库总附件不可超过
                1G（推荐项目不可超过 5G；GVP 项目不可超过
                20G）。附件总容量统计包括仓库附件和发行版附件。
              </p>
            </div>
          </div>
        </div>
      );
    }
  )
);
