<template>
  <div>
    <div
      v-show="examId"
      v-loading="!requestStatus"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="width:21cm;background: #fff;"
    >
    <!-- :style="{border:requestStatus ? '1px solid':'',}" -->
      <common
        :generallySeen="generallySeen"
        :verdict="verdict"
        :rispData="rispData"
        :baseInfo="baseInfo"
        :rispReport="rispReport"
        :curDiagnosis="curDiagnosis"
        style=" page-break-before: always;"
        v-show="requestStatus"
      />
      <div class="doctopdf-paging" v-show="requestStatus && addPageShow"></div>

      <add-page
        :rispData="rispData"
        :baseInfo="baseInfo"
        :rispReport="rispReport"
        :refences="refences"
        style=" page-break-before: always;"
        v-show="requestStatus && addPageShow"
      />
      <div class="doctopdf-paging" v-show="requestStatus && answer.length"></div>

      <capPage
        :templates="question"
        :dataNodes="answer"
        :rispData="rispData"
        :baseInfo="baseInfo"
        :rispReport="rispReport"
        style=" page-break-before: always;"
        v-if="requestStatus && answer.length"
      />
    </div>

    <div v-show="!examId"></div>
  </div>
</template>

<script>
import moment from "moment";

import common from "./common.vue";
import addPage from "./add-page.vue";
import capPage from "./cap-page.vue";
import print from "aegle-sp-components/src/utils/printRisp";

export default {
  name: "risp-report",
  components: {
    common,
    addPage,
    capPage
  },
  props: {
    examId: {
      type: [Number, String],
      default: -200
    },
    isPrint: {
      type: Boolean,
      default: false
    },
    cap: {
      type: Boolean,
      default: false // 该属性为暂时在时间轴和九宫格中屏蔽 cap 模块
    },
    getDocReprotDataRequest: Function,
    getExamsInfoRequest: Function,
    getReportBaseInfoRequest: Function,
    getReferenceByReportIdRequest: Function,
    checkUniqueRequest: Function,
    getCurtCapHistoryFormRequest: Function
  },

  methods: {
    initRequestStatus(status) {
      this.request1 = status;
      this.request2 = status;
      this.request3 = status;
    },
    getData() {
      this.initRequestStatus(false);
      this.getRispData();
      this.getRispReport();
    },
    getRispData() {
      this.getExamsInfoRequest(this.examId).then((res) => {
        if (res.code == 0) {
          this.rispData.mrCode = res.data.mrCode;
          this.rispData.mr.PathologyClass = JSON.parse(
            res.data.mr
          ).PathologyClass;
          this.rispData.parentId = res.data.parentId;
          this.getPathologyData(res.data.hisSheetId);
        } else {
          this.request1 = true
          this.$message.error(res.msg)
        }
      });
    },
    getRispReport() {
      this.getDocReprotDataRequest(this.examId).then((res) => {
        if (res.code == 0 && res.data) {
          this.getReference(res?.data?.id);
          if (res.data?.type == "0") {
            this.isCap = true;
            this.getCapData();
            const diagnoseList = (newTableData, diagnoseCon) => {
              let list = [];
              newTableData.forEach(element => {
                list.push(
                  (element.histology.value || "") +
                    "    " +
                    (element.tnm || "") +
                    "    " +
                    (element.stage || "")
                );
              });
              if (diagnoseCon) {
                list.push(diagnoseCon);
              }
              return list;
            };
            this.verdict = diagnoseList(
              JSON.parse(res.data.pathologyAndStaging),
              res.data.verdict
            );
          } else {
            this.isCap = false;
            let verdict = res?.data?.verdict ? res?.data?.verdict : "";
            this.verdict = [];
            if (verdict) {
              this.verdict.push(verdict);
            }
          }
          this.generallySeen = res?.data?.generallySeen
            ? res?.data?.generallySeen
            : "";
          // this.verdict = res.data.verdict ? res.data.verdict : "";

          //   this.rispReport = res.data;
          for (let key in this.rispReport) {
            this.rispReport[key] = res.data && res.data.hasOwnProperty(key) ? res.data[key] : '';
          }
          this.request2 = true;
        } else {
          this.request2 = true;
        }
      });
    },
    getPathologyData(hisSheetId) {
      this.getReportBaseInfoRequest(hisSheetId).then((res) => {
        if (res.code == 0) {
          let keys = [
            "healthCardNum",
            "patientName",
            "sex",
            "birthday",
            "sendTime",
            "departmentName",
            "inspectionAgency",
            "age"
          ];
          let titles = [
            "患者 ID : ",
            "姓名: ",
            "性别: ",
            "出生日期: ",
            "送检日期: ",
            "送检科室: ",
            "送检医院: ",
            "年龄: "
          ];
          this.baseInfo = [];

          keys.forEach((key, i) => {
            let value = res.data[key];
            if (key == "age") {
              value += " 岁";
            }

            if (key == "birthday" || key == "sendTime") {
              let date1 = new Date(value);
              value = value ? moment(date1).format("YYYY-MM-DD") : "";
            }
            this.baseInfo.push({
              title: titles[i],
              value
            });
          });

          this.curDiagnosis = [];
          this.curDiagnosis.push(
            {
              title: "临床诊断：",
              value: res.data.clinicalDiagnosis
            },
            {
              title: "标本名称：",
              value: res.data.sampleLabelList
            }
          );

          this.request1 = true;
        }
      });
    },

    splitFileName(file) {
      let formatIndex = file.fileName.lastIndexOf(".");
      let value = file.fileName.slice(0, formatIndex);
      let format = file.fileName.slice(formatIndex + 1);
      return {
        value,
        format
      };
    },

    getReference(reportId) {
      this.getReferenceByReportIdRequest(reportId).then((res) => {
        if (res.code == 0) {
          this.refences = res.data.map(file => {
            let { format } = this.splitFileName(file);
            return { ...file, format };
          });

          this.request2 = true;
        }
      });
    },

    // 处理 subject 和 links
    handleSAndL(form) {
      let historyData = form;
      let newHistoryData;
      let newChildren = [];
      newHistoryData = JSON.parse(JSON.stringify(historyData));
      historyData.children.forEach((ele) => {
        if (ele.category !== "archetype::rm") {
          newChildren.push(ele);
        }
      });
      newHistoryData.children = newChildren;
      return newHistoryData;
    },

    getCapData() {
      this.checkUniqueRequest(this.examId).then((res) => {
        if (res.code == 0 && res.data) {
          this.answer = JSON.parse(res.data.doc).content;
          let formTitle = res.data.formTitle;
          let formVersion = res.data.formVersion;
          let formVersionId = `${formTitle}.${formVersion}`;
          this.getCurtCapHistoryFormRequest(formVersionId, 0).then(
            (response) => {
              if (response.code == 0) {
                this.question = this.handleSAndL(
                  JSON.parse(response.data.content)
                ).children;

                this.request3 = true;
              }
            }
          );
        }
      });
    },
    // 打印
    print() {
      let arr = [];

      let clazzes = [".risp-common-page", ".risp-add-page"];
      if (this.isCap) {
        clazzes.push(".risp-cap-page");
      }
      for (let index = 0; index < clazzes.length; index++) {
        let parentHrtmlDom = document.querySelector(clazzes[index]);
        arr.push({
          headerDom: parentHrtmlDom.querySelector(".risp-view-top"),
          footerDom: parentHrtmlDom.querySelector(".risp-view-bottom"),
          containerDom: parentHrtmlDom.querySelector(".risp-view-middle")
        });
      }
      print({
        mul: true,
        arr: arr
      });
    },
    // 状态重置
    resetData() {
      this.generallySeen = "";
      this.verdict = [];
      this.rispData = {
        mrCode: "",
        mr: {
          PathologyClass: ""
        },
        parentId: ""
      }

      this.rispReport =  {
        content: "",
        generallySeen: "",
        healthCardNo: "",
        jsonData: "",
        reference: "",
        remark: "",
        reportDoctor: "",
        reportTime: "",
        reviewDoctor: "",
        reviewTime: "",
        type: "",
        verdict: "",
        lensSeen: ""
      }

      this.baseInfo= []
      this.curDiagnosis= []
      this.refences= []
      this.question= []
      this.answer= []
      this.request1= false
      this.request2= false
      this.request3= false
      this.isCap= false
    }
  },
  data() {
    return {
      generallySeen: "",
      verdict: [],
      rispData: {
        mrCode: "",
        mr: {
          PathologyClass: ""
        },
        parentId: "",
        pathologyClass: ""
      },
      rispReport: {
        content: "",
        generallySeen: "",
        healthCardNo: "",
        jsonData: "",
        reference: "",
        remark: "",
        reportDoctor: "",
        reportTime: "",
        reviewDoctor: "",
        reviewTime: "",
        type: "",
        verdict: "",
        lensSeen: null
      },
      baseInfo: [],
      curDiagnosis: [],
      refences: [],
      question: [],
      answer: [],
      request1: false,
      request2: false,
      request3: false,
      isCap: false
    };
  },
  created() {
    // if(this.examId) this.getData()
  },
  watch: {
    examId: {
      handler(val) {
        this.resetData()
        if (val) {
          this.getData();
        }
      },
      immediate: true
    },
    isPrint(val) {
      if (val) {
        this.getData();
      }
    },
    requestStatus(val) {
      if (val) {
        if (this.isPrint) {
          // 打印
          this.print();
          this.$emit("update:is-print", false);
        }
        this.$emit("rispPrint",true)
      }else {
        this.$emit("rispPrint",false)
      }
    }
  },
  computed: {
    requestStatus() {
      return this.isCap
        ? this.request1 && this.request2 && this.request3
        : this.request1 && this.request2;
    },
    addPageShow() {
      /**
       * 组织学病理报告中  备注说明 参考文献 上传参考文献资料 都不存在时不展示
       * 妇科细胞学、非妇科细胞学、冰冻病理、会诊病理 参考文献 上传参考文献资料 都不存在时不展示
       */
      if (this.rispReport.type == "0") {
        if (
          this.rispReport.remark.trim() ||
          this.rispReport.reference.trim() ||
          this.refences.length > 0
        ) {
          return true;
        }
        // 组织学
      } else {
        if (this.rispReport.reference.trim() || this.refences.length > 0) {
          return true;
        }
      }

      return false;
    }
  },
  provide() {
    return {
      risp: this
    };
  },
};
</script>
<style lang="less" scoped>
.doctopdf-paging {
  width: 100%;
  padding: 10px;
  background-color: gray;
}
</style>