import React , { useState , useEffect } from 'react';
import { Form , Input, Button } from 'antd';
import ColorCard from './colorCard';
import axios from 'axios';

function AddTagsBox({onSuccess , form ,owner , projectsId,onCancel}){
  const { getFieldDecorator , getFieldsValue , validateFields } = form;  
  const [ colors , setColors ] = useState(undefined);
  const [ defaultColor , setDefaultColor ]= useState(undefined);

  useEffect(()=>{
    const c = Math.random().toString(16).substr(-6);
    c && setDefaultColor(`#${c}`);
  },[])

  function saveFunc(){
    validateFields((error,values)=>{
      if(!error){
        const { desc , name } = getFieldsValue();
        const url = `/v1/${owner}/${projectsId}/issue_tags`;
        axios.post(url,{
          name,description:desc,color:colors || defaultColor
        }).then(result=>{
          result && onSuccess();
        }).catch(error=>{})
      }
    })
  }

  function getColor(colors){
    setColors(colors);
  }
  
  return(
    <Form className="addTags_form" hideRequiredMark={true}>
      <p className="manageTitle"><i className="iconfont icon-xiangzuojiantou font-15 color-grey mr5 cursor" onClick={onCancel}/>创建标记</p>
      <div className="inline">
        <Form.Item colon={false} style={{flex:1,marginRight:'20px'}}>
          {getFieldDecorator('name',{
            rules:[
              {
                required:true,
                message:"请输入标记名称"
              }
            ],
            validateTrigger:"onInput",
          })(<Input placeholder="标记名称15字以内" maxLength={15}/>)}
        </Form.Item>
        <Form.Item style={{marginTop:"7px"}}>
          <ColorCard getColor={getColor} defaultColor={defaultColor}/>
        </Form.Item>
      </div>
      <Form.Item colon={false}>
        {getFieldDecorator('desc',{rules:[],
          validateTrigger:"onInput",
        })(<Input placeholder="描述30字以内" maxLength={30}/>)}
      </Form.Item>
      <div style={{textAlign:'center'}}>
        <Button style={{width:"80px"}} className="cancelTags" onClick={onCancel}>取消</Button>
        <Button style={{width:"80px"}} className="ml20" type="primary" onClick={saveFunc}>确认</Button>
      </div>
    </Form>
  )
}
export default Form.create({ name: 'Bind' })(AddTagsBox);