import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Button, Loading, CellGroup, Input, Form} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {AppUser} from "@/api/app/appUser/model";
import {getAppUser, updateAppUser} from "@/api/app/appUser";

const AddAppUser = () => {
  const {params} = useRouter();
  const [loading, setLoading] = useState<boolean>(true)
  const [FormData, setFormData] = useState<AppUser>({})
  const formRef = useRef<any>(null)

  const reload = async () => {
    if (params.id) {
      const data = await getAppUser(Number(params.id))
      setFormData(data)
    } else {
      setFormData({})
    }
  }

  const submitSucceed = async (values: any) => {
    try {
      if (params.id) {
        await updateAppUser({
          ...values,
          id: Number(params.id)
        })
      }

      Taro.showToast({
        title: `操作成功`,
        icon: 'success'
      })

      setTimeout(() => {
        return Taro.navigateBack()
      }, 1000)
    } catch (error) {
      Taro.showToast({
        title: `操作失败`,
        icon: 'error'
      });
    }
  }

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  useEffect(() => {
    reload().then(() => {
      setLoading(false)
    })
  }, []);

  if (loading) {
    return <Loading className={'px-2'}>加载中</Loading>
  }

  return (
    <>
      <Form
        ref={formRef}
        divider
        initialValues={FormData}
        labelPosition="left"
        onFinish={(values) => submitSucceed(values)}
        onFinishFailed={(errors) => submitFailed(errors)}
        footer={
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              width: '100%'
            }}
          >
            <Button
              nativeType="submit"
              type="success"
              size="large"
              className={'w-full'}
              block
            >
              更新
            </Button>
          </div>
        }
      >
        <CellGroup style={{padding: '4px 0'}}>
          <Form.Item name="userName" label="用户名" initialValue={FormData.userName}>
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="nickName" label="昵称" initialValue={FormData.nickName}>
            <Input placeholder="请输入昵称" />
          </Form.Item>
          <Form.Item name="email" label="邮箱" initialValue={FormData.email}>
            <Input placeholder="请输入邮箱" />
          </Form.Item>
        </CellGroup>
      </Form>
    </>
  );
};

export default AddAppUser;
