<template>
  <IxForm :control="userInfoForm"
      class="user-info-form"
      label-align="end"
      layout="horizontal"
      message-tooltip
      @submit.prevent="submitHandler">
    <IxFormItem>
      <IxTooltip placement="top" title="昵称">
        <IxInput control="nickname" placeholder="请输入昵称"/>
      </IxTooltip>
    </IxFormItem>
    <IxFormItem>
      <IxTooltip placement="top" title="头像">
        <IxUpload
            v-model:files="files"
            :action="uploadBaseUrl"
            :max-count="1"
            :progress="{
      strokeColor: {
        '0%': '#108EE9',
        '100%': '#87D068',
      },
      strokeWidth: 3,
    }"
            :request-data="requestData"
            @requestChange="showMsg"

        >
          <IxButton>上传头像</IxButton>
          <template #list>
            <IxUploadFiles :icon="{file: 'paper-clip', remove: 'close', retry: 'redo'}" type="image"/>
          </template>
        </IxUpload>
      </IxTooltip>
    </IxFormItem>
    <IxButton block class="denglu-btn" mode="primary" type="submit">确定</IxButton>
  </IxForm>
</template>

<script lang="ts" setup>

import { useFormGroup } from '@idux/cdk'
import HeaderBarApi from '@/pages/main-zone/header-bar/header-bar-api.ts'
import { reloadUserInfo } from '@/common/app'
import { uploadBaseUrl } from '@/common'
import {
  UploadFile,
  UploadRequestChangeOption
} from '@idux/components'
import AppApi from '@/common/app/app-api.ts'
import Toast from '@/components/toast'

const files = ref()

const userInfoForm = useFormGroup<SettingsTypes.UserInfoForm>({
  avatar: [ undefined ],
  nickname: [ undefined ],
})

function submitHandler() {
  const loading = Toast.loading('正在提交')
  const value = userInfoForm.getValue()
  HeaderBarApi.modifyInfo(value)
      .then(reloadUserInfo)
      .finally(() => {
        Toast.close(loading)
        userInfoForm.reset()
        userInfoForm.markAsPristine()
        files.value = []
      })
}

async function requestData({name, raw}: UploadFile) {
  if (raw == null) return Promise.reject()
  let res = await AppApi.obtainPresignedUrl(name)
  const avatar = userInfoForm.get('avatar')
  avatar?.setValue('/' + res.data.bucketName + '/' + res.data.objectName)
  delete res.data.bucketName
  delete res.data.objectName
  return Promise.resolve(res.data)
}

let loading: string | null = null

function showMsg({status}: UploadRequestChangeOption) {
  if (status === 'loadstart') {
    loading = Toast.loading('正在上传')
  } else if (status === 'loadend') {
    if (loading != null) Toast.close(loading)
    Toast.success('上传成功')
  } else if (status === 'error') {

    if (loading != null) Toast.close(loading)
    Toast.error('上传失败')
  } else if (status === 'abort') {
    if (loading != null) Toast.close(loading)
  }
}
</script>

<style lang="stylus" scoped>
.user-info-form {
  padding: 1rem 0;
  height 100%
  display grid
  grid-template-columns 80%
  grid-template-rows 1fr 1fr 1fr 1fr
  justify-content center
  align-content: space-evenly
}

:deep(.ix-upload-selector ),
:deep(.ix-upload-selector .ix-button) {
  width 100%
}
</style>
