<template>
  <div class="page-check-data h-full">
    <div class="flex items-center px-4 bg-white shadow z-10 relative">
      <div class="flex-1 overflow-x-auto whitespace-nowrap">
        <el-scrollbar>
          <div class="space-x-4 py-2">
            <el-tag
              v-if="detail.archivesId"
              class="cursor-copy"
              size="large"
              v-copy:click="detail.archivesId || '-'"
            >
              <span class="align-middle select-none"
                >关联档案号:{{ detail.archivesId || "-" }}</span
              >
              <!-- <CopyDocument class="inline-block align-middle ml-2 w-4 h-4" /> -->
            </el-tag>
            <div
              v-if="
                [1, 2, 9].includes(leftView) || [1, 2, 9].includes(rightView)
              "
              class="inline-flex items-center"
            >
              <el-select
                v-model="curReport"
                class="w-40"
                @change="reportChange"
              >
                <el-option
                  v-for="(item, index) in reportList"
                  :key="index"
                  :label="item.sn"
                  :value="item.sn"
                >
                  <div class="flex items-center justify-between">
                    <span>{{ uploadDataType[item.type] }}：{{ item.sn }}</span>
                    <span
                      v-if="item.date"
                      class="ml-4 text-xs rounded text-gray-600 bg-gray-50 border-gray-200 border px-1"
                      >{{ item.date }}</span
                    >
                  </div>
                </el-option>
              </el-select>
              <!-- <CopyDocument v-copy:click="curReport" class="text-blue-600 cursor-pointer inline-block align-middle ml-2 w-4 h-4" /> -->
            </div>
            <div class="inline-flex items-center">
              <span class="align-middle">左屏：</span>
              <el-select v-model="leftView" class="w-32">
                <el-option
                  v-for="(item, index) in viewOptions"
                  :key="index"
                  :value="item.val"
                  :label="item.label"
                  :disabled="rightView == item.val"
                />
              </el-select>
              <span class="align-middle ml-4">右屏：</span>
              <el-select v-model="rightView" class="w-32">
                <el-option
                  v-for="(item, index) in viewOptions"
                  :key="index"
                  :value="item.val"
                  :label="item.label"
                  :disabled="leftView == item.val"
                />
              </el-select>
              <el-alert
                v-if="pendingDataState == 1"
                show-icon
                class="ml-4 inline-flex h-[32px] w-fit"
                title="该用户有新数据处理中"
                type="warning"
                :closable="false"
              />
              <el-alert
                v-if="pendingDataState == 2"
                class="ml-4 inline-flex h-[32px] w-fit"
                :title="`该用户所有数据已确认，分析数据截止至：${compareReportDetail.lastTime}`"
                type="success"
                :closable="false"
              />
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="py-2">
        <el-button type="primary" link @click="router.back()">
          <Fold class="h-4 w-4 mr-2" />
          <span>返回</span>
        </el-button>
      </div>
    </div>
    <div class="data-container">
      <el-row class="h-full">
        <el-col
          v-show="containerView.includes(1)"
          :style="{
            order: containerView.findIndex(v => v == 1)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <div
            v-if="detail.files.length > 1 && curFileType != 'img'"
            class="h-8 flex justify-center items-center space-x-4"
          >
            <div
              class="flex items-center text-blue-500 hover:text-blue-700 cursor-pointer"
              @click="curFileIdx--"
            >
              <ArrowLeft class="h-4 w-4" /><span>上一份</span>
            </div>
            <span>{{ curFileIdx + 1 }}/{{ detail.files.length }}</span>
            <div
              class="flex items-center text-blue-500 hover:text-blue-700 cursor-pointer"
              @click="curFileIdx++"
            >
              <span>下一份</span><ArrowRight class="h-4 w-4" />
            </div>
          </div>
          <template v-if="curFileType == 'pdf'">
            <Webview
              :url="formatFileUrlProtocol(detail.files[curFileIdx].fileUrl)"
              class="w-full h-full"
            />
          </template>
          <template v-else-if="curFileType == 'img'">
            <div v-for="(item, index) in detail.files" :key="index">
              <img
                :src="formatFileUrlProtocol(item.fileUrl)"
                alt=""
                class="w-full h-fit select-none"
              />
            </div>
          </template>
          <template v-else-if="curFileType == 'json'">
            <json-viewer
              v-if="detail.files[curFileIdx].jsonData"
              :value="detail.files[curFileIdx].jsonData"
              :show-array-index="false"
              boxed
              expanded
              preview-mode
            />
          </template>
          <el-empty v-else description="不支持的文件类型" />
        </el-col>
        <el-col
          v-show="containerView.includes(2)"
          :style="{
            order: containerView.findIndex(v => v == 2)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <el-card
            v-for="(item, index) in transferRawJson"
            :key="index"
            class="mb-4"
            shadow="never"
          >
            <div class="p-2 text-blue-600">检查数据</div>
            <el-table :data="item.bodyData">
              <el-table-column label="身体物质/部位" prop="name" />
              <el-table-column label="检查项目" prop="itemName" />
              <el-table-column label="结果" prop="value" />
              <el-table-column label="参考范围" prop="reference" />
              <el-table-column label="单位" prop="unit" />
            </el-table>
            <div class="mt-2 p-2 text-yellow-600">异常项目</div>
            <el-table :data="item.abnormalData">
              <el-table-column label="异常项目" prop="name" width="200" />
              <el-table-column label="结果">
                <template #default="{ row }">
                  <div v-if="row.value" class="space-x-2 space-y-2">
                    <el-tag
                      v-for="(val, valKey) in row.value"
                      :key="valKey"
                      type="warning"
                    >
                      <span>{{ valKey }}</span
                      >:
                      <span>{{ val }}</span>
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col
          v-show="containerView.includes(8)"
          :style="{
            order: containerView.findIndex(v => v == 8)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <div class="flex items-center justify-end p-4 space-x-4 text-sm">
            <div class="flex-1">
              <div class="mb-3">
                <span
                  class="font-bold text-base"
                  :class="
                    [
                      'text-red-400',
                      'text-red-700',
                      'text-gray-500',
                      'text-green-500'
                    ][compareReportDetail.suggestionStatus - 1]
                  "
                  >{{
                    dataSuggestStatus[compareReportDetail.suggestionStatus - 1]
                  }}</span
                >

                <div class="inline-flex items-center ml-7">
                  <span>数据变动:{{ updateDetail.list.length }}条记录</span>
                  <el-button
                    type="primary"
                    link
                    :disabled="!updateDetail.list.length"
                    @click="updateDetail.visible = true"
                    >查看></el-button
                  >
                </div>
              </div>
              <span class="text-gray-600">{{
                userDataSuggestDesc[compareReportDetail.suggestionStatus]
              }}</span>
            </div>
            <div>
              <Auth value="healthManage:suggestion:view">
                <el-button
                  type="primary"
                  @click="visibleHealthAdviceLibrary = true"
                  >健康建议库</el-button
                >
              </Auth>
            </div>

            <el-button type="warning" @click="clearCompareSuggestion"
              >清空</el-button
            >
            <el-button type="primary" plain @click="saveCompareSuggestionDraft"
              >保存草稿</el-button
            >

            <el-button
              type="primary"
              :disabled="!isCompareSuggestionDraft"
              @click="saveCompareSuggestion"
              >{{ !isCompareSuggestionDraft ? "已发布" : "发布" }}</el-button
            >
          </div>
          <div class="border border-solid border-gray-200 mx-2">
            <Toolbar
              :editor="compareEditorRef"
              :defaultConfig="{
                excludeKeys: ['uploadVideo']
              }"
              mode="default"
              class="border-b border-solid border-gray-200"
            />
            <div class="h-96 min-h-[500px]">
              <Editor
                v-model="compareSuggestion"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="editor => (compareEditorRef = editor)"
                @onChange="editorChange"
              />
            </div>
          </div>
        </el-col>
        <el-col
          v-show="containerView.includes(9)"
          :style="{
            order: containerView.findIndex(v => v == 9)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <component :is="UserDataAnalysis" />
        </el-col>
        <el-col
          v-show="containerView.includes(10)"
          :style="{
            order: containerView.findIndex(v => v == 10)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <div class="bg-white pt-2 px-2 relative">
            <el-tabs v-model="dataAnalysisActive" type="card">
              <el-tab-pane label="综合分析结果" name="0">
                <component
                  v-if="compareReportData && UserDataAnalysis"
                  :is="UserDataAnalysis"
                  :need-horizontal="true"
                />
              </el-tab-pane>
              <el-tab-pane label="疾病趋势" name="1">
                <component
                  v-if="compareReportData && TrendOfRiskChange"
                  :is="TrendOfRiskChange"
                />
              </el-tab-pane>
              <el-tab-pane label="异常数据对比" name="2">
                <component
                  v-if="compareReportData && ComparisonOfAbnormalData"
                  :is="ComparisonOfAbnormalData"
                />
              </el-tab-pane>
            </el-tabs>
            <div class="absolute right-0 top-0 p-2 pt-4">
              <el-button type="primary" link @click="refreshReportDetail">
                <Refresh class="w-4 h-4" />
                <span>重新分析</span>
              </el-button>
            </div>
          </div>
        </el-col>
        <el-col
          v-show="containerView.includes(11)"
          :style="{
            order: containerView.findIndex(v => v == 11)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full flex flex-col"
        >
          <div class="p-2">
            <el-select
              v-if="templateList.length > 1"
              v-model="curPdfTemplate"
              filterable
            >
              <el-option
                v-for="(item, index) in templateList"
                :key="index"
                :label="item.template.name"
                :value="index"
              />
            </el-select>
            <el-button
              type="primary"
              class="ml-4"
              @click="showDownloadReportDialog"
              >生成/更新报告</el-button
            >
          </div>
          <Webview
            v-if="templateList[curPdfTemplate]?.result?.pdfTransferResultUrl"
            :url="
              formatFileUrlProtocol(
                templateList[curPdfTemplate]?.result?.pdfTransferResultUrl
              )
            "
            class="w-full h-full flex-1"
          />
          <el-empty v-else description="暂无分析报告" />
        </el-col>

        <el-col
          v-show="containerView.includes(12)"
          :style="{
            order: containerView.findIndex(v => v == 12)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full overflow-y-auto"
        >
          <div class="flex items-center justify-end p-4 space-x-4 text-sm">
            <div class="flex-1" />
            <el-button type="warning" @click="clearWarningMessage"
              >清空</el-button
            >
            <el-button type="primary" @click="saveWarningMessage"
              >保存</el-button
            >
          </div>
          <div class="border border-solid border-gray-200 mx-2">
            <Toolbar
              :editor="warningMessageRef"
              :defaultConfig="{
                excludeKeys: ['uploadVideo']
              }"
              mode="default"
              class="border-b border-solid border-gray-200"
            />
            <div class="h-96 min-h-[500px]">
              <Editor
                v-model="warningMessageSuggestion"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="
                  editor => {
                    warningMessageRef = editor;
                    hasAuth('archivesReportSuggestionManage') &&
                      editor.disable();
                  }
                "
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-dialog v-model="downloadReportDialog.visible" title="下载分析报告">
      <div
        v-for="(item, index) in templateList"
        :key="index"
        class="flex flex-col py-6 border-b border-solid border-gray-100 last:border-b-0"
      >
        <div class="flex items-center justify-between mb-2">
          <div class="flex items-center">
            <el-tag v-if="item.isMember" size="small" class="mr-2"
              >用户使用</el-tag
            >
            <span>{{ item.template.name }}</span>
          </div>
          <span class="text-xs text-gray-500"
            >最近生成时间: {{ item.result?.pdfTransferEndTime || "暂无" }}</span
          >
        </div>
        <div class="flex items-center justify-between">
          <div v-if="item.result" class="flex items-center">
            <img src="@/assets/pdf.png" />
            <span>{{ detail.sn }}{{ detail.archivesId }}.pdf</span>
          </div>

          <div v-else-if="item.generateState">报告生成中...</div>
          <div v-else>暂无报告</div>
          <div>
            <el-button
              v-if="!item.generateState"
              type="primary"
              class="ml-4"
              @click="generatePdf(item)"
              >{{ item.result ? "更新" : "生成" }}</el-button
            >
            <el-button
              v-else
              type="primary"
              class="ml-4"
              @click="getPdfResultList(downloadReportDialog.row)"
              >刷新</el-button
            >
            <el-button
              type="primary"
              :disabled="!item.result"
              plain
              tag="a"
              target="_blank"
              :href="item.result?.pdfTransferResultUrl"
              >在线预览</el-button
            >
            <el-button
              type="primary"
              :disabled="!item.result"
              tag="a"
              target="_blank"
              :href="
                item.result?.pdfTransferResultUrl +
                '?response-content-type=application/octet-stream'
              "
              :download="`${downloadReportDialog.row.sn}-${downloadReportDialog.row.archivesId}.pdf`"
              >下载报告</el-button
            >
          </div>
        </div>
      </div>
      <el-empty v-if="!templateList.length" />
    </el-dialog>

    <el-dialog v-model="updateDetail.visible" title="变化详情">
      <div class="p-4">用户ID: {{ route.query.archivesId }}</div>
      <el-table :data="updateDetail.list" border>
        <el-table-column
          label="更新类型"
          :formatter="v => compareReportUpdateType[v.logType]"
        />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="medicalDataSn" label="编号" />
        <el-table-column
          label="数据类型"
          :formatter="v => uploadDataType[v.medicalDataType]"
        />
      </el-table>
    </el-dialog>
    <DialogHealthAdviceLibrary
      v-model:show="visibleHealthAdviceLibrary"
      @onAdd="handleAddHealthAdviceLibrary"
    />
  </div>
</template>

<script setup>
import { hasAuth } from "@/router/utils";

import {
  computed,
  shallowRef,
  watch,
  ref,
  nextTick,
  reactive,
  onMounted,
  provide,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  CopyDocument,
  Refresh,
  Fold,
  ArrowLeft,
  ArrowRight
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { request, parseJsonData, uploadToOSS } from "@/utils";
import JsonViewer from "vue-json-viewer";
import Webview from "@/components/WebView.vue";
import { uploadDataType, compareReportUpdateType } from "@/enumerated/archives";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  userDataSuggestStatus,
  userDataSuggestDesc
} from "@/enumerated/archives";
import DialogHealthAdviceLibrary from "./components/DialogHealthAdviceLibrary.vue";
const dataSuggestStatus = Object.values(userDataSuggestStatus);
const UserDataAnalysis = defineAsyncComponent(() =>
  import("./components/UserDataAnalysis.vue")
);

const TrendOfRiskChange = defineAsyncComponent(() =>
  import("./components/TrendOfRiskChange.vue")
);
const ComparisonOfAbnormalData = defineAsyncComponent(() =>
  import("./components/ComparisonOfAbnormalData.vue")
);

const [route, router] = [useRoute(), useRouter()];
const sn = provide("sn", route.query.sn);
const leftView = ref(10);
const rightView = ref(8);
const visibleHealthAdviceLibrary = ref(false);
const containerView = computed(() => {
  return [leftView.value, rightView.value].filter(v => v > 0);
});
const viewOptions = ref([]);
const originViewOptions = [
  {
    label: "隐藏视图",
    val: -1
  },
  {
    label: "单份原始数据",
    val: 1
  }
];
const viewOptionsMap = {
  1: [
    {
      label: "单份处理后的数据",
      val: 2
    },
    // {
    //   label: "分析结果",
    //   val: 3
    // },
    // {
    // label: "分析报告",
    // val: 4
    // },
    // {
    //   label: "单份数据分析结果",
    //   val: 9
    // },
    {
      label: "综合数据分析结果",
      val: 10
    },
    // {
    //   label: "个性化健康管理建议",
    //   val: 6
    // },
    // {
    //   label: "横向对比数据",
    //   val: 7
    // },
    {
      label: "综合个性化建议",
      val: 8
    },
    {
      label: "综合解读PDF报告",
      val: 11
    },
    {
      label: "特别提醒",
      val: 12
    }
  ],
  4: [
    {
      label: "单份处理后的数据",
      val: 2
    },
    {
      label: "综合数据分析结果",
      val: 10
    },
    {
      label: "综合个性化建议",
      val: 8
    },
    {
      label: "综合解读PDF报告",
      val: 11
    },
    {
      label: "特别提醒",
      val: 12
    }
  ]
  // 6: [
  //   {
  //     label: "填写数据",
  //     val: 5
  //   }
  // ],
  // 7: [
  //   {
  //     label: "填写数据",
  //     val: 5
  //   }
  // ]
};
const defaultView = {
  1: 2
};
const curFileIdx = ref(0);
watch(
  () => curFileIdx.value,
  idx => {
    if (idx < 0) {
      curFileIdx.value = detail.value.files.length - 1;
    } else if (idx > detail.value.files.length - 1) {
      curFileIdx.value = 0;
    }
  }
);
const detail = ref({
  sn: "",
  archivesId: "",
  transferRawJson: [],
  files: [],
  suggestion: ""
});
// provide('detail')
const curFileType = computed(() => {
  const curFile = detail.value.files[curFileIdx.value];
  if (curFile) {
    const afterFix = curFile.fileUrl.split(".").at(-1).toLocaleLowerCase();
    if (
      [
        "gif",
        "png",
        "jpg",
        "jpeg",
        "webp",
        "svg",
        "psd",
        "bmp",
        "tif"
      ].includes(afterFix)
    )
      return "img";
    return afterFix;
  }
  return "";
});

const editorRef = shallowRef();
const editorCreated = editor => {
  editorRef.value = editor;
};

const editorConfig = {
  placeholder: "请输入内容....",
  disabled: true,
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        console.log(file);
        // file 即选中的文件
        const url = await uploadToOSS(file, file.name);
        // 最后插入图片
        insertFn(url, "image");
      }
    }
  }
};
const transferRawJson = ref();
const resultRawJson = ref();
const latestResultRawJson = ref();
const transferRawJsonFormId = ref();

provide("transferRawJson", transferRawJson);
provide("formId", transferRawJsonFormId);
provide("resultRawJson", resultRawJson);
provide("latestResultRawJson", latestResultRawJson);
const formatFileUrlProtocol = url => url.replace(/^https?:/, location.protocol);
const refreshReportDetail = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "分析中..."
  });
  await getCompareReportDetail();
  await Promise.all([
    getUserUpdateDetail(),
    getReportList(),
    getAnalysisData(),
    getArchivesReportDetail()
  ]);
  ElMessage.success("操作成功");
  loading.close();
};
const getArchivesReportDetail = async (param = {}) => {
  const { data } = await request.get(
    `/idcService/mechanism/archivesReport/detail`,
    {
      params: {
        archivesId: route.query.archivesId,
        ...param
      }
    }
  );
  resultRawJson.value = parseJsonData(data.detail.resultRawData, {});

  latestResultRawJson.value = resultRawJson.value;
  console.log("resultRawJson.value", resultRawJson.value);
};
const getDetail = async (latest = false) => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/detail`,
    {
      params: {
        sn: curReport.value
      }
    }
  );
  for (const file of data.detail.files) {
    if (file.fileUrl.split(".").at(-1) == "json") {
      const jsonData = await request.get(file.fileUrl);
      console.log(jsonData);
      file.jsonData = jsonData;
    }
  }
  try {
    data.detail.resultRawJson = parseJsonData(data.detail.resultRawJson, []);

    const temp = parseJsonData(data.detail.transferRawJson, {});
    console.log(temp);
    transferRawJson.value = temp?.answers || temp || [];
    transferRawJsonFormId.value = temp?.formId;
  } catch (error) {
    console.log(error);
  }
  viewOptions.value = [
    ...originViewOptions,
    ...(viewOptionsMap[data.detail.type] || [])
  ];
  // rightView.value = defaultView[data.detail.type]
  detail.value = data.detail;
  getPDFTemplateConfig(detail.value);
  getCompareReport();
};
const curPdfTemplate = ref(0);
const templateList = ref([]);
const downloadReportDialog = reactive({
  visible: false,
  row: {},
  templateList: [],
  timer: null,
  count: 0
});
const showDownloadReportDialog = () => {
  downloadReportDialog.row = detail.value;
  // getPDFTemplateConfig(detail.value)
  downloadReportDialog.visible = true;
};

const confirmReport = async row => {
  ElMessageBox.confirm(
    `确定该报告无误，要进行确认提交吗？提交后用户可以见该报告结果`,
    "提示",
    {
      type: "warning"
    }
  ).then(async () => {
    await request.post(`/idcService/mechanism/medicalData/confirm`, {
      sn: detail.value.sn
    });
    ElMessage.success("操作成功");
  });
};
const reAnalysis = async row => {
  await request.post(`/idcService/mechanism/medicalData/reAnalysis`, {
    sn: detail.value.sn
  });
  ElMessage.success("操作成功");
};
const getPDFTemplateConfig = async row => {
  const { data } = await request.get(
    `/pdfTemplateService/mechanism/pdfTemplateMechanism/list`,
    {
      params: {
        mechanismId: row.mechanismId
      }
    }
  );
  templateList.value = (data.list || []).map(v => {
    v.result = null;
    v.generateState = false;
    v.timer = null;
    return v;
  });

  getPdfResultList(row);
};

const getPdfResultList = async row => {
  console.log(row);
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/pdfResult/list`,
    {
      params: {
        // sn: reportList.value[0]?.sn
        archivesId: row.archivesId
      }
    }
  );
  if (data.list?.length) {
    templateList.value = templateList.value.map(v => {
      const result = data.list.find(v2 => v2.pdfTemplateId == v.template.id);
      v.result = result?.pdfTransferStatus == 3 ? result : null;
      v.generateState = result?.pdfTransferStatus == 2;
      return v;
    });
    console.log(templateList.value);
  }
};
const generatePdf = async pdfRow => {
  await request.post(
    `/idcService/mechanism/medicalData/archivesPdfResult/generate`,
    {
      sn: curReport.value,
      pdfTemplateId: pdfRow.template.id,
      archivesId: downloadReportDialog.row.archivesId,
      mechanismId: pdfRow.mechanismId
    }
  );
  ElMessage.info("开始生成,请耐心等待...");
  pdfRow.result = null;
  pdfRow.generateState = true;
  pdfRow.timer && clearTimeout(pdfRow.timer);
  refreshDetail(pdfRow);
};
const refreshDetail = async pdfRow => {
  if (downloadReportDialog.count > 15) {
    pdfRow.timer && clearTimeout(pdfRow.timer);
    downloadReportDialog.count = 0;
    return;
  }
  if (!pdfRow.result) {
    downloadReportDialog.count++;
    pdfRow.timer = setTimeout(() => {
      getPdfResultList(detail.value);
      refreshDetail(pdfRow);
    }, 3e3);
  } else {
    pdfRow.timer && clearTimeout(pdfRow.timer);
    downloadReportDialog.count = 0;
  }
};
onMounted(() => {
  // getDetail();
  getReportList();
  getCompareReportDetail();
  getUserUpdateDetail();
  getAnalysisData();
  getArchivesReportDetail();
});
const latestReport = ref();
provide("latestReport", latestReport);
const curReport = ref();
const reportList = ref([]);
const getReportList = async () => {
  if (!route.query.archivesId) return false;
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/paginate`,
    {
      params: {
        typeList: "1,4",
        archivesId: route.query.archivesId,
        isAbandon: 2,
        page: 1,
        pageSize: 9999,
        fieldsSort: "date_desc"
      }
    }
  );
  // reportList.value = data.list.filter(v => v.status == 5);
  reportList.value = data.list;
  if (reportList.value[0]) {
    latestReport.value = reportList.value[0];
    curReport.value = reportList.value[0].sn;
    await getDetail(true);
  }
};
const reportChange = async sn => {
  const latest = reportList.value.findIndex(item => item.sn === sn) === 0;
  saveCompareSuggestionDraft();
  nextTick(() => {
    getDetail(latest);
  });
};
const compareEditorRef = shallowRef();
const compareSuggestion = ref("");
provide("compareSuggestion", compareSuggestion);
const compareSuggestionStatus = ref("");
provide("compareSuggestionStatus", compareSuggestionStatus);
const isCompareSuggestionDraft = ref(false);
const getCompareReport = async () => {
  if (!detail.value.archivesId) return false;
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/compareReport/detail`,
    {
      params: {
        archivesId: detail.value.archivesId
      }
    }
  );
  isCompareSuggestionDraft.value =
    data.detail?.draftSuggestion != data.detail?.suggestion;
  compareSuggestion.value =
    data.detail?.draftSuggestion || data.detail?.suggestion;
  warningMessageSuggestion.value = data.detail?.warningMessage;
  compareSuggestionStatus.value = data.detail?.suggestionStatus;
};
const clearCompareSuggestion = async () => {
  await ElMessageBox.confirm(
    `确定要清空内容吗？清空后用户端将不会展示健康建议板块，填写状态会变更为：未填写。如果本次有数据变动记录，也会被同时删除，下次有数据变动时才会通知`,
    "提示",
    {
      type: "warning"
    }
  );
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/draftSuggestion",
    {
      archivesId: detail.value.archivesId,
      suggestion:""
    }
  );
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/suggestion",
    {
      archivesId: detail.value.archivesId,
      suggestion: ""
    }
  );
  compareSuggestion.value = "";
  ElMessage.success("操作成功");
  // getCompareReport();
  getCompareReportDetail();
  getUserUpdateDetail();
  editorChangeState.value = false;
};
const saveCompareSuggestionDraft = async () => {
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/draftSuggestion",
    {
      archivesId: detail.value.archivesId,
      suggestion:
        compareSuggestion.value == "<p><br></p>" ? "" : compareSuggestion.value
    }
  );
  ElMessage.success("操作成功");
  getCompareReport();
  getCompareReportDetail();
};
const saveCompareSuggestion = async () => {
  let msg = "";
  if ([1, 2, 3].includes(compareReportDetail.value.suggestionStatus)) {
    msg = editorChangeState.value
      ? "确定要保存吗?保存后用户将看到该填写内容，同时本次数据变动记录将会被清空，下次有数据变动时才会再提醒"
      : "内容没有变化，确定保存吗?保存后用户将看到该填写内容，同时本次数据变动记录将会被清空，下次有数据变动时才会再提醒";
  } else {
    msg = editorChangeState.value
      ? "确定要保存吗?保存后用户将看到该填写内容"
      : "内容没有变化，确定保存吗?";
  }
  await ElMessageBox.confirm(msg, "提示");
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/suggestion",
    {
      archivesId: detail.value.archivesId,
      suggestion:
        compareSuggestion.value == "<p><br></p>" ? "" : compareSuggestion.value
    }
  );
  ElMessage.success("操作成功");
  getCompareReportDetail();
  getUserUpdateDetail();
  editorChangeState.value = false;
};
const editorChangeState = ref(false);
const editorChange = () => {
  editorChangeState.value = true;
};

const compareReportDetail = ref({
  awaitTotal: 0,
  processTotal: 0,
  successTotal: 0,
  doneTotal: 0,
  confirmTotal: 0,
  suggestionStatus: 0
});
// 是否存在待处理数据
const pendingDataState = computed(() => {
  const waitTotal = !!(
    compareReportDetail.value.awaitTotal ||
    compareReportDetail.value.processTotal ||
    compareReportDetail.value.successTotal ||
    compareReportDetail.value.doneTotal
  );
  if (!waitTotal && compareReportDetail.value.confirmTotal) return 2;
  return waitTotal ? 1 : 0;
});
const getCompareReportDetail = async () => {
  const { data } = await request.get(
    `/idcService/mechanism//medicalData/compareReport/detailByArchivesId`,
    {
      params: {
        archivesId: route.query.archivesId
      }
    }
  );
  compareReportDetail.value = data.detail;
};

const updateDetail = reactive({
  visible: false,
  list: []
});

const getUserUpdateDetail = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/compareReport/log`,
    {
      params: {
        archivesId: route.query.archivesId
      }
    }
  );
  updateDetail.list = data.list;
};

const warningMessageRef = ref();
const warningMessageSuggestion = ref();

const clearWarningMessage = async () => {
  await ElMessageBox.confirm(`确定要清空内容吗？`, "提示", {
    type: "warning"
  });
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/warningMessage",
    {
      archivesId: detail.value.archivesId,
      warningMessage: ""
    }
  );
  warningMessageSuggestion.value = "";
  ElMessage.success("操作成功");
};
const saveWarningMessage = async () => {
  await ElMessageBox.confirm("确定要保存吗?", "提示");
  await request.post(
    "/idcService/mechanism/medicalData/compareReport/update/warningMessage",
    {
      archivesId: detail.value.archivesId,
      warningMessage:
        warningMessageSuggestion.value == "<p><br></p>"
          ? ""
          : warningMessageSuggestion.value
    }
  );
  ElMessage.success("操作成功");
};

const dataAnalysisActive = ref("0");
const compareReportData = ref();
provide("compareReportData", compareReportData);
const getAnalysisData = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/compareReport/data/v2`,
    {
      params: {
        archivesId: route.query.archivesId
      }
    }
  );
  compareReportData.value = data.data;
};

const handleAddHealthAdviceLibrary = content => {
  compareSuggestion.value = content;
};
</script>

<style lang="scss">
.el-scrollbar__view {
  height: 100%;
  .main-content.page-check-data {
    margin: 0;
  }
}
.page-check-data {
  .data-container {
    height: calc(100% - 52px);
    width: 100%;
  }
}
</style>
