<template>
  <el-container>
    <el-main>
      <div class="batch-dispatch sa-m-b-20">
        <div class="title">{{ t('modules.order.systemAutoProcess') }}</div>
        <div class="order-content sa-flex sa-flex-col">
          <div class="sa-flex sa-flex-col">
            <div class="order-file sa-table-line-1 sa-m-b-8">
              <span v-if="state.file">{{ state.file.name }}</span>
            </div>
            <el-upload action :http-request="onImportFile" :show-file-list="false" accept=".xlsx,.xls">
              <el-button v-if="!state.file">{{ t('modules.order.importDeliveryList') }}</el-button>
              <el-button class="is-link" type="primary" v-if="state.file">{{ t('modules.order.reSelectFile')
              }}</el-button>
            </el-upload>
          </div>
          <div class="sa-m-t-22" v-if="state.file">
            <el-button type="primary" @click="onDispatch" :loading="state.loading" :disabled="!state.file">
              {{ t('modules.order.batchShip') }}
            </el-button>
          </div>
        </div>
      </div>
      <!-- <div class="batch-dispatch">
        <div class="title">
          方法二：如使用批量发货，需确认
          <el-button class="is-link" type="primary"> &nbsp;商城配置-第三方服务&nbsp; </el-button>
          中快递鸟配置完成
        </div>
        <div class="sa-flex sa-row-center">
          <el-button
            type="primary"
            :disabled="modal.params.order_ids.length == 0"
            @click="onBatchDispatch"
            >批量发货</el-button
          >
        </div>
      </div> -->
    </el-main>
  </el-container>
</template>
<script setup>
import { getCurrentInstance, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { api } from '../order.service';

const { t } = useI18n();
const props = defineProps(['modal']);
const { proxy } = getCurrentInstance();

const state = reactive({
  file: '',
  loading: false,
});

// 导入发货单
function onImportFile(file) {
  state.file = file.file;
}

// 批量发货
async function onDispatch() {
  if (!state.file) {
    ElMessage.warning(t('modules.order.pleaseSelectDeliveryFile'));
    return;
  }

  state.loading = true;

  try {
    const formData = new FormData();
    formData.append('file', state.file);

    const response = await api.order.importDelivery(formData);

    // 检查响应类型
    const contentType = response.headers['content-type'];

    if (contentType && contentType.includes('application/json')) {
      // JSON响应，表示成功 - 需要将blob转换为文本再解析
      const text = await response.data.text();
      const result = JSON.parse(text);
      if (result.code == 200) {
        ElMessage.success(t('modules.order.batchShipSuccess'));
        // 关闭弹窗并触发刷新
        proxy.$emit('modalCallBack', { action: 'confirm', refresh: true });
      } else {
        ElMessage.error(t('modules.order.batchShipFailed'));
      }
    } else {
      // 文件流响应，表示有失败的记录，需要下载错误文件
      const blob = response.data;

      // 从响应头获取文件名
      const now = new Date();
      const dateTimeStr = now.getFullYear() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0') + '_' +
        String(now.getHours()).padStart(2, '0') +
        String(now.getMinutes()).padStart(2, '0') +
        String(now.getSeconds()).padStart(2, '0');
      let filename = `批量发货失败记录_${dateTimeStr}.xlsx`; // 默认文件名
      const contentDisposition = response.headers['content-disposition'];

      if (contentDisposition) {
        // 尝试从 content-disposition 中提取文件名
        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (filenameMatch && filenameMatch[1]) {
          filename = filenameMatch[1].replace(/['"]/g, ''); // 移除引号
          // 如果文件名是 URL 编码的，进行解码
          try {
            filename = decodeURIComponent(filename);
          } catch (e) {
            // 解码失败，使用原文件名
            console.warn('文件名解码失败，使用原文件名:', filename);
          }
        }
      }

      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      ElMessage.warning(t('modules.order.partialShipFailed'));
    }
  } catch (error) {
    console.error('批量发货失败:', error);
    ElMessage.error(t('modules.order.batchShipFailed'));
  } finally {
    state.loading = false;
  }
}


</script>
<style lang="scss" scoped>
.batch-dispatch {
  background: var(--sa-table-header-bg);
  border-radius: 4px;
  padding: 0 16px 24px;

  .title {
    line-height: 18px;
    margin-bottom: 20px;
    padding: 15px 0;
    display: flex;
    align-items: center;

    .el-button {
      height: 18px;
    }
  }

  .order-content {
    .order-file {
      height: 16px;
      line-height: 16px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-font);
    }

    .el-form--inline .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
    }

    :deep() {
      .el-select {
        flex: 1;
      }

      .el-input__inner {
        border-radius: 4px 0 0 4px;
      }
    }

    .select-append {
      padding: 0 16px;
      line-height: 30px;
      background: var(--sa-table-header-bg);
      border: 1px solid var(--sa-border);
      box-sizing: border-box;
      border-left: none;
      border-radius: 0 4px 4px 0;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-font);
      cursor: pointer;
    }
  }
}
</style>
