import React , { forwardRef, useEffect } from 'react';
import {Form , Modal , Input, Select } from 'antd';
import "./sub.scss";
import axios from 'axios';
import { useState } from 'react';
const { TextArea } = Input;
function UpdateDescModal({form , visible , onCancel , onOk,desc,website,lesson_url, topicsInfo}){
  const { getFieldDecorator, validateFields , setFieldsValue } = form;
  const [topics, setTopics] = useState(undefined);

  useEffect(()=>{
    // 获取所有的项目标签
    axios.get(`/v1/project_topics`).then(res=>{
      if(res && res.data){
        setTopics(res.data.project_topics);
      }
    })
  }, [])

  useEffect(()=>{
    if(desc || website){
      setFieldsValue({
        website,desc,lesson_url
      })
    }
  },[desc,website])

  function onSure(){
    validateFields((err,values)=>{
      if(!err){
        onCancel();
        onOk(values.desc,values.website,values.lesson_url, values.project_topic_names)
      }
    })
  }

  // 校验项目标签
  function checkTopics(rule, value, callback){
    const boolLength = value.filter(item=>item.length > 20);
    const bool = value.filter(item=>!/^(?![-])[a-zA-Z0-9\u4e00-\u9fa5\\-]+$/.test(item));
    if(value.length > 5){
      callback("最多创建5个标签");
    }else if(boolLength.length){
      callback("每个标签最多支持20个汉字");
    }else if(bool.length){
      callback("标签名只允许包含中文、字母、数字或者中划线(-), 不能以中划线开头");
    }
    callback();
  }

  return(
    <Modal
      title={"修改信息"}
      closable={false}
      visible={visible}
      centered
      onCancel={onCancel}
      onOk={onSure}
      okText="确定"
      cancelText="取消"
      width="520px"
      className={"descmodal"}
      maskClosable={false}
    >
      <Form>
        <Form.Item label="项目简介">
          {getFieldDecorator("desc",{
            rules:[]
          })(
            <TextArea placeholder="请输入项目简介" rows={4} maxLength={200}/>
          )}
        </Form.Item>
        <Form.Item label="项目标签">
          {getFieldDecorator("project_topic_names",{
            rules:[{validator:checkTopics}],
            initialValue: topicsInfo && topicsInfo.map(item=>item.name)
          })(
            <Select mode='tags' placeholder="请输入标签名称" getPopupContainer={trigger => trigger.parentNode} maxLength={2}>
              {topics && topics.map(item=> <Select.Option key={item.name}>{item.name}</Select.Option>)}
            </Select>
          )}
        </Form.Item>
        <Form.Item label="website">
          {getFieldDecorator("website",{
            rules:[]
          })(
            <Input placeholder="website链接" maxLength={200}/>
          )}
        </Form.Item>
        <Form.Item label="实践课程">
          {getFieldDecorator("lesson_url",{
            rules:[]
          })(
            <Input placeholder="实践课程链接" maxLength={200}/>
          )}
        </Form.Item>
      </Form>
    </Modal>
  )
}
export default Form.create()(forwardRef(UpdateDescModal));