<template>
  <!-- 批量导入设备 -->
  <el-dialog v-model="upload.importDeviceDialog" :title="upload.title" width="550px" append-to-body>
    <div style="margin-top: -55px">
      <el-divider style="margin-top: 50px;width: 106%;margin-left: -2.9%;" />
      <el-form label-position="top" :model="importForm" ref="importFormRef" :rules="importRules">
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="importForm.productId"
            placeholder="请选择产品"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="item in productList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上传文件" prop="fileList">
          <el-upload
            style="width: 100%;"
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            v-model:file-list="importForm.fileList"
            :action="upload.url + '?productId=' + importForm.productId"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            :on-change="handleChange"
            :on-remove="handleRemove"
            drag
          >
            <el-icon class="el-upload__icon"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                <div style="margin-top: 10px">
                  <span>提示:仅允许导入xls、xlsx格式文件。</span>
                </div>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-link
          type="primary"
          :underline="false"
          style="font-size: 14px; vertical-align: baseline"
          @click="importTemplate"
        >
          <el-icon><Download /></el-icon>
          下载设备导入模板
        </el-link>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确定</el-button>
        <el-button @click="upload.importDeviceDialog = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { UploadFilled, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listProduct } from '@/api/pms/video/product'
import { getAccessToken } from '@/utils/auth'
import { download } from '@/config/axios/service'

// 国际化
const { t } = useI18n()

// 定义 emit
const emit = defineEmits(['save'])

// Refs
const importFormRef = ref()
const uploadRef = ref()

// 数据响应式变量
const type = ref(1)

// 导入表单
const importForm = reactive({
  productId: null,
  fileList: []
})

const productList = ref([])
const file = ref(null)

// 批量导入参数
const upload = reactive({
  // 是否显示弹出层
  importDeviceDialog: false,
  // 弹出层标题
  title: '批量导入',
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getAccessToken() },
  // 上传的地址
  url: import.meta.env.VITE_BASE_URL + '/iot/device/importData'
})

// 批量导入表单校验
const importRules = {
  productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }]
}

// 生命周期钩子
onMounted(() => {
  getProductList()
})

// 方法定义
/** 下载模板操作 */
function importTemplate() {
  download(
    '/iot/device/uploadTemplate?type=' + type.value,
    {},
    `device_template_${new Date().getTime()}.xlsx`
  )
}

// 选择文件后给表单验证的prop字段赋值， 并且清除该字段的校验
function handleChange(file, fileList) {
  importForm.fileList = fileList
  // 防止用户打开了文件选择框之后不选择文件而出现效验失败
  if (importForm.fileList) {
    importFormRef.value?.clearValidate('fileList')
  }
}

// 删除文件后重新校验该字段
function handleRemove(file, fileList) {
  importForm.fileList = fileList
  importFormRef.value?.validateField('fileList')
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
}

// 文件上传成功处理
function handleFileSuccess(response, file, fileList) {
  upload.importDeviceDialog = false
  upload.isUploading = false
  uploadRef.value?.clearFiles()
  ElMessageBox.alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      '</div>',
    '导入结果',
    { dangerouslyUseHTMLString: true }
  )
  emit('save')
}

/** 查询产品列表 */
function getProductList() {
  const params = {
    pageSize: 20
  }
  listProduct(params).then((response) => {
    productList.value = response.list.map((item) => {
      return { value: item.productId, label: item.productName }
    })
  })
}

// 提交上传文件
function submitFileForm() {
  importFormRef.value?.validate((valid) => {
    if (valid) {
      uploadRef.value?.submit()
      upload.importDeviceDialog = false
    }
  })
}

defineExpose({
  showDialog: () => {
    upload.importDeviceDialog = true
  },
  importForm
})
</script>

<style scoped>
.el-upload__icon {
  font-size: 67px;
  color: #c0c4cc;
  margin: 40px 0 16px;
  line-height: 50px;
}
</style>
