<script setup lang="tsx">
import { mj_form_upload } from '#/components/mj/mj-table'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

defineOptions({ name: 'ImportData' })
const props = withDefaults(
  defineProps<{
    fileKey?: string
    fileTypes?: any[]
    modelValue?: boolean
    request: (data: any) => Promise<any>
    templateUrl?: string
    title?: any
  }>(),
  {
    fileKey: 'file',
    title: '导入数据',
    fileTypes: undefined,
    templateUrl: undefined,
  },
)
const emits = defineEmits(['update:modelValue', 'success'])
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
    formRef.value?.setData({})
  },
})

const formRef = ref()
const form = {
  titleWidth: 110,
  items: obj.joinObjs<any>(
    !props.templateUrl || {
      span: 24,
      slots: {
        default() {
          return (
            <div style={{ textAlign: 'center' }}>
              <a
                href={props.templateUrl}
                style={{ color: 'blue', textDecoration: 'underline' }}
                target="_blank"
              >
                点击这里下载导入模块
              </a>
            </div>
          )
        },
      },
    },
    {
      required: true,
      span: 24,
      field: props.fileKey,
      // title: '文件',
      itemRender: {
        name: mj_form_upload,
        props: {
          fileTypes: props.fileTypes,
        },
      },
    },
  ),
} as any

const submit = () => {
  const data = formRef.value?.getData()
  if (!data) return
  hud.load({
    task: async () => {
      await props.request({
        [props.fileKey]: data[props.fileKey].file,
      })
      emits('success')
      emits('update:modelValue', false)
    },
    option: '提交',
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title,
      width: 500,
    }"
  >
    <mj-form ref="formRef" :options="form" @submit="submit" />
  </mj-modal>
</template>

<style lang="scss" scoped></style>
