<script setup lang="ts">
import type {
  UploadFile,
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadRequestOptions,
} from 'element-plus'

import { SYS_INFO } from '@vben/preferences'
import { useAccessStore } from '@vben/stores'

import { ElMessageBox, genFileId } from 'element-plus'

// import localUploadIMG from '#/assets/image/local_upload.png'
import hud from '#/utils/hud'
import { downloadFile } from '#/utils/tool'

type Props = {
  accept?: string
  action: string
  data?: anyObj
  downloadUrl?: string
  headers?: anyObj
  httpRequest?: (options: UploadRequestOptions) => Promise<any>
  limitData?: string[]
  modelValue?: boolean
  name?: string
  placeholder?: string
  showRemark?: boolean
  title?: string
}

const props = withDefaults(defineProps<Props>(), {
  data: undefined,
  accept: undefined,
  downloadUrl: undefined,
  httpRequest: undefined,
  limitData: undefined,
  headers: undefined,
  modelValue: false,
  title: '上传文件',
  name: 'file',
  placeholder: '仅支持*.Word、*.Excel、*.Txt 或 *.Json的文件类型',
})

const emits = defineEmits(['update:modelValue', 'onRefresh'])

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})
const { accessToken } = storeToRefs(useAccessStore())
const remark = ref('')
const upload = ref<UploadInstance>()
// 文件数量
let fileCount = 0
const handleExceed: UploadProps['onExceed'] = (file) => {
  upload.value!.clearFiles()
  const files = file[0] as UploadRawFile
  files.uid = genFileId()
  upload.value!.handleStart(files)
}

const submitUpload = () => {
  if (fileCount === 0) {
    hud.error('请选择文件')
    return
  }
  hud.loading('正在上传中...')
  // upload.value?.fileList
  upload.value?.submit()
}

async function downloadTemplate() {
  // let res = await loadQuestionTemplate();
  downloadFile(`${props.downloadUrl!}?${Date.now()}`)
}

function handleSuccess(response: any) {
  hud.hide()
  if (response.code === 200) {
    hud.success(response.message || response.data)
    emits('onRefresh', response.data)
    show.value = false

    if (typeof response.data === 'string' && response.data.startsWith('http')) {
      // 下载
      downloadFile(response.data)
    }
  } else {
    upload.value!.clearFiles()
    hud.error(response.message)
  }
}

// const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
//   return false
//   // const fileType = ['audio/mpeg'];
//   // if (!fileType.includes(rawFile.type)) {
//   //     ElMessage.error('上传格式不正确，只支持mp3');
//   //     return false;
//   // }
// }

function handleChange(file: UploadFile, fileList: UploadFile[]) {
  fileCount = fileList.length
}

function handleRemove(file: UploadFile, fileList: UploadFile[]) {
  fileCount = fileList.length
}

function handleError() {
  hud.hide()
  hud.error('上传失败')
}

function cancelUpload() {
  if (remark.value) {
    ElMessageBox.confirm('确定要放弃此次编辑？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(() => {
        remark.value = ''
        emits('update:modelValue', false)
      })
      .catch()
  } else {
    remark.value = ''
    emits('update:modelValue', false)
  }
}
</script>

<template>
  <div>
    <el-dialog
      v-model="show"
      :title="title"
      width="500"
      destroy-on-close
      :before-close="cancelUpload"
    >
      <el-upload
        ref="upload"
        class="upload"
        :action="action"
        :headers="{
          Authorization: `Bearer ${accessToken}`,
          'X-Tenant-Id': SYS_INFO.tenantId,
          ...headers,
        }"
        :data="{ remark, ...data }"
        :limit="1"
        :accept="accept"
        :http-request="httpRequest"
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :on-change="handleChange"
        :on-error="handleError"
        :on-remove="handleRemove"
        :auto-upload="false"
        :name="name"
      >
        <el-button
          v-if="downloadUrl"
          class="module-btn"
          type="primary"
          @click="downloadTemplate"
        >
          下载模板
        </el-button>
        <template #trigger>
          <div class="upload-box">
            <!-- <span><img :src="localUploadIMG" alt="" /></span> -->
            <span class="right">
              <div class="title">本地上传</div>
              <div class="tip">{{ placeholder }}</div>
            </span>
          </div>
        </template>
      </el-upload>
      <el-input
        v-if="showRemark"
        v-model="remark"
        type="textarea"
        placeholder="请输入需要备注的信息～"
      />
      <template #footer>
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" @click="submitUpload">立即上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dialog) {
  width: 524px;
  border-radius: 8px;

  .el-dialog__header {
    display: flex;
    padding: 14px 16px !important;
    margin-right: 0;
    border-bottom: 1px solid #e6e6e6;

    .el-dialog__title {
      font-size: 14px;
      font-weight: 600;
      color: $main-text-color !important;
    }

    .el-dialog__headerbtn {
      height: 48px;
    }
  }

  .el-dialog__footer {
    margin-top: 15px;

    .el-button {
      width: 88px;
      height: 32px;
    }
  }

  .module-btn {
    margin: 16px 0 6px;
  }

  .upload-box {
    display: flex;
    align-items: center;
    width: 492px;
    height: 88px;
    background: linear-gradient(272deg, #fbfcff 0%, #fafcff 100%);
    border: 1px solid #f4f8ff;
    border-radius: 8px;

    .right {
      margin-left: 8px;

      span {
        display: inline-block;
      }

      .title {
        font-size: 14px;
        font-weight: 700;
        color: $main-text-color;
      }

      .tip {
        font-size: 12px;
        color: $minor-text-color;
      }
    }
  }

  .el-upload-list {
    margin-bottom: 16px;
  }

  .el-textarea__inner {
    width: 492px;
    height: 72px;
    border: 1px solid #d7d7d7;
    box-shadow: none;

    &::placeholder {
      color: $minor-text-color;
    }
  }
}
</style>
