<template>
  <el-dialog v-model="visible" title="薪资导入" width="600px" :close-on-click-modal="false" destroy-on-close>
    <el-form label-width="100px">
      <el-form-item label="日期">
        <el-date-picker
          v-model="chooseDate"
          type="month"
          format="YYYY-M"
          value-format="YYYY-M"
          placeholder="请选择日期"
          @change="handleChange"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item>
        <el-upload
          v-if="showUpload"
          :headers="headers"
          class="upload-demo"
          :action="url"
          :limit="1"
          :with-credentials="true"
          :before-upload="beforeUpload"
        >
          <template #tip>
            <div class="el-upload-list__item-name">{{ fileName }}</div>
          </template>
          <el-button
            size="small"
            v-auth="'professional_salary_import'"
            type="primary">选择文件
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">关 闭</el-button>
        <el-button type="primary" @click="submitUpload" :loading="btnLoading">导入</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMessage } from '/@/hooks/message'
import { Session } from '/@/utils/storage'
import request from '/@/utils/request'

// Emits
const emit = defineEmits<{
  (e: 'refreshData'): void
}>()

// 消息提示
const message = useMessage()

// 对话框显示状态
const visible = ref(false)

// 表单数据
const chooseDate = ref('')
const url = ref('')
const showUpload = ref(false)
const fileList = ref<any[]>([])
const btnLoading = ref(false)
const fileName = ref('')
const files = ref<File | null>(null)

// 请求头
const headers = computed(() => {
  return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})

// 日期改变
const handleChange = () => {
  if (chooseDate.value) {
    showUpload.value = true
    url.value = `/professional/file/importSalary?chooseDate=${chooseDate.value}`
  } else {
    showUpload.value = false
  }
}

// 初始化
const init = () => {
  fileList.value = []
  files.value = null
  fileName.value = ''
  chooseDate.value = ''
  showUpload.value = false
  visible.value = true
}

// 上传前验证
const beforeUpload = (file: File) => {
  files.value = file
  const fileLast = file.name.split('.')
  const extension = fileLast[fileLast.length - 1] === 'xls'
  const extension2 = fileLast[fileLast.length - 1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 20
  
  if (!extension && !extension2) {
    message.warning('上传模板只能是 xls、xlsx格式!')
    return false
  }
  if (!isLt2M) {
    message.warning('上传模板大小不能超过 20MB!')
    return false
  }
  fileName.value = file.name
  return false // 返回false不会自动上传
}

// 导入提交
const submitUpload = async () => {
  btnLoading.value = true
  if (fileName.value === "") {
    message.warning('请选择要上传的文件！')
    btnLoading.value = false
    return
  }
  
  if (!files.value) {
    message.warning('请选择要上传的文件！')
    btnLoading.value = false
    return
  }
  
  const fileFormData = new FormData()
  fileFormData.append('file', files.value, fileName.value)
  
  try {
    const res = await request({
      url: url.value,
      method: 'post',
      data: fileFormData,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res.data.data && res.data.data.code == 1) {
      message.error(`导入失败,${res.data.data.title}: ${res.data.data.msg}`)
    } else {
      message.success("导入成功")
      visible.value = false
      emit('refreshData')
    }
  } catch (error: any) {
    message.error(error?.msg || '导入失败')
  } finally {
    btnLoading.value = false
  }
}

// 暴露方法
defineExpose({
  init
})
</script>

<style scoped>
</style>
