import React, { useCallback, useEffect, useState } from "react";
import { Input, Button, Form, message } from "antd";
import MDEditor from "../../../modules/tpm/challengesnew/tpm-md-editor";
import {getAgreement, agreementAdd,agreementEdit } from "../api";
import "../index.scss";
import "./index.scss";

export default Form.create()(({ form,current_user, showNotification, match, history }) => {
  const { getFieldDecorator, validateFields, setFieldsValue } = form;

  const [id,setId]=useState(0);
  const [content,setContent]=useState(null);

  useEffect(()=>{
    getAgreement({title:'协议模板'}).then(res=>{
      if(res.data){
        setContent(res.data.content);
        setId(res.data.id);
      }
    })
  },[])

  // 保存,包括新增和修改
  function saveFile() {
    validateFields((err, values) => {
      if (!err) {
       id?agreementEdit({
          ...values,
          userId:current_user.user_id,
          id,
        }).then((res) => dealRes(res)):
        agreementAdd({
          ...values,
          userId:current_user.user_id,
          id:0,
        }).then((res) => dealRes(res))
      }
    })
  }

  function dealRes(res) {
    if (res && res.message === "success") {
      showNotification("操作成功");
    } else {
      message.error(res&&res.message||'操作失败');
    }
  }

  function onContentChange(value) {
    setContent(value);
    setFieldsValue({
      content: value
    });
  };

  const helper = useCallback(
    (label, name, rules, widget, initialValue, rightComponent) => (
      <Form.Item label={label} className="mb0">
        {getFieldDecorator(name, { rules, initialValue, validateFirst: true })(
          widget
        )}
        {rightComponent}
      </Form.Item>
    ),[]);

  return (
    <div className="centerbox task-manage agreement-content">
      {helper(
        "协议名称",
        "title",
        [{ required: true, message: "请输入协议名称" }],
        <Input
          placeholder={"请输入协议名称"}
          maxLength={50}
          disabled
        />,
        "协议模板"
      )}

      <Form.Item className="mb0">
        <MDEditor
          placeholder={"请输入协议内容"}
          height={500}
          mdID={"order-new-description"}
          initValue={content}
          onChange={onContentChange}
          className="mt20"
        ></MDEditor>
        {getFieldDecorator("content", {
          rules: [{ required: true, message: "请输入协议内容" }],
          validateFirst: true,
        })(<Input style={{ display: "none" }} />)}
      </Form.Item>

      <Button className="mt25" type="primary" onClick={saveFile}>
        保存
      </Button>
    </div>
  );
});
