<template>
  <div>
    <el-card v-if="cardVisible">
      <template #header>
        <div class="flex justify-between items-center pop-head">
          <div style="font-size: 16px; font-weight: 600">批量修改</div>
          <el-icon
            :size="18"
            class="mr-3"
            @click="
              () => {
                emits('close');
              }
            "
            style="cursor: pointer"
          >
            <Close />
          </el-icon>
        </div>
      </template>
      <div class="upload-content">
        <el-upload
          ref="upload"
          style="width: 384px; height: 192px; border-radius: 8px"
          :headers="getHeaders()"
          :multiple="false"
          :limit="1"
          drag
          :action="actionUrl"
          :with-credentials="true"
          :auto-upload="false"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-exceed="handleExceed"
          :on-change="handleChange"
          :on-remove="handleRemove"
        >
          <el-icon class="el-icon--upload" style="width: 33px; height: 42px; color: #409efc">
            <Document />
          </el-icon>
          <div class="el-upload__text">
            <div style="font-size: 12px; color: red; margin-bottom: 5px"
              >请先导出需要修改的相机信息，并在原模版上修改后在此导入文件</div
            >
            <div style="font-size: 16px">点击或将文件拖拽到这里上传</div>
            <div style="font-size: 12px; color: rgba(0, 0, 0, 0.45); margin-top: 5px"
              >文件支持.xlsx .xls格式，仅支持上传一个文件</div
            >
          </div>
        </el-upload>
        <div style="margin-top: 72px; margin-left: 380px; display: flex">
          <el-button type="primary" @click="handleImport" :disabled="isImportEnable"
            >导入</el-button
          >
        </div>
      </div>
    </el-card>

    <el-dialog
      v-model="DialogVisibleErr"
      title="Warning"
      width="50%"
      align-center
      @close="
        () => {
          emits('update');
        }
      "
    >
      <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">
        <div
          >修改成功：<span class="succ-sum">{{ sucCount }}</span> 条</div
        >
        <div
          >修改失败：<span class="err-sum">{{ errCount }}</span> 条</div
        >
      </div>
      <div class="err-info">
        <ul v-for="(item, index) in errDetail" :key="index">
          <li v-html="item"></li>
        </ul>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleErrComfirm"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { genFileId, ElMessage } from 'element-plus';
  import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
  import { Close, Document, WarnTriangleFilled } from '@element-plus/icons-vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { getHeaders } from '@/utils/http/axios';

  const emits = defineEmits(['close', 'update']);

  const upload = ref<UploadInstance>();
  const cardVisible = ref<boolean>(true);
  const isImportEnable = ref<boolean>(true);
  const DialogVisibleErr = ref<boolean>(false);
  const sucCount = ref<number>(0);
  const errCount = ref<number>(0);
  const errDetail = ref<string[]>([]);

  const { urlPrefix } = useGlobSetting();

  const actionUrl = computed(() => {
    return urlJoin(urlPrefix, `/admin/cameraConfig/updateCameraList`);
  });

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

  // 上传文件之前的钩子，参数为上传的文件。即上传之前验证文件类型/后缀
  const beforeUpload = (file) => {
    const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
    if (!isExcel) {
      // 提示用户选择正确的文件类型
      ElMessage({
        message: '仅支持上传.xlsx .xls格式文件',
        type: 'error',
      });
      return false; // 阻止上传
    }
    return true; // 允许上传
  };

  const handleUploadSuccess = (response, _file, _fileList) => {
    console.log(response);
    sucCount.value = response.data.successCount;
    errCount.value = response.data.failCount;
    errDetail.value = response.data.resultList;

    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 (sucCount.value != 0 && errCount.value === 0 && errDetail.value.length === 0) {
        ElMessage({
          message: '批量修改成功', // 1.全部修改成功 —— failCount === 0
          type: 'success',
        });
        emits('update');
      } else {
        DialogVisibleErr.value = true; // 2.有错误 —— 显示错误dialog
      }
      cardVisible.value = false;
    } catch (error) {
      ElMessage({
        message: '系统错误',
        type: 'error',
      });
      emits('update');
    }
  };

  const handleErrComfirm = () => {
    DialogVisibleErr.value = false;
    emits('update');
  };

  // 当超出只能上传一个文件的限制时，自动替换上一个文件
  const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles();
    const file = files[0] as UploadRawFile;
    file.uid = genFileId();
    upload.value!.handleStart(file);
  };

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

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

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

  :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;
        font-weight: 600;

        .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;
    }
  }

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