<template>
  <div v-loading="loading" class="clinical-data-wrapper">
    <el-tabs type="border-card">
      <el-tab-pane v-for="cd in clinicalDatas" :key="cd.ClinicalDataTrialSetId" :label="$i18n.locale === 'zh'
        ? cd.ClinicalDataSetName
        : cd.ClinicalDataSetEnName
        ">
        <!-- 格式化录入 -->
        <div v-if="cd.ClinicalUploadType === 0">
          <!-- 既往放疗史 -->
          <h4>{{ $t("trials:uploadClinicalData:title:pastTreatment") }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <!-- 新增 -->
            <el-button type="primary" icon="el-icon-plus" size="small" @click.native.prevent="
              addPreviousHistory(cd.ClinicalDataTrialSetId)
              ">
              {{ $t("common:button:new") }}
            </el-button>
          </div>

          <el-table :data="cd.ClinicalTableData.PreviousHistoryList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 放疗部位 -->
            <el-table-column prop="Position" :label="$t('trials:uploadClinicalData:table:bodyPart')" />
            <!-- 开始日期 -->
            <el-table-column prop="StartTime" :label="$t('trials:uploadClinicalData:table:beginDate')">
              <template slot-scope="scope">
                {{
                  scope.row.StartTime
                    ? moment(scope.row.StartTime).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column prop="EndTime" :label="$t('trials:uploadClinicalData:table:endDate')">
              <template slot-scope="scope">
                {{
                  scope.row.EndTime
                    ? moment(scope.row.EndTime).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>
            <!-- 病灶是否PD -->
            <el-table-column prop="IsPD" :label="$t('trials:uploadClinicalData:table:isPD')">
              <template slot-scope="scope">
                {{ $fd("IsPdEnum", scope.row.IsPD) }}
              </template>
            </el-table-column>
            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="120">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 1)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousHistory(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往手术史 -->
          <h4>{{ $t("trials:uploadClinicalData:title:pastSurgery") }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <el-button type="primary" icon="el-icon-plus" size="small"
              @click="addPreviousSurgery(cd.ClinicalDataTrialSetId)">
              {{ $t("common:button:new") }}
            </el-button>
          </div>
          <el-table :data="cd.ClinicalTableData.PreviousSurgeryList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 手术名称 -->
            <el-table-column prop="OperationName" :label="$t('trials:uploadClinicalData:table:surgeryName')" />
            <!-- 手术日期 -->
            <el-table-column prop="OperationTime" :label="$t('trials:uploadClinicalData:table:surgeryDate')">
              <template slot-scope="scope">
                {{
                  scope.row.OperationTime
                    ? moment(scope.row.OperationTime).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="200">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 2)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousSurgery(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往其他治疗史 -->
          <h4>{{ $t("trials:uploadClinicalData:title:others") }}</h4>
          <div v-if="allowAddOrEdit" style="text-align: right">
            <!-- 新增 -->
            <el-button type="primary" icon="el-icon-plus" size="small"
              @click="addPreviousOther(cd.ClinicalDataTrialSetId)">
              {{ $t("common:button:new") }}
            </el-button>
          </div>
          <el-table :data="cd.ClinicalTableData.PreviousOtherList" style="width: 100%">
            <el-table-column type="index" width="50" />
            <!-- 治疗类型 -->
            <el-table-column prop="TreatmentType" :label="$t('trials:uploadClinicalData:table:treatmentType')" />
            <!-- 开始日期 -->
            <el-table-column prop="StartTime" :label="$t('trials:uploadClinicalData:table:treatmentbeginDate')">
              <template slot-scope="scope">
                {{
                  scope.row.StartTime
                    ? moment(scope.row.StartTime).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column prop="EndTime" :label="$t('trials:uploadClinicalData:table:treatmentendDate')">
              <template slot-scope="scope">
                {{
                  scope.row.EndTime
                    ? moment(scope.row.EndTime).format("YYYY-MM-DD")
                    : ""
                }}
              </template>
            </el-table-column>

            <el-table-column v-if="allowAddOrEdit" :label="$t('common:action:action')" min-width="200">
              <template slot-scope="scope">
                <!-- 编辑 -->
                <el-button v-if="allowAddOrEdit" icon="el-icon-edit-outline" circle :title="$t('common:button:edit')"
                  size="small" @click.native.prevent="editRow(scope.row, 3)" />
                <!-- 移除 -->
                <el-button v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                " icon="el-icon-delete" circle :title="$t('common:button:delete')" size="small"
                  @click.native.prevent="deletePreviousOther(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- PDF录入 -->
        <div v-if="cd.ClinicalUploadType === 1">
          <div v-if="allowAddOrEdit" style="display:flex;align-items:center;justify-content: flex-end;">
            <!-- 下载模板 -->
            <el-button v-if="cd.Path" type="primary" icon="el-icon-download" size="small" :loading="downloadLoading"
              @click.native.prevent="handleDownloadTpl(cd)">
              {{ $t("trials:uploadClinicalData:button:downloadTemplate") }}
            </el-button>
            <div id="directoryInputWrapper" class="btn btn-link" style="
                position: relative;
                overflow: hidden;
                display: inline-block;
                margin-left:10px
              ">
              <!-- 新增 -->
              <el-button icon="el-icon-plus" type="primary" size="small" :disabled="btnLoading" :loading="btnLoading">
                {{ $t("common:button:new") }}
              </el-button>
              <input type="file" name="file" multiple ref="addFile" style="
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  height: 100%;
                  opacity: 0;
                  cursor: pointer;
                " :accept="faccept.join(',')" @change="
                  ($event) =>
                    beginScanFiles($event, cd.Id, cd.ClinicalDataTrialSetId)
                " />
            </div>
          </div>
          <div class="drag" ref="drag" @dragover="handleDragover"
            @drop="(e) => handleDrop(e, cd.Id, cd.ClinicalDataTrialSetId)">
            <el-table :data="cd.PDFFileList" style="width: 100%;min-height: 300px;">
              <el-table-column type="index" width="50" />
              <!-- 文件名称 -->
              <el-table-column prop="FileName" :label="$t('trials:uploadClinicalData:table:fileName')" width="250" />
              <!-- 文件大小 -->
              <el-table-column prop="Size" :label="$t('trials:uploadClinicalData:table:fileSize')" width="150">
                <template slot-scope="scope">
                  <span>{{
                    $FormatSize(scope.row.Size)
                  }}</span>
                </template>
              </el-table-column>
              <!-- 上传时间 -->
              <el-table-column prop="CreateTime" :label="$t('trials:uploadClinicalData:table:uploadedTime')"
                width="200" />
              <el-table-column :label="$t('common:action:action')" width="200">
                <template slot-scope="scope">
                  <!-- 预览 -->
                  <el-button icon="el-icon-view" circle :title="$t('trials:uploadClinicalData:action:preview')"
                    size="small" @click.native.prevent="preview(scope.row)" />
                  <!-- 移除 -->
                  <el-button v-if="allowAddOrEdit" icon="el-icon-delete" circle :title="$t('common:button:delete')"
                    size="small" @click.native.prevent="deleteFile(scope.row.Id)" />
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>
        <!-- PDF录入 -->
        <div v-if="cd.ClinicalUploadType === 2">
          <clinicalDataQuestions v-if="cd.ClinicalFromList.length > 0" :data="cd"
            :trial-clinical-id="cd.ClinicalDataTrialSetId" :is-viewer="false" :visit-id="subjectVisitId"
            :subject-id="data.SubjectId" :trial-id="trialId" :clinical-form-id="cd.ClinicalFromList[0].ClinicalFormId"
            :open-type="allowAddOrEdit ? 'edit' : 'look'" @close="getClinicalData" />
          <clinicalDataQuestions v-else :data="cd" :trial-clinical-id="cd.ClinicalDataTrialSetId"
            :is-viewer="!allowAddOrEdit" :visit-id="subjectVisitId" :subject-id="data.SubjectId" :trial-id="trialId"
            :open-type="'add'" @close="getClinicalData" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 既往放疗史 -->
    <el-dialog v-if="prVisible" :visible.sync="prVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:pastTreatment')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousRadiotherapy v-if="prVisible" :data="currentRow" :subject-visit-id="subjectVisitId"
        @closePRDialog="closePRDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 既往手术史  -->
    <el-dialog v-if="psVisible" :visible.sync="psVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:pastSurgery')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousSurgery v-if="psVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        @closePSDialog="closePSDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 既往其他治疗史 -->
    <el-dialog v-if="poVisible" :visible.sync="poVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:others')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousOther v-if="poVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        @closePODialog="closePODialog" @refresh="refresh" />
    </el-dialog>
    <!-- 上传文件 -->
    <el-dialog v-if="upVisible" :visible.sync="upVisible" :close-on-click-modal="false"
      :title="$t('trials:uploadClinicalData:title:uploadFile')" width="600px" append-to-body
      custom-class="base-dialog-wrapper">
      <PreviousFiles v-if="upVisible" :data="currentRow" :parent-data="data" :subject-visit-id="subjectVisitId"
        @closeUpDialog="closeUpDialog" @refresh="refresh" />
    </el-dialog>
    <!-- 预览文件 -->
    <el-dialog v-if="previewObj.visible" :visible.sync="previewObj.visible" :title="previewObj.fileName"
      :fullscreen="true" append-to-body custom-class="base-dialog-wrapper">
      <div class="base-modal-body" style="border: 2px solid #ccc; padding: 10px">
        <PreviewFile v-if="previewObj.visible" :file-path="previewObj.filePath" :file-type="previewObj.fileType" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  deleteReadingClinicalDataPDF,
  deletePreviousHistory,
  deletePreviousOther,
  deletePreviousSurgery,
  DownloadTrialClinicalFile,
  addOrUpdateReadingClinicalData,
  getCRCClinicalData,
} from "@/api/trials";
import PreviousRadiotherapy from "./previousRadiotherapy";
import PreviousSurgery from "./previousSurgery";
import PreviousOther from "./previousOther";
import PreviousFiles from "./previousFiles";
import clinicalDataQuestions from "@/components/clinicalDataQuestions";
import PreviewFile from "@/components/PreviewFile/index";
import moment from "moment";
import { readEntry } from '@/utils/index'
export default {
  name: "ClinicalData",
  components: {
    PreviousRadiotherapy,
    PreviousSurgery,
    PreviousOther,
    PreviousFiles,
    clinicalDataQuestions,
    PreviewFile,
  },
  props: {
    data: {
      type: Object,
      default() {
        return {};
      },
    },
    subjectVisitId: {
      type: String,
      required: true,
    },
    enumType: {
      type: Number,
      default: 0,
    },
    allowAddOrEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      faccept: [".pdf"],
      isShow: false,
      userTypeEnumInt: zzSessionStorage.getItem("userTypeEnumInt") * 1,
      loading: false,
      PreviousHistoryList: [],
      PreviousSurgeryList: [],
      PreviousOtherList: [],
      PreviousPDFList: [],
      fileList: [],
      addFileList: [],
      btnLoading: false,
      currentRow: {},
      prVisible: false,
      psVisible: false,
      poVisible: false,
      upVisible: false,
      trialId: this.$route.query.trialId,
      moment,
      downloadLoading: false,
      clinicalDatas: [],
      previewObj: { visible: false, filePath: "", fileType: "" },
    };
  },
  mounted() {
    this.getClinicalData();
  },
  methods: {
    handleDragover(e) {
      e.stopPropagation();
      e.preventDefault();
    },
    handleDrop(e, id, clinicalDataTrialSetId) {
      e.stopPropagation();
      e.preventDefault();
      this.beginScanFiles(e, id, clinicalDataTrialSetId, true)
    },
    async beginScanFiles(e, id, clinicalDataTrialSetId, isDrop = false) {
      this.currentRow = {
        Id: id,
        ClinicalDataTrialSetId: clinicalDataTrialSetId,
        SubjectId: this.data.SubjectId,
      };
      this.currentRow.TrialId = this.$route.query.trialId;
      var files = [];
      if (isDrop) {
        const items = e.dataTransfer.items;
        const allFiles = []; // 用于存储所有找到的文件

        // 遍历拖拽项
        for (const item of items) {
          const entry = item.webkitGetAsEntry(); // 获取文件系统入口
          if (entry) {
            const files = await readEntry(entry); // 递归读取入口内容
            allFiles.push(...files);
          }
        }
        files = allFiles
      } else {
        files = e.target.files
      }
      this.fileList = [];
      for (var i = 0; i < files.length; ++i) {
        const fileName = files[i].name;
        var extendName = fileName
          .substring(fileName.lastIndexOf("."))
          .toLocaleLowerCase();
        if (this.faccept.indexOf(extendName) !== -1) {
          let obj = {
            size: files[i].size,
            type: extendName.split('.')[1],
            file: files[i],
            fileType: files[i].type
          }
          this.fileList.push(obj);
        }
      }
      this.handleUploadFile();
      this.$refs.addFile.forEach(item => {
        item.value = null;
      })
    },
    async handleUploadFile() {
      this.btnLoading = true;
      this.loading = true;
      this.addFileList = [];
      try {
        for (var i = 0; i < this.fileList.length; ++i) {
          const file = await this.fileToBlob(this.fileList[i].file);
          var timestamp = Date.now();
          const res = await this.OSSclient.put(
            `/${this.trialId}/ClinicalData/${timestamp}_${this.fileList[i].file.name}`,
            file,
            {
              fileName: `${this.fileList[i].file.name}`,
              fileSize: file.size,
              fileType: this.fileList[i].fileType,
              uploadBatchId: this.$guid(),
              batchDataType: 4,
              trialId: this.trialId,
              subjectId: this.data.SubjectId,
              subjectVisitId: this.subjectVisitId
            }
          );
          this.addFileList.push({
            fileName: this.fileList[i].file.name,
            path: this.$getObjectName(res.url),
            url: this.$getObjectName(res.url),
            type: this.fileList[i].type,
            size: this.fileList[i].size,
          });
        }
        this.saveClinicalData();
      } catch (err) {
        console.log(err);
        this.btnLoading = false;
        this.loading = false;
      }
    },
    saveClinicalData() {
      this.btnLoading = true;
      this.loading = true;
      var param = {
        id: this.currentRow.Id,
        trialId: this.currentRow.TrialId,
        subjectId: this.currentRow.SubjectId,
        readingId: this.subjectVisitId,
        clinicalDataTrialSetId: this.currentRow.ClinicalDataTrialSetId,
        isVisit: true,
        deleteFileIds: [],
        addFileList: this.addFileList,
      };
      // if (this.studyData.StudyId) {
      //   param.StudyId = this.studyData.StudyId;
      // }
      addOrUpdateReadingClinicalData(param)
        .then((response) => {
          this.btnLoading = false;
          this.loading = false;
          // 刷新文件列表并关闭弹窗
          this.getClinicalData();
          this.$message.success(
            this.$t("trials:uploadClinicalData:message:uploadSuccessfully")
          );
        })
        .catch(() => {
          this.btnLoading = false;
          this.loading = false;
        });
    },
    getClinicalData() {
      this.loading = true;
      this.data.TrialId = this.$route.query.trialId;
      var param = {
        subjectVisitId: this.subjectVisitId,
        trialId: this.trialId,
        subjectId: this.data.SubjectId,
        isBaseLine: this.data.IsBaseLine,
      };
      getCRCClinicalData(param)
        .then((res) => {
          this.clinicalDatas = res.Result;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 打开编辑框
    editRow(row, type) {
      if (type === 1) {
        this.prVisible = true;
      } else if (type === 2) {
        this.psVisible = true;
      } else if (type === 3) {
        this.poVisible = true;
      }
      this.currentRow = { ...row };
      this.currentRow.TrialId = this.$route.query.trialId;
    },
    // 根据ID删除既往放疗史
    deletePreviousHistory(row) {
      this.$confirm(this.$t("trials:uploadedDicoms:message:deleteMes"), {
        type: "warning",
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true;
        deletePreviousHistory(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false;
            if (res.IsSuccess) {
              this.getClinicalData();
              this.$message.success(
                this.$t("trials:uploadedDicoms:message:deleteSuccessfully")
              );
              this.$emit("getList");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    // 根据ID删除既往手术史
    deletePreviousSurgery(row) {
      console.log(this.$route.query.trialId);
      this.$confirm(this.$t("trials:uploadedDicoms:message:deleteMes"), {
        type: "warning",
        distinguishCancelAndClose: true,
      }).then(() => {
        // row.Type = '既往手术史'
        this.loading = true;
        deletePreviousSurgery(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false;
            if (res.IsSuccess) {
              this.getClinicalData();
              this.$message.success(
                this.$t("trials:uploadedDicoms:message:deleteSuccessfully")
              );
              this.$emit("getList");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    // 根据ID删除既往其他资料史
    deletePreviousOther(row) {
      this.$confirm(this.$t("trials:uploadedDicoms:message:deleteMes"), {
        type: "warning",
        distinguishCancelAndClose: true,
      }).then(() => {
        // row.Type = '既往其他治疗史'
        this.loading = true;
        deletePreviousOther(
          this.$route.query.trialId,
          this.subjectVisitId,
          row.Id
        )
          .then((res) => {
            this.loading = false;
            if (res.IsSuccess) {
              this.getClinicalData();
              this.$message.success(
                this.$t("trials:uploadedDicoms:message:deleteSuccessfully")
              );
              this.$emit("getList");
            }
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    // 文件预览
    preview(row) {
      if (!row.Path) return;
      this.previewObj.fileName = row.FileName;
      this.previewObj.filePath = row.Path;
      this.previewObj.fileType = "pdf";
      this.previewObj.visible = true;
      // window.open(this.OSSclientConfig.basePath + path, '_blank')
    },
    addPreviousHistory(clinicalDataTrialSetId) {
      console.log(clinicalDataTrialSetId);
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId };
      this.currentRow.TrialId = this.$route.query.trialId;
      this.prVisible = true;
    },
    addPreviousSurgery(clinicalDataTrialSetId) {
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId };
      this.currentRow.TrialId = this.$route.query.trialId;
      this.psVisible = true;
    },
    addPreviousOther(clinicalDataTrialSetId) {
      this.currentRow = { ClinicalDataTrialSetId: clinicalDataTrialSetId };
      this.currentRow.TrialId = this.$route.query.trialId;
      this.poVisible = true;
    },
    // 关闭既往放疗史窗口并刷新列表
    closePRDialog() {
      this.prVisible = false;
      this.currentRow.TrialId = this.$route.query.trialId;
    },
    closePSDialog() {
      this.psVisible = false;
      this.currentRow.TrialId = this.$route.query.trialId;
    },
    closePODialog() {
      this.poVisible = false;
      this.currentRow.TrialId = this.$route.query.trialId;
    },
    closeUpDialog() {
      this.upVisible = false;
      this.currentRow.TrialId = this.$route.query.trialId;
    },
    refresh() {
      this.getClinicalData();
      this.$emit("getList");
    },
    // 添加文件
    addFile(id, clinicalDataTrialSetId) {
      this.currentRow = {
        Id: id,
        ClinicalDataTrialSetId: clinicalDataTrialSetId,
        SubjectId: this.data.SubjectId,
      };
      this.currentRow.TrialId = this.$route.query.trialId;
      this.upVisible = true;
    },
    // 删除文件
    deleteFile(id) {
      this.$confirm(this.$t("trials:uploadedDicoms:message:deleteMes"), {
        type: "warning",
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true;
        deleteReadingClinicalDataPDF(id)
          .then((res) => {
            this.loading = false;
            if (res.IsSuccess) {
              this.getClinicalData();
              this.$emit("getList");
              this.$message.success(
                this.$t("trials:uploadedDicoms:message:deleteSuccessfully")
              );
            }
          })
          .catch(() => {
            this.loading = false;
          });
      });
    },
    handleDownloadTpl(cd) {
      window.open(this.OSSclientConfig.basePath + cd.Path);
    },
  },
};
</script>
<style lang="scss">
.clinical-data-wrapper {
  .box-title {
    padding: 12px;
    margin-bottom: 10px;
    background-color: #dcdfe6;
  }
}
</style>
