<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="importUrl"
          :headers="getHeaders()"
          :with-credentials="true"
          :auto-upload="false"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :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; display: flex">
          <!-- <el-button @click="handleDownloadInfoForm" style="margin-right: 10px; margin-left: auto"
            >组织/用户id信息</el-button
          > -->
          <el-icon :size="18" style="margin-top: 7px; margin-left: auto">
            <Download />
          </el-icon>
          <el-tooltip content="点击下载组织/角色id信息" placement="top" effect="light">
            <span
              style="color: #409efc; margin-top: 6px; margin-right: 12px; cursor: pointer"
              @click="handleDownloadInfoForm"
              >组织/角色id信息查询</span
            >
          </el-tooltip>

          <el-button @click="handleDownload" style="margin-right: 10px">下载模板</el-button>
          <el-button type="primary" @click="handleImport" :disabled="isImportEnable"
            >导入</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> -->

    <el-dialog
      v-model="DialogVisible"
      title="Warning"
      width="50%"
      align-center
      @close="
        () => {
          emits('update:modelValue', false);
        }
      "
    >
      <template #header>
        <el-icon :size="24" color="#f2b20a" style="margin: 0 5px 2px">
          <WarnTriangleFilled />
        </el-icon>
        <div class="header-text">添加提示</div>
      </template>
      <!-- <div class="sum-count">
        成功上传 <span class="succ-sum">{{ sucCount }}</span> 条，
        失败 <span class="err-sum">{{ errCount }}</span> 条
      </div> -->
      <div class="sum-count">
        成功上传 <span class="succ-sum">{{ successCount }}</span> 条， 失败
        <span class="err-sum">{{ errorCount }}</span> 条
      </div>
      <div class="err-info">
        <!-- <div v-if="errCount === 0">未检测到相机数据</div> -->
        <div>
          <ul v-for="(item, index) in errDetail" :key="index">
            <li v-html="item"></li>
          </ul>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleErrComfirm"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  // import { Close, Document, CircleCheck, Warning } from '@element-plus/icons-vue';
  import { Close, Document, WarnTriangleFilled, Download } from '@element-plus/icons-vue';
  import { computed, 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';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { getHeaders } from '@/utils/http/axios';

  const userStore = useUserStore();

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

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

    cardVisible.value = props.modelValue;
  });

  const cardVisible = ref<boolean>(true);

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

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

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

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

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

  const { urlPrefix } = useGlobSetting();

  const importUrl = computed(() => {
    return urlJoin(urlPrefix, `/admin/user/importUser`);
  });

  const handleDownload = async () => {
    //调用后端接口
    try {
      const config: AxiosRequestConfig = {
        headers: getHeaders(),
        responseType: 'blob',
      };
      const response = await axios.get(
        './skyeye-file-upload/skyeye/CAMERALIST_TEMPLATE/importTemplate.xlsx',
        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 = '批量导入模板.xlsx';
      downloadLink.click();
      // 移除下载链接
      window.URL.revokeObjectURL(url);
      downloadLink = null;
    } catch (error) {
      console.error('Error downloading file:', error);
    }
  };

  const handleDownloadInfoForm = async () => {
    //调用后端接口
    try {
      const config: AxiosRequestConfig = {
        headers: getHeaders(),
        responseType: 'blob',
      };
      const response = await axios.get(urlPrefix + '/admin/user/exportDeptRoleInfo', 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 = '组织/角色id信息模板.xlsx';
      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) => {
    // console.log(response);
    if (response.code == 400) {
      ElMessage({
        message: response.message,
        type: 'error',
      });
      emits('update:modelValue', false);
    } else {
      // isSuc.value = response.data.isSuc;
      errDetail.value = response.data.errorList;
      successCount.value = response.data.successCount || 0;
      errorCount.value = response.data.errorCount || 0;

      try {
        if (errDetail.value.length > 0) {
          errDetail.value.forEach((item, index) => {
            if (item.indexOf('【添加失败】') >= 0) {
              errDetail.value[index] = item.replace(
                '【添加失败】',
                '<span style="color: #ff4d4f">【添加失败】</span>',
              );
            } else if (item.indexOf('【添加成功】') >= 0) {
              errDetail.value[index] = item.replace(
                '【添加成功】',
                '<span style="color: #52c41a">【添加成功】</span>',
              );
            }
          });
        }

        if (successCount.value != 0 && errorCount.value === 0 && errDetail.value.length === 0) {
          ElMessage({
            message: '添加成功', // 1.全部添加成功 —— failCount === 0
            type: 'success',
          });
          emits('update:modelValue', true);
          emits('change');
          //把上一级的AddUser窗口关掉
          props.colseAddUser();
          // window.location.reload();
        } else {
          // console.log('code500');
          DialogVisible.value = true;
        }
        cardVisible.value = false;
      } catch (error) {
        // console.log('code200'),
        ElMessage({
          message: response.message,
          type: 'error',
        });
        emits('update:modelValue', false);
      }
    }

    // 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;
    DialogVisible.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);
  };

  //用于没有上传文件时导入按钮置灰
  const isImportEnable = ref<boolean>(true);

  const handleChange = () => {
    isImportEnable.value = false;
  };

  const handleRemove = () => {
    isImportEnable.value = true;
  };

  //对话框
</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;
  }

  :deep(.el-dialog) {
    padding: 0px;
    border-radius: 5px;

    .el-dialog__header {
      display: flex;
      align-items: flex-end;
      height: 70px;
      padding: 0px 0px 10px 10px;
      border-bottom: 1px solid #e7e7e7;

      .header-text {
        font-size: 20px;
      }
    }

    .el-dialog__headerbtn {
      top: 22px;

      .el-dialog__close {
        color: black;
      }
    }

    .el-dialog__body {
      padding: 20px;

      .sum-count {
        margin: 10px 0 20px 20px;
        font-size: 20px;

        .succ-sum {
          color: #52c41a;
        }

        .err-sum {
          color: #ff4d4f;
        }
      }

      .err-info {
        height: 200px;
        margin-left: 20px;
        overflow: auto;
      }
    }

    .el-dialog__footer {
      margin: 0 20px 20px 0;
    }
  }
</style>
