<template>
  <div v-if="props.modelValue">
    <el-card v-if="cardVisible" class="pop-card">
      <template #header>
        <div class="flex justify-between items-center pop-head">
          <div style="font-size: 16px">批量导入</div>
          <el-icon :size="16" class="mr-3" @click="updateValue(false)"><Close /></el-icon
        ></div>
      </template>
      <div class="upload-content">
        <el-upload
          ref="upload"
          class="upload-demo"
          :multiple="false"
          :limit="1"
          drag
          action="/skyeye-admin-api/user/import"
          :headers="headers"
          :with-credentials="true"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          style="width: 384px; height: 192px; border-radius: 8px"
        >
          <el-icon class="el-icon--upload" style="width: 33px; height: 42px"><Document /></el-icon>
          <div class="el-upload__text">
            <div style="font-size: 16px">点击或将文件拖拽到这里上传</div>
            <div style="font-size: 14px; color: rgba(0, 0, 0, 0.45)"
              >文件只支持：.xlsx .xls .仅支持上传一个文件</div
            ></div
          >
        </el-upload>
        <div style="margin-top: 52px; margin-left: 288px; display: flex">
          <el-button @click="handleDownload" style="margin-right: 10px">下载模板</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button></div
        ></div
      >
    </el-card>
    <!-- //上传成功 -->
    <el-dialog
      v-model="DialogVisibleSuc"
      title="Warning"
      width="30%"
      @close="
        () => {
          emits('update:modelValue', false);
        }
      "
      align-center
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass" style="display: flex">
            <el-icon style="margin-top: 2px" color="#52C41A"><CircleCheck /></el-icon
            ><div style="margin-left: 14px">导入成功</div></h4
          >
        </div>
      </template>
      <span style="margin-left: 30px"> 已成功添加{{ sucCount }}条用户信息</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleRightComfirm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传失败 -->
    <el-dialog
      v-model="DialogVisibleErr"
      title="Warning"
      width="30%"
      @close="
        () => {
          emits('update:modelValue', false);
        }
      "
      align-center
    >
      <template #header="{ titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass" style="display: flex">
            <el-icon style="margin-top: 2px" color="#FF4D4F "><Warning /></el-icon>
            <div style="margin-left: 14px">导入失败</div></h4
          >
        </div>
      </template>
      <ul v-for="(item, index) in errDetail" :key="index">
        <li v-if="index < 3">{{ item }} </li>
        <li v-else v-show="showMore">{{ item }}</li>
      </ul>
      <div v-if="errDetail.length > 3 && !showMore" @click="showMore = true" class="more-link"
        >更多</div
      >
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleErrComfirm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog></div
  >
</template>

<script setup lang="ts">
  import { Close, Document, CircleCheck, Warning } from '@element-plus/icons-vue';
  import { ref } from 'vue';
  import { genFileId, ElMessage } from 'element-plus';
  import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
  import { useUserStore } from '@/store/modules/user';
  import { onMounted } from 'vue';
  import axios, { AxiosRequestConfig } from 'axios';

  const userStore = useUserStore();

  onMounted(() => {
    console.log('111');

    console.log('props.modelValue', props.modelValue);

    cardVisible.value = props.modelValue;
  });

  const headers = {
    Satoken: userStore.getToken,
    Tenantid: userStore.getTenantId,
  };

  const cardVisible = ref<boolean>(true);

  //对话框
  const DialogVisibleSuc = ref<boolean>(false);
  const DialogVisibleErr = ref<boolean>(false);

  //更多
  const showMore = ref(false);

  const isSuc = ref<boolean>(true);
  const errDetail = ref<string[]>([]);
  const sucCount = ref<number>(0);

  const props = defineProps<{ modelValue: boolean }>();
  const emits = defineEmits(['update:modelValue', 'change']);

  const updateValue = (value) => {
    emits('update:modelValue', value);
  };
  const upload = ref<UploadInstance>();

  const handleDownload = async () => {
    //调用后端接口
    try {
      const config: AxiosRequestConfig = {
        headers,
        responseType: 'blob',
      };
      const response = await axios.get('/skyeye-admin-api/user/downloadExcel', config);
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      // 创建下载链接
      let downloadLink: HTMLAnchorElement | null = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      downloadLink.href = url;
      downloadLink.download = '批量导入模板（重命名请加后缀.xlsm）.xlsm';
      downloadLink.click();
      // 移除下载链接
      window.URL.revokeObjectURL(url);
      downloadLink = null;
    } catch (error) {
      console.error('Error downloading file:', error);
    }
  };

  const handleImport = async () => {
    upload.value!.submit();
  };

  const beforeUpload = (file) => {
    const isExcel = /\.(xlsx|xls|xlsm)$/.test(file.name.toLowerCase());
    if (!isExcel) {
      // 提示用户选择正确的文件类型
      ElMessage({
        message: '仅支持上传.xlsx .xls格式文件',
        type: 'error',
      });
      return false; // 阻止上传
    }
    return true; // 允许上传
  };

  const handleUploadSuccess = (response, _file, _fileList) => {
    isSuc.value = response.data.isSuc;
    errDetail.value = response.data.failedInfo;
    sucCount.value = response.data.sucCount || 0;

    if (isSuc.value) {
      DialogVisibleSuc.value = true;
      DialogVisibleErr.value = false;
    } else {
      DialogVisibleSuc.value = false;
      DialogVisibleErr.value = true;
    }
    cardVisible.value = false;
  };

  const handleRightComfirm = () => {
    DialogVisibleSuc.value = false;
    emits('update:modelValue', false);
    emits('change');
  };
  const handleErrComfirm = () => {
    DialogVisibleErr.value = false;
    emits('update:modelValue', false);
    emits('change');
  };

  const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value!.handleStart(file);
  };

  //对话框
</script>

<style scoped>
  .upload-content {
    margin-left: 96px;
    margin-top: 36px;
  }

  .more-link {
    color: #1890ff;
    margin-left: 30px;
  }

  li:before {
    content: '';
    width: 6px;
    height: 6px;
    display: inline-block;
    border-radius: 50%;
    background: #ff4d4f;
    vertical-align: middle;
    margin-left: 30px;
    margin-right: 8px;
  }

  li {
    font-size: 14px;
    margin-bottom: 2px;
  }
</style>
