<template>
  <div style="margin-top: 10px; height: 400px">
    <el-date-picker v-model="nf" type="year" placeholder="请选择年份" />
    <el-select v-model="insurId" style="width: 200px; padding-left: 5px">
      <el-option label="长沙市城职普通住院" value="1"></el-option>
      <el-option label="长沙市城居普通住院" value="2"></el-option>
    </el-select>
    <div style="margin-top: 10px">
      <el-upload
        class="upload-demo"
        ref="upload"
        accept=".xlsx,.xls"
        :action="apiUrl + '/cssYbTj/ybCssImp'"
        :headers="header"
        :file-list="fileList"
        :limit="1"
        :data="queryData"
        :on-exceed="fileSizeOutLimit"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary" icon="Picture">选取文件</el-button>
        </template>
        <el-button style="margin-left: 10px" type="success" icon="Upload" @click="submitUpload">上传</el-button>
        <template #tip>
          <div class="el-upload__tip">只能上传 xls/xlsx 文件，建议上传一个月数据</div>
        </template>
      </el-upload>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from '@vue/reactivity'
import { onMounted } from 'vue'
import store from '@/store'
import { ElMessage } from 'element-plus'
import { formatYear } from '@/utils/date'

export default {
  setup() {
    const nf = ref(null)
    const insurId = ref('1')

    const queryData = reactive({
      nf: '',
      insurName: '',
    })

    // 初始化数据
    onMounted(() => {
      nf.value = new Date()
      queryData.nf = formatYear(nf.value)
      queryData.insurName = insurId.value === '1' ? '长沙市城职普通住院' : '长沙市城居普通住院'
    })

    // ------------------ 上传 ---------------------
    const fileList = ref([])
    const apiUrl = import.meta.env.VITE_BASE_URL

    const upload = ref(null)
    const header = {
      token: store.state.user.token,
    }
    const submitUpload = () => {
      queryData.insurName = insurId.value === '1' ? '长沙市城职普通住院' : '长沙市城居普通住院'
      queryData.nf = formatYear(nf.value)
      nextTick(() => {
        upload.value.submit()
      })
    }
    const fileSizeOutLimit = () => {
      ElMessage.error('已经选取excel，如须更换请先移除已选取的excel!')
    }
    const uploadSuccess = () => {
      ElMessage.success('上传成功!')
    }
    const uploadError = () => {
      ElMessage.error('上传失败!')
    }

    return {
      queryData,
      nf,
      insurId,
      header,
      fileList,
      apiUrl,
      submitUpload,
      fileSizeOutLimit,
      uploadSuccess,
      uploadError,
      upload,
    }
  },
}
</script>

<style scoped>
.inline {
  display: inline-block;
  vertical-align: top;
}
</style>