import {useState} from "react";
import {Profile} from '@/store'
import PopPut from "@/components/popPut/popPut";
import {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, token} = 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 && name.length < 2) {
      Taro.showToast({title: "名称不能小于2个字", icon: 'error'})
      return
    }
    const res = await userApi.putName(user?.id!, name)
    if (res) {
      setUser(res)
      setShow(!show)
      Taro.showToast({title: '修改成功'})
    }
  }

  function outLogin() {
    Taro.showModal({
      title: '是否确定退出登录',
      success({confirm}) {
        confirm && empty(true, true)
      }
    })
  }

  function putAvatar(filePath: string) {
    Taro.showLoading({title: "正在上传图片"})
    Taro.uploadFile({
      url: process.env.TARO_APP_API + '/api/v1/user/avatar',
      filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success(res) {
        Taro.hideLoading()
        if (res.statusCode === 200) {
          const data: User = JSON.parse(res.data).data
          setUser(data)
          Taro.showToast({title: "图片上传成功"})
        } else {
          Taro.showToast({title: "图片上传失败", icon: 'error'})
        }
      },
      fail() {
        Taro.showToast({title: "图片上传失败", icon: 'error'})
      }
    })
  }

  function selectAvatar() {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        if (!res.tempFiles.length) return;
        const file = res.tempFiles[0]
        if (file.size > 40960000) {
          Taro.compressImage({
            src: file.path,
            quality: 50,
            compressedWidth: 50,
            compressHeight: 50,
            success(res) {
              putAvatar(res.tempFilePath)
            }
          })
        } else {
          putAvatar(file.path)
        }
      }
    })
  }

  return (
    <>
      <View className={styles.box}>
        <PopPut title='头像' image={user?.avatar} no_border onClick={selectAvatar}/>
        <PopPut title='手机号' content={user?.phone_number?.replace(user?.phone_number.slice(3, 7), "****")} chevron
                no_border/>
        <PopPut title='昵称' content={user?.name} isProp show={show} no_border>
          <View className='p-2'>
            <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'>限制2-20个字符，可由中英文、数字、“_”、“-”组成</View>
            <MyButton onClick={putName}>确定</MyButton>
          </View>
        </PopPut>

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


export default List
