import {useEffect, useState, useRef} from "react";
import {useRouter} from '@tarojs/taro'
import {Button, Loading, CellGroup, Input, TextArea, Form} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {View} from '@tarojs/components'
import {${entity}} from "@/api/${package.ModuleName}/${table.entityPath}/model";
import {get${entity}, list${entity}, update${entity}, add${entity}} from "@/api/${package.ModuleName}/${table.entityPath}";

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

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

  // 提交表单
  const submitSucceed = async (values: any) => {
    try {
      if (params.id) {
        // 编辑模式
        await update${entity}({
          ...values,
          id: Number(params.id)
        })
      } else {
        // 新增模式
        await add${entity}(values)
      }

      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
            >
              {params.id ? '更新' : '保存'}
            </Button>
          </div>
        }
      >
        <CellGroup style={{padding: '4px 0'}}>
<% for(field in table.fields){ %>
<% if(field.propertyName != 'id' && field.propertyName != 'createTime' && field.propertyName != 'updateTime'){ %>
          <Form.Item name="${field.propertyName}" label="${field.comment!field.propertyName}" initialValue={FormData.${field.propertyName}} required>
<% if(field.propertyType == 'String' && field.comment?? && (field.comment?contains('描述') || field.comment?contains('备注') || field.comment?contains('内容'))){ %>
            <TextArea maxLength={200} placeholder="请输入${field.comment!'内容'}"/>
<% } else { %>
            <Input placeholder="请输入${field.comment!'字段'}" maxLength={50}/>
<% } %>
          </Form.Item>
<% } %>
<% } %>
        </CellGroup>
      </Form>
    </>
  );
};

export default Add${entity};
