import React, { useState, useEffect } from 'react';
import request from 'axios';
import { Message } from '@alifd/next';
// import { useParams } from 'react-router-dom';
import { getParams } from '@/utils/url';
import { getUser, updateUser } from '@/apis';

import BasicForm from '@/components/BasicForm';

const EditBasicForm = ()=> {
  const [user, setUser] = useState({});

  // eslint-disable-next-line no-underscore-dangle
  const _id = getParams()._id;

  useEffect(() => {
    const fetchUser = async () => {
      if (_id) {
        try {
          const result = await request.get(getUser, {
            params: { _id },
          });
          // const result = await request.post(getUser, { _id });

          if (result && result.data) {
            if (result.data.errorMessage) {
              throw new Error(result.data.errorMessage);
            }
            setUser(result.data);
          } else {
            throw new Error('网络错误');
          }
        } catch (err) {
          Message.error(err.message || '网络错误');
        }
      }
    }

    fetchUser();
  }, []);

  const handleSubmit = (value) => {
    request.post(updateUser, { ...value, _id }).then((result) => {
      console.log(result);
      if (result.data && result.data.errorMessage) {
        Message.error(result.data.errorMessage);
      } else {
        Message.success('编辑用户成功');
      }
    }).catch(err => {
      Message.error(err.message || '网络错误');
    });
  };
  const handleCancel = () => {
    window.history.back();
  };

  return (<BasicForm defaultValue={user} onSubmit={handleSubmit} onCancel={handleCancel} />);
};

export default EditBasicForm;
