<script lang="ts" setup>
import { useAccessorAndControl } from '@idux/cdk/forms'
import { useFormItemRegister } from '@idux/components/form'
import { uploadBaseUrl } from '@/common'
import {
  UploadFile,
  UploadRequestHandler,
  UploadRequestOption
} from '@idux/components/upload/src/types'
import { UploadRequestChangeOption } from '@idux/components'
import AppApi from '@/common/app/app-api.ts'
import Toast from '@/components/toast'

defineProps<{
  control?: string | number | (string | number)[] | object
  disabled?: boolean
  value?: string | string[]
}>()
const {control: controlRef} = useAccessorAndControl()
useFormItemRegister(controlRef)

const files = ref<UploadFile[]>()

function requestData({name, raw}: UploadFile) {
  if (raw == null) return Promise.reject()
  return AppApi.obtainPresignedUrl(name)
      .then(res => res.data)
}

function customRequest(options: UploadRequestOption<any>): Promise<UploadRequestHandler | void> | UploadRequestHandler | void {
  console.log(options)
  return Promise.resolve()
}

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>

<template>
  <IxUpload
      v-model:files="files"
      :action="uploadBaseUrl"
      :custom-request="customRequest"
      :max-count="1"
      :progress="{
      strokeColor: {
        '0%': '#108EE9',
        '100%': '#87D068',
      },
      strokeWidth: 3,
    }"
      :request-data="requestData"
      @request-change="showMsg"
  >
    <IxButton>上传头像</IxButton>
    <template #list>
      <IxUploadFiles :icon="{file: 'paper-clip', remove: 'close', retry: 'redo'}" type="image"/>
    </template>
  </IxUpload>
</template>

<style lang="stylus" scoped>

</style>
