<script setup lang="ts">
import type { UploadFile } from 'ant-design-vue/es/upload/interface'

import { h, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'
import { InBoxIcon } from '@vben/icons'

import { Modal, Upload, Select, message } from 'ant-design-vue'

import type { Resident_unitQuery } from '#/api/property/resident/unit/model'
import { resident_unitList } from '#/api/property/resident/unit'
import { personImportFace } from '#/api/property/resident/person'

const emit = defineEmits<{ reload: [] }>()

const UploadDragger = Upload.Dragger

const [BasicModal, modalApi] = useVbenModal({
  onCancel: handleCancel,
  onConfirm: handleSubmit,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null
    }

    const params: Resident_unitQuery = {
      pageNum: 1,
      pageSize: 500,
    }

    const res = await resident_unitList(params)
    unitOptions.value = res.rows
  }
})

const unitOptions = ref<any[]>([])
const fileList = ref<UploadFile[]>([])
const unitId = ref<number>()
const fieldNames = {
  value: 'id',
  label: 'name',
}

async function handleSubmit() {
  try {
    modalApi.modalLoading(true)
    if (fileList.value.length !== 1) {
      handleCancel()
      return
    }
    if (!unitId.value) {
      message.error('请选择单位！')
      return
    }
    const data = {
      file: fileList.value[0]!.originFileObj as Blob,
      unitId: unitId.value,
    }
    // console.log(data)
    // const code = 200
    // const msg = '成功'
    const { code, msg } = await personImportFace(data)
    let modal = Modal.success
    if (code === 200) {
      emit('reload')
    } else {
      modal = Modal.error
    }
    handleCancel()
    modal({
      content: h('div', {
        class: 'max-h-[260px] overflow-y-auto',
        innerHTML: msg, // 后台已经处理xss问题
      }),
      title: '提示',
    })
  } catch (error) {
    console.warn(error)
    modalApi.close()
  } finally {
    modalApi.modalLoading(false)
  }
}

function handleCancel() {
  modalApi.close()
  fileList.value = []
}
</script>

<template>
  <BasicModal :close-on-click-modal="false" :fullscreen-button="false" title="用户人脸导入">
    <!-- z-index不设置会遮挡模板下载loading -->
    <!-- 手动处理 而不是放入文件就上传 -->
    <UploadDragger v-model:file-list="fileList" :before-upload="() => false" :max-count="1" :show-upload-list="true"
      accept=".zip">
      <p class="ant-upload-drag-icon flex items-center justify-center">
        <InBoxIcon class="text-primary size-[48px]" />
      </p>
      <p class="ant-upload-text">点击或者拖拽到此处上传文件</p>
    </UploadDragger>
    <div class="mt-2 flex flex-col gap-2">
      <div class="flex items-center gap-2">
        <span>允许导入.zip文件</span>
      </div>
      <div class="flex items-center gap-2">
        <span>
          选择单位：
        </span>
        <Select :options="unitOptions" :fieldNames="fieldNames" v-model:value="unitId" style="width: 250px;" />
      </div>
    </div>
  </BasicModal>
</template>
