<template>
  <div class="page-check-data h-full">
    <div class="flex items-center px-4 bg-white">
      <div class="flex-1 overflow-x-auto whitespace-nowrap">
        <el-scrollbar>
          <div class="space-x-4 py-2">
            <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-option>
            </el-select>
            <span class="align-middle">右屏：</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-option>
            </el-select>
          </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 px-4"
        >
          <div class="flex justify-between p-4 bg-white my-2 rounded">
            <div>分析结果</div>
            <el-button type="primary" link @click="reanalysis"
              >重新分析</el-button
            >
          </div>
          <div class="my-4 bg-white p-4 rounded">
            <el-descriptions title="企业信息" :column="2">
              <el-descriptions-item label="单位名称">{{
                detail.groupName
              }}</el-descriptions-item>
              <el-descriptions-item label="体检人数">{{
                Math.max(detail.medicalDataTotal, detail.personTotal)
              }}</el-descriptions-item>
              <el-descriptions-item label="体检日期"
                >{{ detail.medicalDataStartDate }} ~
                {{ detail.medicalDataEndDate }}</el-descriptions-item
              >
              <el-descriptions-item label="报告日期">{{
                detail.date
              }}</el-descriptions-item>
            </el-descriptions>
          </div>
          <template v-if="pushData">
            <component v-if="SeriousDiseases" :is="SeriousDiseases" />
            <component v-if="AbnormalityIndicator" :is="AbnormalityIndicator" />
            <component v-if="Overview" :is="Overview" />
            <div
              v-for="(item, index) in pushData?.analyzeResult
                ?.departmentAnalyze"
              :key="index"
            >
              <component
                v-if="SectorAnalysis"
                :is="SectorAnalysis"
                :data="item"
              />
            </div>
            <div v-for="(item, index) in suggestionType" :key="index">
              <Summary
                v-if="detail[item.key] && detail[item.key] != '<p><br></p>'"
                :title="item.label"
                :data="detail[item.key]"
              />
            </div>
          </template>
        </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 px-4"
        >
          <div class="py-4 flex justify-between items-center">
            <el-select v-model="curSuggestionType" filterable>
              <el-option
                v-for="(item, index) in suggestionType"
                :key="index"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>

            <div>
              <el-button @click="clearSuggestion">清空</el-button>
              <el-button type="primary" @click="saveSuggestion">保存</el-button>
            </div>
          </div>
          <div class="border border-solid border-gray-200">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="{
                excludeKeys: ['uploadVideo']
              }"
              mode="default"
              class="border-b border-solid border-gray-200"
            />
            <div class="h-96 min-h-[500px]">
              <Editor
                v-model="detail[curSuggestionType]"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="editorCreated"
              />
            </div>
          </div>
        </el-col>
        <el-col
          v-show="containerView.includes(3)"
          :style="{
            order: containerView.findIndex(v => v == 3)
          }"
          :span="containerView.length > 1 ? 12 : 24"
          class="h-full"
        >
          <div class="flex flex-col h-full">
            <div class="flex justify-between p-4 bg-white my-2 rounded">
              <el-link
                v-if="detail.pdfTransferResultUrl"
                @click="
                  downloadReportRename(
                    detail.pdfTransferResultUrl +
                      '?response-content-type=application/octet-stream',
                    `${detail.groupName}团体健康分析报告.pdf`
                  )
                "
              >
                <el-icon>
                  <Download />
                </el-icon>
                <span>下载报告</span>
              </el-link>
              <div v-else></div>
              <el-button type="primary" link @click="generatePdf"
                >生成/更新报告</el-button
              >
            </div>
            <el-empty
              v-if="detail.pdfTransferStatus == 2"
              description="报告生成中..."
            >
              <el-button @click="getDetail">刷新</el-button>
            </el-empty>
            <Webview
              v-else-if="detail.pdfTransferResultUrl"
              :url="detail.pdfTransferResultUrl"
              class="w-full h-full flex-1"
            ></Webview>
            <el-empty v-else description="暂未生成报告"></el-empty>
          </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-empty>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  computed,
  shallowRef,
  watch,
  ref,
  nextTick,
  reactive,
  onMounted,
  provide,
  defineAsyncComponent
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { Download, Fold, ArrowLeft, ArrowRight } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox,ElLoading } from "element-plus";
import {
  request,
  parseJsonData,
  uploadToOSS,
  downloadReportRename
} from "@/utils";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import Webview from "@/components/WebView.vue";

const Overview = defineAsyncComponent(() =>
  import("./components/teamReport/Overview.vue")
);
const AbnormalityIndicator = defineAsyncComponent(() =>
  import("./components/teamReport/AbnormalityIndicator.vue")
);
const SeriousDiseases = defineAsyncComponent(() =>
  import("./components/teamReport/SeriousDiseases.vue")
);
const SectorAnalysis = defineAsyncComponent(() =>
  import("./components/teamReport/SectorAnalysis.vue")
);
const Summary = defineAsyncComponent(() =>
  import("./components/teamReport/Summary.vue")
);

const [route, router] = [useRoute(), useRouter()];

const leftView = ref(1);
const rightView = ref(2);
const containerView = computed(() => {
  return [leftView.value, rightView.value].filter(v => v > 0);
});

const viewOptions = ref([
  {
    label: "隐藏视图",
    val: -1
  },
  {
    label: "分析结果",
    val: 1
  },
  {
    label: "分析建议",
    val: 2
  },
  {
    label: "PDF报告",
    val: 3
  }
]);
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: [],
  pdfTransferResultUrl: "",
  healthSuggestion: "",
  abnormalSuggestion: "",
  departmentAbnormalSuggestion: "",
  occupationalHealthSuggestion: "",
  improvingSuggestion: ""
});

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

const editorConfig = {
  placeholder: "请输入内容....",
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        console.log(file);
        // file 即选中的文件
        const url = await uploadToOSS(file, file.name);
        // 最后插入图片
        insertFn(url, "image");
      }
    }
  }
};
const curSuggestionType = ref("healthSuggestion");
const suggestionType = [
  {
    label: "企业员工健康水平年度小结",
    key: "healthSuggestion"
  },
  {
    label: "企业员工重点异常项目分析",
    key: "abnormalSuggestion"
  },
  {
    label: "各部门重点异常项目分析",
    key: "departmentAbnormalSuggestion"
  },
  {
    label: "本企业职业影响因素分析",
    key: "occupationalHealthSuggestion"
  },
  {
    label: "企业员工健康水平提升建议",
    key: "improvingSuggestion"
  }
];
const pushData = ref();
provide("pushData", pushData);
const getDetail = async () => {
  const { data } = await request.get(
    `/idcService/mechanism/channelMedicalReport/detail`,
    {
      params: {
        id: route.query.id
      }
    }
  );
  // 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 {
    pushData.value = parseJsonData(data.detail.pushData);
  } catch (error) {
    console.log(error);
  }
  detail.value = data.detail;
  console.log("push data: ", pushData.value);
};
const saveSuggestion = async () => {
  await request.post(
    `/idcService/mechanism/channelMedicalReport/update/suggestion`,
    {
      id: Number(route.query.id),
      suggestionField: curSuggestionType.value,
      suggestion:
        detail.value[curSuggestionType.value] == "<p><br></p>"
          ? ""
          : detail.value[curSuggestionType.value]
    }
  );
  ElMessage.success("保存成功");
};
const clearSuggestion = async () => {
  await ElMessageBox.confirm(`确定要清空内容吗？`, "提示", {
    type: "warning"
  });
  await request.post(
    `/idcService/mechanism/channelMedicalReport/update/suggestion`,
    {
      id: Number(route.query.id),
      suggestionField: curSuggestionType.value,
      suggestion: ""
    }
  );
  ElMessage.success("清空成功");
};
onMounted(() => {
  getDetail();
});

const reanalysis = async () => {
  await ElMessageBox.confirm(`是否确认重新分析？`, "提示", {
    type: "warning"
  });

  await request.post(`/idcService/mechanism/channelMedicalReport/reAnalysis`, {
    id: Number(route.query.id)
  });

  const loading = ElLoading.service({
    lock: true,
    text: '分析中...',
    background: 'rgba(255, 255, 255, 0.7)',
  })

  setTimeout(() => {
    getDetail()
    loading.close()
  }, 3e3);
};
const curPdfTemplate = ref(0);
const templateList = ref([]);
const downloadReportDialog = reactive({
  visible: false,
  row: {},
  templateList: [],
  timer: null,
  count: 0
});
const showDownloadReportDialog = () => {
  // getPDFTemplateConfig(detail.value)
  downloadReportDialog.visible = true;
};

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 => {
  const { data } = await request.get(
    `/idcService/mechanism/medicalData/pdfResult/list`,
    {
      params: { sn: reportList.value[0]?.sn }
    }
  );
  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/channelMedicalReport/generate/pdfReport`,
    {
      id: Number(route.query.id)
    }
  );
  ElMessage.info("开始生成,请耐心等待...");
  getDetail();
};
</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>
