<template>
  <Dialog v-model="dialogVisible" title="生成工资条" style="width: 800px">
    <el-form :model="formData" ref="formRef" :rules="rules" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="年月" prop="period">
            <el-date-picker
              v-model="formData.period"
              type="month"
              placeholder="选择年月"
              format="YYYY-MM"
              value-format="YYYY-MM"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-form-item label="导入奖金">
            <div>
              <el-upload
                ref="rewardFile"
                action="#"
                :limit="1"
                accept=".xls,.xlsx"
                :before-upload="fileBeforeUpload"
                :http-request="rewardUpload"
              >
                <el-button type="primary">
                  <Icon icon="ep:upload" class="mr-5px" /> 点击上传
                </el-button>
              </el-upload>
              <el-link type="primary" :underline="false" @click="downloadTemplateFile(1)">
                点击下载模板文件
              </el-link>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="导入考勤" prop="attendanceFile">
            <div>
              <el-upload
                ref="attendanceFile"
                action="#"
                :limit="1"
                accept=".xls,.xlsx"
                :before-upload="fileBeforeUpload"
                :http-request="attendanceUpload"
              >
                <el-button type="primary">
                  <Icon icon="ep:upload" class="mr-5px" /> 点击上传
                </el-button>
              </el-upload>
              <el-link type="primary" :underline="false" @click="downloadTemplateFile(2)">
                点击下载模板文件
              </el-link>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="formLoading" @click="handleSave"> 确认生成 </el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogCreateSalary">
import * as SalaryApi from '@/api/home/salary.js'
import download from '@/utils/download'

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)

const formData = ref({})

const formLoading = ref(false)

const rules = {
  period: { required: true, message: '年月不可为空', trigger: 'blur,change' }
}

function open() {
  dialogVisible.value = true
  resetForm()
}

function resetForm() {
  const month = `${new Date().getMonth() + 1}`
  formData.value = {
    period: `${new Date().getFullYear()}-${month.padStart(2, '0')}`
  }
}

defineExpose({ open })

const emit = defineEmits(['success'])
const formRef = ref()
async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    fd.value.delete('period')
    fd.value.append('period', formData.value.period)
    await SalaryApi.createSalarySlip(fd.value)
    message.success('生成成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

async function downloadTemplateFile(type) {
  let data
  if (type == 1) {
    data = await SalaryApi.getLinkReward()
    console.log(data)
    download.excel(data, '奖金模板.xls')
  } else if (type == 2) {
    data = await SalaryApi.getLinkAttendance()
    download.excel(data, '考勤模板.xls')
  }
}

const fileBeforeUpload = (file) => {
  let format = '.' + file.name.split('.')[1]
  if (!['.xls', '.xlsx'].includes(format)) {
    message.error(`请上传指定格式".xls,.xlsx"文件`)
    return false
  }
  let isRightSize = file.size / 1024 / 1024 < 20
  if (!isRightSize) {
    message.error('文件大小超过 20MB')
  }
  return isRightSize
}

const fd = ref(new FormData())

function rewardUpload(data) {
  fd.value.append('rewardSalaryFile', data.file)
}

function attendanceUpload(data) {
  fd.value.append('attendanceFile', data.file)
}
</script>

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