import React, { useState, useEffect, forwardRef } from "react";
import styled from "styled-components";
import { AutoComplete , Input, Checkbox, Button, Form } from "antd";
import SelectBranch from '../../Branch/Select';

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.scss";
import { trim } from "lodash";

const { Option } = AutoComplete;

const Span = styled.span`
  margin: 0px 15px;
  color: #bbb;
  line-height: 35px;
  font-size:16px;
  font-weight:400;
  color:#666;
`;
export default Form.create()(
  forwardRef(
    (
      { form, projectDetail , match, showNotification, history },
      ref
    ) => {
      const { getFieldDecorator, validateFields, setFieldsValue } = form;
      const [tagList, setTagList] = useState(undefined);
      const [desc, setDesc] = useState(null);
      const [branch, setBranch ] = useState(null);
      const [fileList, setFileList] = useState(undefined);
      const [attachment, setAttachment] = useState(undefined);
      const [options , setOptions] = useState(undefined);
      const stable = history && history.location && history.location.state&&history.location.state.stable;
      const { projectsId, versionId , owner } = match.params;
      
      useEffect(()=>{
        if(projectDetail && projectDetail.default_branch){
          setBranch(projectDetail.default_branch);
        }
      },[projectDetail])


      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.tags);
                setOptions(renderTagList(result.data.tags));
              }
            })
            .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,
                target_commitish:branch
              })
              .then(result => {
                if (result) {
                  showNotification("版本修改成功！");
                  history.push(`/${owner}/${projectsId}/releases`);
                }
              });
          } else {
            let url = `/${owner}/${projectsId}/releases.json`;
            axios.post(url, {
              ...value,
              body: desc,
              attachment_ids: fileList,
              target_commitish:branch
            })
            .then(result => {
              if (result) {
                showNotification("版本发布成功！");
                history.push(`/${owner}/${projectsId}/releases`);
              }
            });
          }
        });
      }
      // 输入标签名
      function changeAuto(value){
        let l = tagList && tagList.length > 0 ? tagList.filter(item=>item.name.indexOf(value) > -1) :[];
        setOptions(renderTagList(l));
      }

      function changeBranch(params) {
        setBranch(params);
      }

      return (
        <div className="df pt15">
          <Form className="versionForm">
            <div className="itemInline">
              <Form.Item>
                {getFieldDecorator("tag_name", 
                  { rules:[
                    { required: true, message: "请输入获取或选择一个标签" },
                    { validator: (rule,val,callback) =>{
                        if(val.length>30 || val.indexOf(' ')>0 || val.match(/^\s+$/) || trim(val).length!=val.length){
                          callback('无效的标签名称，请参考右侧建议命名标签并确认长度在1~30个字符之间');
                        }else{
                          callback();
                        }
                    }}], 
                    validateFirst: true 
                  })(
                  <AutoComplete
                    placeholder="标记一个版本"
                    onChange={changeAuto}
                    style={{ width: "200px" }}
                  >
                    {options}
                  </AutoComplete>
                )}
              </Form.Item>
              <Span>@</Span>
              <SelectBranch
                repo_id={projectDetail && projectDetail.repo_id}
                projectsId={projectsId}
                branch={branch}
                changeBranch={changeBranch}
                owner={owner}
                history={history}
                tagflag={false}
                branchList={projectDetail && projectDetail.branches && projectDetail.branches.list}
              ></SelectBranch>
              <p className="font-12 color-grey-6 weight400">选择一个已经存在的标签，或者在发布时新建一个标签</p>
            </div>
            <Form.Item className="pt20">
              {getFieldDecorator("name", 
                { rules:[
                  { required: true, message: "请输入发行版的标题" },
                  { validator: (rule,val,callback) =>{
                      if(val.length>50){
                        callback('标题长度在1~50个字符之间');
                      }else{
                        callback();
                      }
                  }}], 
                  validateFirst: true 
                })(
                  <Input placeholder="发行版的标题" />
              )}
            </Form.Item>
            <Editor
              placeholder={"描述此发行版"}
              height={200}
              mdID={`version-comments-description`}
              initValue={desc}
              onChange={setDesc}
              noStorage={true}
            />
            
            <div className="mt5 dragBox">
              <Upload
                className="versionStyle"
                isComplete={true}
                load={setFileList}
                icon={
                  <i className="iconfont icon-shangchuanicon dragIcon" />
                }
                size={100}
                showNotification={showNotification}
              />
              {versionId && attachment && attachment.length > 0 ? (
                <Attachments
                  attachments={attachment}
                  showNotification={showNotification}
                  canDelete={true}
                />
              ) : (
                ""
              )}
            </div>
            <Form.Item className="prerelease">
              {getFieldDecorator("prerelease", 
                { rules:[], 
                  validateFirst: true 
                })(
                  <Checkbox defaultChecked={!stable}>这是一个预览版本</Checkbox>
              )}
            </Form.Item>
            <p className="pt20 pb20" style={{borderTop:"1px solid #eee"}}>
              <Button onClick={submit} type="primary" className="mr30 btnblue">
                {versionId ? "保存" : "创建"}发行版
              </Button>
              <Button
                onClick={() =>history.push(`/${owner}/${projectsId}/releases`)} className="btngrey"
              >取消</Button>
            </p>
          </Form>
          <div className="versionTips">
            <div className="infosTip">
              <p className="font-16 mb14 weight">标签命名建议</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 mb14 weight">语义化版本</p>
              <p>
                如果你是第一次发布版本，我们强烈建议你阅读<a href='https://semver.org/lang/zh-CN' target='_blank' className="color-blue">语义化版本</a>。
              </p>
            </div>
            <div className="infosTip">
              <p className="font-16 mb14 weight">附件大小说明</p>
              <p>
                单个附件不能超过 100M（GVP 项目200M），每个仓库总附件不可超过
                1G（推荐项目不可超过 5G；GVP 项目不可超过
                20G）。附件总容量统计包括仓库附件和发行版附件。
              </p>
            </div>
          </div>
        </div>
      );
    }
  )
);
