<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <!-- 发货信息，用于导出代发货订单的excel交给快递公司 -->
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('product.spu.uploadTips')"
    :close-on-click-modal="false"
    width="38%"
    class="components-purchase-order-upload"
  >
    <div class="tips">
      <p>{{ $t('order.order.batchShipmentProcess') }}</p>
      <p>
        {{ $t('order.order.beCareful') }}
      </p>
      <p>{{ $t('order.order.tips1') }}</p>
      <p>{{ $t('order.order.tips2') }}</p>
    </div>
    <el-upload
      ref="uploadRef"
      v-loading="loading"
      :auto-upload="false"
      :v-loading="loading"
      :before-upload="beforeAvatarUpload"
      :file-list="files"
      :limit="1"
      :on-error="uploadFalse"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-success="uploadSuccess"
      :action="baseURL + '/mall4cloud_order/s/purchase/order/export_order_excel'"
      :headers="{Authorization: getTokenVal}"
      class="upload-demo"
      name="excelFile"
    >
      <template #tip>
        <div class="el-upload__tip" />
      </template>
      <el-button
        style="margin-left: 10px"
        type="success"
        @click="submitUpload"
      >
        {{ $t("product.spu.import") }}
      </el-button>
      <template #trigger>
        <el-button
          type="primary"
        >
          {{
            $t("product.spu.selectFile")
          }}
        </el-button>
      </template>
      <!-- 导出待发货单 -->
      <el-button
        style="margin-left: 10px"
        type="success"
        @click="exportOrder"
      >
        {{ $t("order.order.exportOrder") }}
      </el-button>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import * as orderApi from '@/api/order/purchase-order'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  param: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const emit = defineEmits([
  'refreshDataList1'
])

const baseURL = ref(import.meta.env.VITE_APP_BASE_API)

const exportOrder = () => {
  const timeParam = props.param
  if (!timeParam.startTime || !timeParam.endTime) {
    ElMessage.error($t('order.order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm($t('table.sureToExport'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    orderApi.deliverySoldExcel({
      startTime: timeParam.startTime, // 开始时间
      endTime: timeParam.endTime // 结束时间
    }).then((data) => {
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = `${$t('order.order.purchaseOrderUndelivery')}.xlsx`
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch((e) => {
      ElMessage.error(e)
    })
  })
}

const files = reactive([])
const loading = ref(false)
const visible = ref(false)
const uploadSuccess = (response) => {
  loading.value = false
  const data = response.data
  if (!data) {
    alert($t('product.spu.fileSuccess'))
  } else {
    alert(data)
  }
  files.length = 0
  visible.value = false
  emit('refreshDataList1')
}

const uploadFalse = () => {
  loading.value = false
  ElMessageBox.confirm($t('product.spu.fileUploadFail'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    showCancelButton: false,
    type: 'error'
  })
}

let getTokenVal = null
const couponId = ref(3)
const init = (id) => {
  visible.value = true
  loading.value = false
  files.length = 0
  getTokenVal = getToken()
  nextTick(() => {})
  couponId.value = id
}

// 上传前对文件的大小的判断
const upload = ref(false)
const beforeAvatarUpload = (file) => {
  upload.value = true
  const extension = checkFile(file, ['xls', 'xlsx'], 10)
  loading.value = extension
  return extension
}

const uploadRef = ref()
const submitUpload = () => {
  upload.value = false
  uploadRef.value?.submit()
  if (!upload.value) {
    ElMessage.error($t('order.order.uploadFileTips'))
  }
}

const handleRemove = () => {
}

const handlePreview = (file) => {
  ElMessageBox.confirm($t(file.response.status ? 'product.spu.fileSuccess' : 'product.spu.fileFail'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    showCancelButton: false,
    type: file.response.status ? 'success' : 'error'
  })
  visible.value = false
  emit('refreshDataList1')
}

defineExpose({
  init
})
</script>

<style scoped>
.components-purchase-order-upload {
  :deep(.el-dialog__body) {
    padding: 10px 20px 30px 20px;
  }
  .tips {
    margin-bottom: 30px;
  }
}
</style>
