<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="18"><span>数据期初信息列表</span> </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Top" @click="handleAdd">导入商品</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Top" @click="handleAdd">导入商品图片</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="primary" icon="Top" @click="handleAdd">导入供应商</el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="primary" icon="Top" @click="handleAdd">导入客户</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button type="primary" icon="Top">
                导入供应商
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="importSupplierTemplate">下载模板</el-dropdown-item>
                  <el-dropdown-item icon="Top" @click="handleSupplierImport">导入数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>

          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button type="primary" icon="Top">
                导入客户
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="importCustomerTemplate">下载模板</el-dropdown-item>
                  <el-dropdown-item icon="Top" @click="handleCustomerImport">导入数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Top" :loading="buttonLoading" @click="handleCustomerExport">
              导出客户
              <el-icon class="el-icon--right"> </el-icon>
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="Top" :loading="buttonLoading" @click="handleSupplierExport">
              导出供应商
              <el-icon class="el-icon--right"> </el-icon>
            </el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="uploadList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="上传类型" align="center" prop="" />
        <el-table-column label="上传名称" align="center" prop="" />
        <el-table-column label="上传时间" align="center" prop="" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <!-- <template #default="scope"> </template> -->
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileUploadError"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的{{ upload.name }}数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleDownloadTemplate">
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button :disabled="upload.isUploading" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LogisticsCompany" lang="ts">
import { globalHeaders } from '@/utils/request';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no } = toRefs<any>(proxy?.useDict('sys_platform_yes_no'));

const uploadList = ref<[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const uploadRef = ref<ElUploadInstance>();
/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  name: '',
  method: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的客户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: ''
});
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: any = {
  id: undefined
};
const data = reactive<PageData<any, any>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,

    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

const getList = async () => {
  loading.value = true;
  //   uploadList.value = res.rows;
  //   total.value = res.total;
  loading.value = false;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 客户导入按钮操作 */
const handleCustomerImport = () => {
  upload.name = '客户';
  upload.title = '客户导入';
  upload.method = 'importCustomerTemplate';
  upload.open = true;
  upload.url = import.meta.env.VITE_APP_BASE_API + '/customer/customerInfo/importData';
};

/** 客户导入按钮操作 */
const handleSupplierImport = () => {
  upload.name = '供应商';
  upload.title = '供应商导入';
  upload.method = 'importSupplierTemplate';
  upload.open = true;
  upload.url = import.meta.env.VITE_APP_BASE_API + '/customer/info/importData';
};

/** 客户导出按钮操作 */
const handleCustomerExport = async () => {
  buttonLoading.value = true;
  try {
    await proxy?.download('customer/customerInfo/exportTemplateData', {}, `客户导出_${new Date().getTime()}.xlsx`);
  } finally {
    buttonLoading.value = false;
  }
};
/** 供应商导出按钮操作 */
const handleSupplierExport = async () => {
  buttonLoading.value = true;
  try {
    await proxy?.download('customer/info/exportTemplateData', {}, `供应商导出_${new Date().getTime()}.xlsx`);
  } finally {
    buttonLoading.value = false;
  }
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传失败处理 */
const handleFileUploadError = () => {
  upload.isUploading = false;
  ElMessage.error('文件上传失败，请联系管理员！');
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

/** 通用下载模板处理函数 */
const handleDownloadTemplate = () => {
  // 根据 upload.method 存储的函数名字符串来动态执行
  // 或者根据 upload.name 判断
  if (upload.method === 'importCustomerTemplate') {
    importCustomerTemplate();
  } else if (upload.method === 'importSupplierTemplate') {
    importSupplierTemplate();
  }
};

/** 下载客户模板操作 */
const importCustomerTemplate = () => {
  proxy?.download('customer/customerInfo/importTemplate', {}, `客户导入模板_${new Date().getTime()}.xlsx`);
};

/** 下载供应商模板操作 */
const importSupplierTemplate = () => {
  proxy?.download('customer/info/importTemplate', {}, `供应商导入模板_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getList();
});
</script>
