<template>
  <el-dialog v-model="visible" title="薪资导出" width="500px" :close-on-click-modal="false" destroy-on-close>
    <el-form label-width="120px">
      <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 label="劳务日期锁定">
        <el-radio-group v-model="lockedLw">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-tag type="warning">选择是，则本月其他造单批次无法指定到当前月份。如需解锁，请前往「薪资导出记录」删除记录即可。</el-tag>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span v-if="showBtn" class="dialog-footer">
        <el-button @click="visible = false">关 闭</el-button>
        <el-button type="primary" @click="exportSalaryData" :loading="btnLoading">导 出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

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

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

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

// 表单数据
const chooseDate = ref('')
const showBtn = ref(false)
const btnLoading = ref(false)
const lockedLw = ref(1)

// 初始化
const init = () => {
  chooseDate.value = ''
  showBtn.value = false
  btnLoading.value = false
  lockedLw.value = 1
  visible.value = true
}

// 日期改变
const handleChange = () => {
  if (chooseDate.value) {
    showBtn.value = true
  } else {
    showBtn.value = false
  }
}

// 下载文件
const downLoadFile = async (url: string) => {
  return request({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json',
      "Authorization": 'Bearer ' + Session.getToken()
    }
  })
}

// 导出薪资数据
const exportSalaryData = async () => {
  if (!chooseDate.value) {
    message.warning('请选择日期')
    return
  }
  
  btnLoading.value = true
  try {
    const res = await downLoadFile(`/professional/file/exportSalary?chooseDate=${chooseDate.value}&state=${lockedLw.value}`)
    
    // 处理返回的文件流
    const blob = new Blob([res.data])
    const elink = document.createElement('a')
    elink.download = "薪资表.xls"
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
    
    message.success('导出成功')
    visible.value = false
  } catch (error: any) {
    message.error(error?.msg || '导出失败')
  } finally {
    btnLoading.value = false
  }
}

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

<style scoped>
</style>
