import {useEffect, useState} from "react";
import Taro from '@tarojs/taro'
import {Input, Button,Form} from '@nutui/nutui-react-taro'

const Setting = () => {
  const [FormData, setFormData] = useState<any>(
    {
      domain: undefined
    }
  )

  // 提交表单
  const submitSucceed = (values: any) => {
    if(values.domain){
      Taro.setStorageSync('ServerUrl',values.domain)
      setFormData({
        domain: values.domain
      })
      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      });
      setTimeout(() => {
        Taro.navigateBack()
      },500)
    }
  }

  const submitFailed = (error: any) => {
    console.log(error, 'err...')
    // Taro.showToast({ title: error[0].message, icon: 'error' })
  }
  const reload = () => {
    Taro.hideTabBar()
    if (Taro.getStorageSync('ServerUrl')) {
      setFormData({
        domain: Taro.getStorageSync('ServerUrl')
      })
    }
  }

  useEffect(() => {
    reload()
  }, [])

  return (
    <>
      <Form
        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" block type="info" size={'large'}>
              保存
            </Button>
          </div>
        }
      >
      <div className={'flex flex-col justify-center pt-3'}>
        <div className={'text-sm py-1 px-4'}>服务域名</div>
        <Form.Item
          name="domain"
          initialValue={FormData.domain}
          rules={[{message: '请输入服务域名'}]}
        >
          <Input placeholder="https://domain.com/api" type="text" style={{backgroundColor: '#f5f5f5', borderRadius: '8px', padding: '5px 10px'}}/>
        </Form.Item>
      </div>
      </Form>
    </>
  )
}
export default Setting
