import {Cell, Avatar} from '@nutui/nutui-react-taro';
import {ArrowRight} from '@nutui/icons-react-taro'
import {useEffect, useState} from "react";
import {ConfigProvider} from '@nutui/nutui-react-taro'
import Taro, {getCurrentInstance} from '@tarojs/taro'
import {getUserInfo, updateUserInfo} from "@/api/layout";
import {TenantId} from "@/config/app";
import { TextArea } from '@nutui/nutui-react-taro'
import './profile.scss'

const {router} = getCurrentInstance()
import {
  Form,
  Button,
  Input,
  Radio,
} from '@nutui/nutui-react-taro'
import {DictData} from "@/api/system/dict-data/model";
import {pageDictData} from "@/api/system/dict-data";
import {User} from "@/api/system/user/model";
function Profile() {
  const formId = Number(router?.params.id)

  const [sex, setSex] = useState<DictData[]>()
  const [FormData, setFormData] = useState<User>(
    {
      userId: undefined,
      nickname: undefined,
      realName: undefined,
      avatar: undefined,
      sex: undefined,
      phone: undefined,
      address: undefined,
      comments: undefined
    }
  )

  const reload = () => {
    // 获取数据字典
    pageDictData({limit: 200}).then(res => {
      setSex(res?.list.filter((item) => item.dictCode === 'sex'))
    })
    // 获取用户信息
    getUserInfo().then((data) => {
      // 更新表单数据
      setFormData(data);
    })
  }

  // 提交表单
  const submitSucceed = (values: any) => {
    console.log(values, 'values')
    console.log(formId, 'formId>>')
    updateUserInfo(values).then(() => {
      Taro.showToast({title: `保存成功`, icon: 'success'})
      setTimeout(() => {
        return Taro.navigateBack()
      }, 1000)
    }).catch(() => {
      Taro.showToast({
        title: '保存失败',
        icon: 'error'
      });
    })
  }
  const submitFailed = (error: any) => {
    console.log(error, 'err...')
  }

  const uploadAvatar = ({detail}) => {
    setFormData({
      ...FormData,
      avatar: `${detail.avatarUrl}`,
    })
    Taro.uploadFile({
      url: 'https://server.websoft.top/api/oss/upload',
      filePath: detail.avatarUrl,
      name: 'file',
      header: {
        'content-type': 'application/json',
        TenantId
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code === 0) {
          updateUserInfo({
            userId: FormData?.userId,
            avatar: `${data.data.thumbnail}`
          }).then(() => {
            Taro.showToast({
              title: '上传成功',
            })
          })
        }
      }
    })
  }

  // 获取微信昵称
  const getWxNickname = (nickname: string) => {
    // 更新表单数据
    setFormData({
      ...FormData,
      nickname: nickname
    });
  }

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

  return (
    <>
      <div className={'p-4'}>
        <Cell.Group>
          <Cell title={'头像'} align={'center'} extra={
            <>
              <Button open-type="chooseAvatar" style={{height: '58px'}} onChooseAvatar={uploadAvatar}>
                <Avatar src={FormData?.avatar} size="54"/>
              </Button>
              <ArrowRight color="#cccccc" className={'ml-1'} size={20}/>
            </>
          }
          />
          <Cell title={'手机号码'} align={'center'} extra={FormData?.phone}/>
        </Cell.Group>
        <ConfigProvider>
          <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">
                  提交
                </Button>
              </div>
            }
          >
            <Form.Item
              label={'昵称'}
              name="nickname"
              initialValue={FormData.nickname}
              rules={[{message: '请获取微信昵称'}]}
            >
              <Input
                type="nickname"
                className="info-content__input"
                placeholder="请输入昵称"
                value={FormData?.nickname}
                onInput={(e) => getWxNickname(e.detail.value)}
              />
            </Form.Item>
            <Form.Item
              label="性别"
              name="sex"
              initialValue={FormData.sex}
              rules={[
                {message: '请选择性别'}
              ]}
            >
              <Radio.Group value={FormData?.sex} direction="horizontal">
                {
                  sex?.map((item, index) => (
                    <Radio key={index} value={item.dictDataCode}>
                      {item.dictDataName}
                    </Radio>
                  ))
                }
              </Radio.Group>
            </Form.Item>
            <Form.Item
              label="备注信息"
              name="comments"
              initialValue={FormData.comments}
              rules={[{message: '备注信息'}]}
            >
                <TextArea
                  placeholder={'个性签名'}
                  value={FormData?.comments}
                  onChange={(value) => setFormData({...FormData, comments: value})}
                />
              <Input placeholder={'个性签名'} />
            </Form.Item>
          </Form>
        </ConfigProvider>
      </div>
    </>
  )
}

export default Profile
