<template>
  <el-dialog
    :visible.sync="visible"
    :close-on-click-modal="false"
    :fullscreen="true"
    custom-class="upload-dialog"
    :before-close="beforeCloseStudyDig"
  >
    <span slot="title"
      >{{ $t("trials:hirVisit:button:editStudy") }}（{{
        $t("trials:globalReview:title:subject")
      }}{{ data.SubjectCode }}，{{ $t("trials:studyList:table:visit") }}：{{
        data.VisitName
      }}）
    </span>
    <!--当前检查--->
    <div class="topTable">
      <div class="title">
        <span>{{ $t("trials:hirVisit:titleMessage:currentStudy") }}</span>
        <!-- <div class="btnBox">
          <el-button type="primary" @click="submit">
            {{ $t("trials:seletctedReviews:button:confirm") }}
          </el-button>
          <el-button @click="preview">
            {{ $t("trials:readingPeriod:verify:title:preview") }}
          </el-button>
        </div> -->
      </div>
      <!--当前检查列表  @selection-change="handleSelectChange"--->
      <el-table
        ref="addTrialsList"
        v-loading="topLoading"
        :data="topList"
        stripe
        height="30vh"
        @sort-change="handleSortByColumn"
        :default-sort="{ prop: 'StudyTime', order: 'ascending' }"
      >
        <!-- <el-table-column type="selection" align="center" width="45" /> -->
        <!--患者编号-->
        <el-table-column
          align="center"
          prop="PatientIdStr"
          :label="$t('trials:uploadDicomList:table:pId')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--检查类型-->
        <el-table-column
          align="center"
          prop="Modalities"
          :label="$t('trials:audit:table:modality')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--序列数量-->
        <el-table-column
          align="center"
          prop="SeriesCount"
          :label="$t('trials:audit:table:seriesCount')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--图像数量-->
        <el-table-column
          align="center"
          prop="InstanceCount"
          :label="$t('trials:audit:table:instanceCount')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--检查日期-->
        <el-table-column
          align="center"
          prop="StudyTime"
          :label="$t('trials:audit:table:studyDate')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--所属访视-->
        <el-table-column
          align="center"
          prop="VisitName"
          :label="$t('trials:hirVisit:table:ownershipVisit')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--操作-->
        <el-table-column
          :label="$t('common:action:action')"
          width="300"
          class-name="actionBox"
        >
          <template slot-scope="scope">
            <!-- 查看 -->
            <el-button
              circle
              icon="el-icon-view"
              :title="$t('trials:enrolledReviews:button:view')"
              @click.stop="detail(scope.row, 'top')"
            />
            <!-- 移除 -->
            <el-button
              circle
              icon="el-icon-delete"
              :title="$t('common:button:remove')"
              @click.stop="remove(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--可选检查-->
    <div class="bottomTable">
      <p>{{ $t("trials:hirVisit:titleMessage:optionalStudy") }}</p>
      <div class="form">
        <el-form :inline="true" class="base-search-form">
          <!-- 患者编号 -->
          <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
            <el-input v-model="searchData.PatientIdStr" style="width: 100px"  clearable/>
          </el-form-item>
          <!-- 检查日期 -->
          <el-form-item :label="$t('trials:uploadedDicoms:table:studyDate')">
            <el-date-picker
              v-model="dateValue"
              type="datetimerange"
              range-separator="-" 
              :start-placeholder="$t('trials:uploadClinicalData:table:beginDate')"
              :end-placeholder="$t('trials:uploadClinicalData:table:endDate')"
              :default-time="['00:00:00', '23:59:59']"
              clearable
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <!-- 查询 -->
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
            >
              {{ $t("common:button:search") }}
            </el-button>
            <!-- 重置 -->
            <el-button
              type="primary"
              icon="el-icon-refresh-left"
              @click="handleReset"
            >
              {{ $t("common:button:reset") }}
            </el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button icon="el-icon-refresh" @click="addTrials">
          {{ $t("trials:readingReport:button:refresh") }}
        </el-button> -->
      </div>
      <el-table
        ref="bottomList"
        v-loading="bottomLoading"
        v-adaptive="{ bottomOffset: 60 }"
        :data="bottomList"
        stripe
        height="100"
        @selection-change="handleSelectChange"
        @sort-change="handleSortByColumn"
        :default-sort="{ prop: 'StudyTime', order: 'ascending' }"
      >
        <el-table-column type="selection" align="center" width="45" />
        <!--患者编号-->
        <el-table-column
          align="center"
          prop="PatientIdStr"
          :label="$t('trials:uploadDicomList:table:pId')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--检查类型-->
        <el-table-column
          align="center"
          prop="Modalities"
          :label="$t('trials:audit:table:modality')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--序列数量-->
        <el-table-column
          align="center"
          prop="SeriesCount"
          :label="$t('trials:audit:table:seriesCount')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--图像数量-->
        <el-table-column
          align="center"
          prop="InstanceCount"
          :label="$t('trials:audit:table:instanceCount')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--检查日期-->
        <el-table-column
          align="center"
          prop="StudyTime"
          :label="$t('trials:audit:table:studyDate')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--所属访视-->
        <el-table-column
          align="center"
          prop="VisitName"
          :label="$t('trials:hirVisit:table:ownershipVisit')"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <!--操作-->
        <el-table-column
          :label="$t('common:action:action')"
          width="300"
          class-name="actionBox"
        >
          <template slot-scope="scope">
            <!-- 查看 -->
            <el-button
              circle
              icon="el-icon-view"
              :title="$t('trials:enrolledReviews:button:view')"
              @click.stop="detail(scope.row, 'bottom')"
            />
            <!-- 添加 -->
            <el-button
              circle
              icon="el-icon-plus"
              :title="$t('common:button:add')"
              @click.stop="add(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-dialog>
</template>
<script>
import {
  getCurrentVisitPatientStudyList,
  getPatientOtherStudyList,
  updateSubjectVisitStudyBinding,
} from "@/api/trials/visit.js";
import { getToken } from "@/utils/auth";
const defaultSearchData = () => {
  return {
    EarliestStudyTime: null,
    LatestStudyTime: null,
    Asc: true,
    SortField: "StudyTime",
    PatientIdStr: null,
  };
};
export default {
  name: "editStudyList",
  props: {
    visible: {
      required: true,
      default: false,
    },
    data: {
      required: true,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      // 可选检查查询
      searchData: defaultSearchData(),
      dateValue: [],
      // 可选检查列表
      bottomList: [],
      bottomLoading: false,
      // 当前检查列表
      topList: [],
      topLoading: false,
    };
  },
  created() {
    this.getTopList();
    this.getBottomList();
  },
  methods: {
    // 获取当前检查列表
    async getTopList() {
      try {
        let data = {
          SujectVisitId: this.data.SubjectVisitId,
        };
        this.topLoading = true;
        let res = await getCurrentVisitPatientStudyList(data);
        this.topLoading = false;
        if (res.IsSuccess) {
          this.topList = res.Result;
        }
      } catch (err) {
        this.topLoading = false;
        console.log(err);
      }
    },
    // 获取可选检查列表
    async getBottomList() {
      let data = {};
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key];
      });
      data.PatientIdList = this.data.PatientList.map((item) => item.PatientId);
      data.SujectVisitId = this.data.SubjectVisitId;
      data.TrialId = this.$route.query.trialId;
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.EarliestStudyTime = this.$moment(this.dateValue[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        data.LatestStudyTime = this.$moment(this.dateValue[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      try {
        this.bottomLoading = true;
        let res = await getPatientOtherStudyList(data);
        this.bottomLoading = false;
        if (res.IsSuccess) {
          this.bottomList = res.Result;
        }
      } catch (err) {
        console.log(err);
        this.bottomLoading = false;
      }
    },
    // 排序
    handleSortByColumn(sort) {
      this.searchData.SortField = sort.prop;
      if (sort.order === "ascending") this.searchData.Asc = true;
      if (sort.order === "descending") this.searchData.Asc = false;
      if (!sort.order) this.searchData.SortField = null;
      this.getBottomList();
    },
    // 修改检查与访视绑定关系
    async setRelation(item, isAdd = true) {
      try {
        let confirmMessage = "trials:sitesList:message:removeSite";
        if (isAdd) {
          confirmMessage = "trials:customSite:message:add";
        }
        let confirm = await this.$confirm(this.$t(confirmMessage), {
          type: "warning",
          distinguishCancelAndClose: true,
          confirmButtonText: this.$t("common:button:confirm"),
          cancelButtonText: this.$t("recompose:button:cancel"),
        });
        if (confirm !== "confirm") return;
        let data = {
          isAdd,
          SubjectId: this.data.SubjectId,
          SubjectVisitId: this.data.SubjectVisitId,
          ScpStudyId: item.SCPStudyId,
          TrialId: this.$route.query.trialId,
        };
        let res = await updateSubjectVisitStudyBinding(data);
        if (res.IsSuccess) {
          this.getTopList();
          this.getBottomList();
          let message = "common:message:addedSuccessfully";
          if (!isAdd) {
            message = "common:message:removedSuccessfully";
          }
          this.$message.success(this.$t(message));
          this.$emit("getList");
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 关闭弹框
    beforeCloseStudyDig() {
      this.$setOpenWindow();
      this.$emit("update:visible", false);
    },
    // 预览
    preview() {},
    // 确认
    submit() {},
    // 查看
    detail(item, key) {
      var token = getToken();
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${item.SCPStudyId}&TokenKey=${token}&type=Patient`,
      });
      var newWindow = window.open(routeData.href, "_blank");
      this.$emit("setOpenWindow", newWindow);
      this.$setOpenWindow(newWindow);
    },
    // 当前检查移除
    remove(item) {
      this.setRelation(item, false);
    },
    // 可选检查查询
    handleSearch() {
      this.getBottomList();
    },
    // 可选检查重置
    handleReset() {
      this.reset();
      this.getBottomList();
    },
    // 初始化查询条件
    reset() {
      this.searchData = defaultSearchData();
      this.dateValue = [];
      this.$refs.bottomList.clearSort();
    },
    // 可选检查表格选择
    handleSelectChange() {},
    // 可选检查添加
    add(item) {
      this.setRelation(item, true);
    },
    addTrials() {},
  },
};
</script>
<style lang="scss" scoped>
.topTable {
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.bottomTable {
  .form {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>