import {useState} from "react";
import {Profile} from '@/store'
import avatar from "@/static/img/avatar.png"
import PopPut from "@/components/popPut/popPut";
import {Button, Input, View} from "@tarojs/components";
import Taro from "@tarojs/taro";
import {userApi} from "@/api";
import styles from './userInfo.module.scss'
import MyButton from "@/components/button/MyButton";


const List = () => {
  const {empty, user, setUser} = Profile.useContainer()
  const [show, setShow] = useState(false)
  const [name, setName] = useState<string>(user?.name || '')

  function unbind() {
    Taro.showModal({
      title: '解绑微信',
      async success({confirm}) {
        if (confirm) {
          const res = await userApi.unbind(user?.id!)
          if (res) {
            empty()
          }
        }
      }
    })
  }

  async function putName() {
    if (!name) {
      Taro.showToast({title: "名称不能为空", icon: 'error'})
      return
    }
    const res = await userApi.putName(user?.id!, name)
    if (res) {
      setUser(res)
      setShow(!show)
      Taro.showToast({title: '修改成功'})
    }
  }


  return (
    <>
      <View className={styles.box}>
        <PopPut title='头像' image={avatar} chevron no_border/>
        <PopPut title='手机号' content={user?.phone_number} chevron no_border/>
        <PopPut title='昵称' content={user?.name} isProp show={show} no_border>
          <View className='py-4 px-3'>
            <View className='text-center font-weigh mb-3'>修改昵称</View>
            <Input className='input'
                   placeholder='请输入昵称'
                   onInput={(event) => setName(event.detail.value)}
                   cursorSpacing={110}
                   value={name}
            />
            <View className='text-muted my-3 font-24'>限制4-20个字符，可由中英文、数字、“_”、“-”组成</View>
            <Button className={styles.button} onClick={putName}>确定</Button>
          </View>
        </PopPut>

        <PopPut title='解绑微信' onClick={unbind} no_border/>
      </View>
      <View className={styles.buttonFixed}>
        <MyButton onClick={empty}>退出登录</MyButton>
      </View>
    </>
  )
}


export default List
