<template>
  <div>
    <div
      v-for="(item, index) in list"
      :key="index"
      class="rounded border border-solid border-gray-100 p-4 mb-4"
    >
      <div
        class="flex justify-between items-center pb-4 mb-2 border-0 border-b border-solid border-gray-100"
      >
        <div class="flex items-center">
          <span
            >关联的档案号{{ isOpenWallet ? "（必填）" : "（选填）" }}：</span
          >
          <SearchArchivesSelect
            v-model="item.archivesId"
            :disabled="!!defaultArchivesId"
            @change="archivesSelectChange"
          ></SearchArchivesSelect>
          <el-alert
            v-if="
              archivesBalanceFlag[item.archivesId] !== undefined &&
              !archivesBalanceFlag[item.archivesId]
            "
            title="该用户余额不足，无法关联"
            type="warning"
            class="w-fit ml-2"
            show-icon
            :closable="false"
          />
        </div>
        <el-upload
          :ref="r => appendUploadRefs.push(r)"
          action="#"
          multiple
          :auto-upload="false"
          :show-file-list="false"
          :on-change="
            (file, files) => appendFileChange(file, files, item, index)
          "
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
        </el-upload>
        <el-popconfirm title="是否确定删除?" @confirm="list.splice(index, 1)">
          <template #reference>
            <el-button type="danger" link>删除该批次</el-button>
          </template>
        </el-popconfirm>
      </div>
      <div>
        <el-table :data="item.files">
          <el-table-column label="文件名" prop="fileName"></el-table-column>
          <el-table-column label="数据发生日期(必填)">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.date"
                type="date"
                placeholder="请选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-popconfirm
                title="是否确定删除?"
                @confirm="item.files.splice($index, 1)"
              >
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="flex items-center">
      <el-select v-model.number="uploadType">
        <el-option label="新增单人数据" :value="0"></el-option>
        <el-option label="新增多人数据" :value="1"></el-option>
      </el-select>
      <el-upload
        ref="uploadRef"
        v-model:file-list="uploadFiles"
        action="#"
        multiple
        :auto-upload="false"
        :show-file-list="false"
        :on-change="uploadChange"
      >
        <template #trigger>
          <el-button type="primary" class="ml-4">新增</el-button>
        </template>
      </el-upload>
    </div>
    <div>
      <div class="my-2 text-red-500 text-xs">
        新增单人数据时，如果上传了多份文件，那么这些文件都会放入同一个数据批次中
      </div>
      <div class="my-2 text-red-500 text-xs">
        新增多人数据时，如果上传了多份文件，那么每一份文件都会创建一个独立的数据批次，您可以在每一个独立数据批次里面去追加单人的补充文件数据
      </div>
    </div>
    <div class="text-right">
      <el-button
        type="primary"
        :disabled="
          uploadLock ||
          !list.length ||
          (isOpenWallet &&
            list.map(v => v.archivesId).filter(v => v).length != list.length)
        "
        @click="createUploadTask"
        >保存并开始上传</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElLoading } from "element-plus";
import { ref, inject } from "vue";
import { uploadToOSS, debounce, request, disabledDate } from "@/utils";

import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";

import { useUserStoreHook } from "@/store/modules/user";
const mechanismId = useUserStoreHook()?.profile.id;
const defaultArchivesId = inject("defaultArchivesId") || "";
const getDataList = inject("getList");
const closeUploadDialog = inject("closeUploadDialog");
const list = ref([]);
// uploadToOSS()
const uploadType = ref(0);
const uploadRef = ref();
const uploadFiles = ref([]);
const uploadChange = debounce((file, files) => {
  console.log(uploadFiles.value, file, files);
  if (uploadType.value) {
    files.forEach(f => {
      list.value.push({
        type: uploadType.value,
        archivesId: defaultArchivesId.value || "",
        files: [
          {
            raw: f.raw,
            fileName: f.name,
            date: "",
            fileUrl: "",
            remark: ""
          }
        ]
      });
    });
  } else {
    list.value.push({
      type: uploadType.value,
      files: files.map(f => ({
        raw: f.raw,
        fileName: f.name,
        date: "",
        fileUrl: "",
        remark: ""
      })),
      archivesId: defaultArchivesId.value || ""
    });
  }
  uploadRef.value.clearFiles();
}, 1e2);
const appendUploadRefs = ref([]);
const appendFileChange = debounce((file, files, item, index) => {
  console.log(files, item);
  console.log(appendUploadRefs.value[index]);
  files.forEach(f => {
    item.files.push({
      raw: f.raw,
      fileName: f.name,
      date: "",
      fileUrl: "",
      remark: ""
    });
  });
  appendUploadRefs.value.forEach(v => {
    v.clearFiles && v.clearFiles();
  });
}, 1e2);

const uploadLock = ref(false);
const createUploadTask = async () => {
  uploadLock.value = true;

  const uploadFileTotal = list.value.reduce((a, b) => a + b.files.length, 0);
  console.log(uploadFileTotal);
  if (!uploadFileTotal) return ElMessage.error("请新增数据后保存");
  if (
    uploadFileTotal !=
    list.value
      .map(v => v.files.map(f => f.date))
      .flat()
      .filter(v => v).length
  ) {
    uploadLock.value = false;
    return ElMessage.error("请填写所有文件的发生日期");
  }
  const loading = ElLoading.service({
    lock: true,
    text: "开始上传",
    background: "rgba(255, 255, 255, 0.7)"
  });
  try {
    let uploadCount = 0;
    for (const item of list.value) {
      for (const v of item.files) {
        v.fileUrl = await uploadToOSS(v.raw, v.fileName);
        uploadCount++;
        loading.text = `正在上传文件${uploadCount}/${uploadFileTotal}`;
      }
    }

    loading.text = `批次处理中`;
    await Promise.all(
      list.value.map(item => {
        return request.post(`/medicalData/create`, { ...item, type: 1 });
      })
    );
    ElMessage.success("创建完成");
    getDataList();
    closeUploadDialog();
  } catch (e) {
    console.log(e);
  }
  uploadLock.value = false;
  loading.close();
};
const isOpenWallet = ref(false);
const checkMechanismWallet = async () => {
  const { data } = await request.get(
    "/walletService//openapi/walletType/mechanism",
    {
      params: {
        walletTypeId: 1,
        mechanismId
      }
    }
  );
  isOpenWallet.value = !!data;
};
checkMechanismWallet();
const checkBalance = async archiveSn => {
  if (!isOpenWallet.value) return true;
  const { data } = await request.get(
    `/walletService/mechanism/user/wallet/balance`,
    {
      params: {
        archiveSn,
        walletTypeId: 1
      }
    }
  );
  if (data.balanceType == -1) return true;
  return data.balance > 0;
};
const archivesBalanceFlag = ref({});
const archivesSelectChange = async (archivesId, archives) => {
  console.log(archives);
  archivesBalanceFlag.value[archivesId] = true;
  archivesBalanceFlag.value[archivesId] = await checkBalance(
    archives.mainArchivesId || archives.id
  );
};
</script>

<style lang="scss" scoped></style>
