<template>
  <div>
    <el-dialog
      title="新增数据集"
      v-model="dialogVisible"
      :close-on-click-modal="false"
    >
      <div v-if="!state.dataDetectionVisible">
        <div>
          <h3>
            请下载模板文件，按照模板文件数据格式 填充数据后上传，否则会上传失败
          </h3>
          <div class="mt-3">
            <div class="flex items-center mb-2">
              <img src="@/assets/excel.png" style="width: 50px; height: 50px" />
              <el-link
                @click="
                  handleDown(
                    '体检数据excel模板下载（数据横向展示）.xlsx',
                    'https://oss.mdfitnesscao.com/merchant/XDYDMc51tt48Mx77yMYT0Kf1RpCBQSy71EahFphiTPj5NDRe.xlsx'
                  )
                "
              >
                体检数据excel模板下载（数据横向展示）
              </el-link>
            </div>
            <div class="flex items-center">
              <img src="@/assets/excel.png" style="width: 50px; height: 50px" />
              <el-link
                @click="
                  handleDown(
                    '体检数据excel模板下载（数据纵向展示）.xlsx',
                    'https://oss.mdfitnesscao.com/merchant/AGEHCBk67XfaJthNcTjtcdWDSTRT7YjmKFkAcHZ3knN6F4JK.xlsx'
                  )
                "
                >体检数据excel模板下载（数据纵向展示）</el-link
              >
            </div>
          </div>
        </div>
        <el-divider></el-divider>
        <div>
          <el-form ref="form" label-width="100px" label-position="left">
            <el-form-item label="数据集名称:">
              <el-input
                v-model="state.name"
                placeholder="请输入本次数据集名称，方便搜索"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-upload
            class="upload-demo"
            v-model:file-list="state.uploadFiles"
            ref="uploadRef"
            drag
            action="#"
            :auto-upload="false"
            multiple
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽文件或者<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">上传Excel数据文件</div>
            </template>
          </el-upload>
        </div>
      </div>
      <div v-else>
        <div
          class="flex items-center pl-2 pr-2"
          style="background: var(--el-color-warning-light-7)"
        >
          <span style="color: #f56c6c" v-if="state.loading"
            >数据格式检测中，请稍后...</span
          >
          <span style="color: #67c23a" v-else>数据检测完毕</span>
          <el-button type="primary" link>
            <el-icon class="el-icon--refresh ml-4"
              ><Refresh class="fs-xs"></Refresh
            ></el-icon>
            刷新</el-button
          >
        </div>
        <el-table
          :data="state.uploadResult.data"
          border
          style="width: 100%"
          class="mt-4"
        >
          <el-table-column prop="Filename" label="文件名称" />
          <el-table-column prop="说明" label="说明">
            <template #default="{ row }">
              <div v-if="!row.Errs.length">
                <div style="color: var('--el-color-success-light-3: ')">
                  检查通过
                </div>
              </div>
              <div v-for="(item, index) in row.Errs" :key="index">
                <div style="color: #f56c6c">{{ item }}</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div v-if="!state.dataDetectionVisible">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">下一步</el-button>
        </div>
        <div v-else>
          <el-button @click="() => (state.dataDetectionVisible = false)"
            >上一步</el-button
          >
          <el-button
            type="primary"
            :disabled="state.uploadResult.code !== 200"
            @click="
              () => {
                dialogVisible = false;
                emits('success');
              }
            "
            >完成</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits, watch, reactive } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { uploadToOSS, debounce, request } from "@/utils";
import { UploadFilled, Refresh } from "@element-plus/icons-vue";
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});
const state = reactive({
  name: "",
  uploadFiles: [],
  dataDetectionVisible: false,
  loading: false,
  uploadResult: {
    code: 200,
    data: []
  }
});
const emits = defineEmits(["update:show", "success"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});

watch(
  () => dialogVisible.value,
  n => {
    if (n) {
    } else {
      onReset();
    }
  }
);
const onReset = () => {
  state.dataDetectionVisible = false;
  state.uploadResult = {
    code: 200,
    data: []
  };
  state.name = "";
  state.uploadFiles = [];
};
const handleDown = (name, url) => {
  const x = new window.XMLHttpRequest();
  x.open("GET", url, true);
  x.responseType = "blob";
  x.onload = () => {
    const url = window.URL.createObjectURL(x.response);
    const a = document.createElement("a");
    a.href = url;
    a.target = "_self";
    a.download = name;
    a.style.display = "none";
    a.click();
  };
  x.send();
};
const handleSubmit = async resp => {
  let list = state.uploadFiles;
  let formdata = new FormData();
  if (!list.length) {
    return ElMessage.error("请选择数据集");
  }
  const loading = ElLoading.service({
    lock: true,
    text: "开始上传",
    background: "rgba(255, 255, 255, 0.7)"
  });
  formdata.append("name", state.name);
  try {
    let uploadCount = 0;
    for (const item of list) {
      // item.fileUrl = await uploadToOSS(item.raw, item.name);
      formdata.append("upload[]", item.raw), uploadCount++;
      // loading.text = `正在上传文件${uploadCount}/${list.length}`;
    }
    loading.text = `正在上传文件${uploadCount}/${list.length}`;
    request
      .post("/dataService/dataParse/mechanism/upload/files", formdata, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then(resp => {
        state.dataDetectionVisible = true;
        state.uploadResult = resp;
        state.loading = false;
        emits("success");
      });
    console.log("上传的文件列表", state.uploadFiles);
  } catch (e) {
    console.log(e);
  }
  loading.close();
  state.loading = false;
};
</script>
