<template>
  <div>
    <div class="flex items-center mb-2">
      <span>需要上传原始数据和文件</span>
      <el-switch v-model="needUpload"></el-switch>
    </div>
    <template v-if="needUpload">
      <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>
            <span>关联的档案号（选填）：</span>
            <SearchArchivesSelect
              v-model="item.archivesId"
              :disabled="!!defaultArchivesId"
            ></SearchArchivesSelect>
          </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"
          @click="createUploadTask"
          >保存并开始上传</el-button
        >
      </div>
    </template>
    <template v-else>
      <el-form :inline="true">
        <el-form-item label="关联的档案号" required>
          <SearchArchivesSelect v-model="archivesId" :disabled="!!defaultArchivesId"></SearchArchivesSelect>
        </el-form-item>
        <el-form-item label="选择疾病" required>
          <el-select
            v-model="curNode"
            filterable
            clearable
            @change="nodeChange"
          >
            <el-option
              v-for="(item, index) in nodes"
              :key="index"
              :label="item.properties?.name"
              :value="item.id"
            ></el-option
          ></el-select>
        </el-form-item>
        <el-form-item label="选择回访数据" required>
          <el-select
            v-model="formId"
            :disabled="!archivesId || !curNode"
            filterable
            clearable
            @change="formChange"
            @clear="form = undefined"
          >
            <el-option
              v-for="(item, index) in formList"
              :key="index"
              :label="item.properties?.name"
              :value="item.properties?.['表单ID']"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择回访日期" required>
          <el-date-picker
            v-model="date"
            type="datetime"
            placeholder="请选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-form>
      <div>
        <ArchivesModule is-plat :module-id="formId" :form="form" />
      </div>
      <div class="text-right mt-4">
        <el-button
          type="primary"
          :disabled="!form && !transferRawJson.length"
          @click="submitFormData"
          >保存并开始上传</el-button
        >
      </div>
    </template>
  </div>
</template>

<script setup>
import { ElMessage, ElLoading } from "element-plus";
import { ref, inject, shallowRef, defineAsyncComponent, provide } from "vue";
import { uploadToOSS, debounce, request, disabledDate } from "@/utils";
import dayjs from "dayjs";
import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";
const ArchivesModule = defineAsyncComponent(() =>
  import("@/views/dataCenter/components/ArchivesModule.vue")
);
const getDataList = inject("getList");
const closeUploadDialog = inject("closeUploadDialog");
const defaultArchivesId = inject("defaultArchivesId") || "";
const list = ref([]);
// uploadToOSS()

const needUpload = ref(false);

const archivesId = ref(defaultArchivesId.value || "");
const date = ref();
const curNode = ref("");
const nodes = shallowRef([]);
const searchNodes = async () => {
  const { data } = await request.get(`/graphService/open/node/paginate`, {
    params: {
      page: 1,
      pageSize: 9999,
      tag: "可回访"
    }
  });
  nodes.value = data.list;
};
searchNodes();

const searchRelateNodes = async (id, relationship) => {
  if (!id) return;
  const { data } = await request.get(`/graphService/open/node/related`, {
    params: {
      id,
      relationship
    }
  });
  return data;
};
const formId = ref("");
const form = ref();
const formList = shallowRef([]);
const transferRawJson = ref([]);
provide("transferRawJson", transferRawJson);
const nodeChange = async v => {
  const data = await searchRelateNodes(v, "回访表单信息");
  formList.value = data;
  formId.value = "";
  form.value = undefined;
};
const formChange = v => {
  if (!formId.value) return;
  getFormDetail();
};
const getFormDetail = async () => {
  const { data } = await request.get(`/archivesService/mechanism/form/detail`, {
    params: {
      archivesId: archivesId.value,
      formId: formId.value,
      needCheckItemId: 1,
      isOpen: 1
    }
  });
  form.value = data.detail;
  // getFillFormData();
};
const submitSimpleFormData = async (answers, close) => {
  console.log(answers);
  const answersNo = answers.map(v => v.answer.questionNo);
  transferRawJson.value = [
    ...transferRawJson.value?.filter(
      v => !answersNo.includes(v.answer.questionNo)
    ),
    ...answers
  ];
  close && close();
};
provide("submitSimpleFormData", submitSimpleFormData);
const submitFormData = async () => {
  const req = {
    transferRawJson: JSON.stringify({
      formId: formId.value,
      diseaseId: curNode.value,
      answers: transferRawJson.value
    }),
    type: 3,
    archivesId: archivesId.value,
    date: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")
  };
  console.log(req);
  await request.post(`/medicalData/create`, req);
  ElMessage.success("操作成功");
  closeUploadDialog();
  getDataList();
};

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: archivesId.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: archivesId.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: 3 });
      })
    );
    ElMessage.success("创建完成");
    getDataList();
    closeUploadDialog();
  } catch (e) {
    console.log(e);
  }
  uploadLock.value = false;
  loading.close();
};
</script>

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