<template>
  <div>
    <div class="rounded border border-solid border-gray-100 p-4 mb-4">
      <div
        class="flex items-center pb-4 mb-2 space-x-2 border-0 border-b border-solid border-gray-100"
      >
        <div>
          <span>关联的档案号（必填）：</span>
          <SearchArchivesSelect
            v-model="archivesId"
            :disabled="!!defaultArchivesId"
          ></SearchArchivesSelect>
        </div>
        <div>
          <span>检查数据：</span>
          <el-select
            v-model="curNode"
            multiple
            filterable
            clearable
            collapse-tags
          >
            <el-option
              v-for="(item, index) in nodes"
              :key="index"
              :label="item.properties?.name"
              :value="item.id"
            ></el-option
          ></el-select>
        </div>
        <el-button type="primary" :disabled="!curNode.length" @click="add"
          >添加</el-button
        >
      </div>
      <div>
        <el-table :data="list">
          <el-table-column label="项目名称" prop="name"></el-table-column>
          <el-table-column label="检查结果(必填)">
            <template #default="{ row }">
              <el-input v-model="row.value" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="参考范围(必填)">
            <template #default="{ row }">
              <el-input v-model="row.reference" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位(必填)">
            <template #default="{ row }">
              <el-input v-model="row.unit" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="检测时间(必填)" width="260">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.date"
                type="datetime"
                placeholder="请选择日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled-date="disabledDate"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-button type="primary" link @click="addItem(row, $index)"
                >继续添加该项目</el-button
              >
              <el-popconfirm
                title="是否确定删除?"
                @confirm="list.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"></div>
    <div class="text-right">
      <el-button type="primary" @click="confirm">保存并开始上传</el-button>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElLoading } from "element-plus";
import { ref, shallowRef, inject, onMounted } from "vue";
import { uploadToOSS, debounce, request, findScope, disabledDate } from "@/utils";
import dayjs from "dayjs";
import SearchArchivesSelect from "@/components/Archives/SearchArchivesSelect.vue";
const getDataList = inject("getList");
const closeUploadDialog = inject("closeUploadDialog");

const defaultArchivesId = inject("defaultArchivesId") || "";
const archivesId = ref(defaultArchivesId.value || "");
const curNode = ref([]);
const nodes = shallowRef([]);
const list = ref([]);

const searchNodes = async () => {
  const { data } = await request.get(`/graphService/open/node/paginate`, {
    params: {
      page: 1,
      pageSize: 9999,
      tag: "日常监测指标"
    }
  });
  nodes.value = data.list;
};
const searchRelateNodes = async (id, relationship) => {
  if (!id) return;
  const { data } = await request.get(`/graphService/open/node/related`, {
    params: {
      id,
      relationship
    }
  });
  return data;
};
const add = async () => {
  const tmp = [];
  for (const id of curNode.value) {
    const raw = nodes.value.find(item => item.id == id);
    const node = await searchRelateNodes(id, "可检测");
    const relationship = await searchRelateNodes(id, "默认单位与范围");
    console.log(raw, relationship);
    tmp.push({
      value: "",
      unit: relationship[0]?.properties?.name,
      reference: relationship[0]?.rProperties?.["参考范围"],
      referenceStart: "",
      referenceEnd: "",
      abnormalId: [],
      abnormalDatas: [],
      name: raw.properties?.name,
      id,
      date: "",
      itemId: node[0]?.id || ""
    });
  }
  list.value.push(...tmp);
};
const addItem = (row, index) => {
  const tmp = {
    ...row
  };
  tmp.value = "";
  list.value.splice(index + 1, 0, tmp);
};
const confirm = async () => {
  if (!archivesId.value) {
    return ElMessage.error("请选择关联档案");
  }
  for (const item of list.value) {
    if ((!item.value && item.value !== 0) || !item.date) {
      return ElMessage.error("请填写必填项");
    }
  }
  const req = [
    {
      bodyData: list.value.map(item => {
        const scope = findScope(item.reference);
        console.log(scope);
        item.referenceStart = scope?.start || "";
        item.referenceEnd = scope?.end || "";
        item.date = dayjs(item.date).unix();
        return item;
      }),
      surveyData: [],
      abnormalData: [],
      date: dayjs(Date.now()).unix()
    }
  ];
  console.log(req);
  await request.post(`/medicalData/create`, {
    type: 2,
    archivesId: archivesId.value,
    date: dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss"),
    transferRawJson: JSON.stringify(req)
  });
  ElMessage.success("创建完成");
  getDataList && getDataList();
  closeUploadDialog && closeUploadDialog();
};
onMounted(() => {
  searchNodes();
});
</script>

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