<template>
  <BaseContainer>
    <template slot="search-container">
      <el-form :inline="true">
        <!--患者信息-->
        <el-form-item :label="$t('trials:visit:crcUpload:uploadDicomPacs:search:patientInfo')
          " prop="TrialSiteKeyInfo">
          <el-input v-model="searchData.PatientInfo" size="small" clearable style="width: 190px" :placeholder="$t('trials:visit:crcUpload:uploadDicomPacs:search:placeholder')
            " />
        </el-form-item>
        <!--检查技术-->
        <el-form-item :label="$t('trials:visit:crcUpload:uploadDicomPacs:search:modalities')
          " prop="CalledAE">
          <el-select v-model="searchData.Modalities" clearable>
            <el-option v-for="item of DicomModalityList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <!--检查日期-->
        <el-form-item :label="$t('trials:visit:crcUpload:uploadDicomPacs:search:studyTime')">
          <el-date-picker v-model="datetimerange" type="datetimerange" :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss" @change="handleDatetimeChange" />
        </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-button type="primary" icon="el-icon-plus" :disabled="tableSelectData.length <= 0" @click="handleAddList">
            {{ $t("common:button:add") }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="main-container">
      <el-table v-loading="loading" :data="list" class="table" @selection-change="handleSelectChange"
        @sort-change="handleSortByColumn" :default-sort="{ prop: 'StudyTime', order: 'descending' }">
        <el-table-column type="selection" align="center" width="45" />
        <el-table-column type="index" width="50" />
        <!--患者信息-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:patientMessage')
          " prop="PatientIdStr" min-width="140" show-overflow-tooltip sortable="custom">
          <template slot="header">
            <el-tooltip placement="top">
              <div slot="content">
                {{ $t("trials:uploadDicomList:table:pId") }}<br />
                {{ $t("trials:uploadDicomList:table:patientName") }}<br />
                {{ $t("trials:uploadDicomList:table:pInfo") }}
              </div>
              <span>{{ $t("trials:uploadDicomList:table:patientInfo") }}</span>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <div style="line-height: 15px">
              <div>
                <span v-if="scope.row.PatientIdStr"><span style="font-weight: 500">PID: </span>{{ scope.row.PatientIdStr
                }}</span>
                <span v-else style="color: #f44336">N/A</span>
              </div>
              <div>
                <span :class="[scope.row.PatientName ? '' : 'colorOfRed']">
                  {{ scope.row.PatientName ? scope.row.PatientName : "N/A" }}
                </span>
              </div>
              <div>
                <span :class="[scope.row.PatientSex ? '' : 'colorOfRed']">
                  {{ scope.row.PatientSex ? scope.row.PatientSex : "N/A" }},
                </span>

                <span :class="[scope.row.PatientAge ? '' : 'colorOfRed']">
                  {{ scope.row.PatientAge ? scope.row.PatientAge : "N/A" }},
                </span>

                <span :class="[scope.row.PatientBirthDate ? '' : 'colorOfRed']">
                  {{
                    scope.row.PatientBirthDate
                      ? scope.row.PatientBirthDate
                      : "N/A"
                  }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <!--检查申请号-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:accNumber')" prop="AccessionNumber"
          min-width="90" show-overflow-tooltip sortable="custom" />
        <!--检查模态-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:modalities')" prop="Modalities"
          min-width="120" show-overflow-tooltip sortable="custom" />
        <!--检查部位-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:bodyPartExamined')
          " prop="BodyPartExamined" min-width="120" show-overflow-tooltip sortable="custom" />
        <!--检查描述-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:description')
          " prop="Description" min-width="160" show-overflow-tooltip sortable="custom" />
        <!--序列数量-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:seriesCount')
          " prop="SeriesCount" show-overflow-tooltip sortable="custom" />
        <!--图像数量-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:instanceCount')
          " prop="InstanceCount" show-overflow-tooltip sortable="custom" />
        <!--检查日期-->
        <el-table-column :label="$t('trials:visit:crcUpload:uploadDicomPacs:table:studyTime')" prop="StudyTime"
          min-width="160" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('common:action:action')" fixed="right">
          <template slot-scope="scope">
            <el-button icon="el-icon-view" :title="$t('trials:uploadedDicoms:action:preview')" circle
              @click="handleViewStudy(scope.row)" />
            <!-- 添加 -->
            <el-button :title="$t('common:button:add')" @click="handleAdd(scope.row)" icon="el-icon-plus" circle />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>
  </BaseContainer>
</template>
<script>
import {
  getVisitPatientStudyFilterList,
  submitVisitStudyBinding,
  getDicomModalityList,
  verifyPacsImage,
} from "@/api/trials";
import BaseContainer from "@/components/BaseContainer";
import Pagination from "@/components/Pagination";
import moment from "moment";
import { getToken } from '@/utils/auth'
const searchDataDefault = () => {
  return {
    PatientInfo: null,
    EarliestStudyTime: null,
    LatestStudyTime: null,
    Modalities: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: true,
    SortField: "StudyTime",
  };
};
export default {
  components: { BaseContainer, Pagination },
  props: {
    subjectVisitId: {
      type: String,
      required: true,
    },
    subjectId: {
      type: String,
      required: true,
    },
    relationInfo: {
      required: true,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      moment,
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      datetimerange: [],
      tableSelectData: [],
      DicomModalityList: [],
      SCPStudyIdList: [],
      ReUploadSCPStudyIdList: [],
      warningArr: [],
    };
  },
  created() {
    this.getList();
    this.getDicomModalityList();
  },
  methods: {
    // 预览单个检查影像
    handleViewStudy(row) {
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${row.SCPStudyId}&TokenKey=${token}&type=Study&isPacs=1`,
      })
      window.open(routeData.href, '_blank')
    },
    // 校验上传数据
    async verifyPacsImage(arr) {
      try {
        this.warningArr = [];
        this.ReUploadSCPStudyIdList = [];
        this.SCPStudyIdList = [];
        let data = {
          TrialId: this.$route.query.trialId,
          SubjectVisitId: this.subjectVisitId,
          SubjectId: this.subjectId,
          ScpStudyIdList: arr,
        };
        this.loading = true;
        let res = await verifyPacsImage(data);
        if (res.IsSuccess) {
          for (let i = 0; i < res.Result.length; i++) {
            let item = res.Result[i];
            if (item.AllowReUpload) {
              this.ReUploadSCPStudyIdList.push(item.SCPStudyId);
              continue;
            }
            if (item.AllowUpload) {
              this.SCPStudyIdList.push(item.SCPStudyId);
              continue;
            }
            if (!item.AllowUpload && !item.AllowReUpload) {
              // let data = this.tableSelectData.find(
              //   (d) => d.SCPStudyId === item.SCPStudyId
              // );
              // this.warningArr.push(Object.assign({}, data, item));
              this.warningArr.push(item);
              continue;
            }
          }
          if (this.warningArr.length <= 0) {
            this.submitVisitStudyBinding(
              this.SCPStudyIdList,
              this.ReUploadSCPStudyIdList
            );
          } else {
            var li = this.warningArr.map((item) => {
              return `<li>${item.ErrorMesseage}</li>`;
            });
            const content = `
                        <div>
                        <ol>
                        ${li.join("")}
                        </ol>
                        </div>`;
            this.$alert(
              content,
              this.$t("trials:uploadDicomList:label:prompt"),
              {
                confirmButtonText: this.$t(
                  "trials:uploadDicomList:label:confirm"
                ),
                dangerouslyUseHTMLString: true,
                callback: (action) => { },
              }
            );
            this.loading = false;
          }
        } else {
          this.loading = false;
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 获取检查技术列表
    async getDicomModalityList() {
      try {
        let params = {
          TrialId: this.$route.query.trialId,
        };
        let res = await getDicomModalityList(params);
        if (res.IsSuccess) {
          this.DicomModalityList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleAddList() {
      if (this.tableSelectData.length < 0)
        return this.$message.warning(
          this.$t("trials:visit:crcUpload:uploadDicomPacs:message:notCheck")
        );
      let arr = this.tableSelectData.map((item) => item.SCPStudyId);
      this.verifyPacsImage(arr);
    },
    handleAdd(row) {
      let arr = [row.SCPStudyId];
      this.verifyPacsImage(arr);
    },
    // 添加检查
    async submitVisitStudyBinding(ScpStudyIdList, ReUploadSCPStudyIdList) {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
          SubjectVisitId: this.subjectVisitId,
          SubjectId: this.subjectId,
          ScpStudyIdList,
          ReUploadSCPStudyIdList,
        };
        this.loading = true;
        let res = await submitVisitStudyBinding(data);
        this.loading = false;
        if (res.IsSuccess) {
          let arr = [...ScpStudyIdList, ...ReUploadSCPStudyIdList];
          let tableSelectData = this.list.filter((item) =>
            arr.includes(item.SCPStudyId)
          );
          let flag = tableSelectData.some((item) => {
            return (
              item.Modalities === "PET-CT" ||
              item.Modalities === "CT、PT" ||
              item.Modalities === "PT、CT"
            );
          });
          if (flag && this.relationInfo.IsHaveStudyClinicalData) {
            this.$emit("petDataTip", true);
          }
          this.getList();
          this.$emit("getList");
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 表格选择
    handleSelectChange(selection) {
      // console.log(selection, "handleSelectChange");
      this.tableSelectData = selection;
    },
    getList() {
      this.loading = true;
      let data = {
        SubjectVisitId: this.subjectVisitId,
        SubjectId: this.subjectId,
        ...this.searchData,
      };
      getVisitPatientStudyFilterList(data)
        .then((res) => {
          this.loading = false;
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleDatetimeChange(val) {
      if (val) {
        this.searchData.EarliestStudyTime = val[0];
        this.searchData.LatestStudyTime = val[1];
      } else {
        this.searchData.EarliestStudyTime = "";
        this.searchData.LatestStudyTime = "";
      }
    },
    handleSearch() {
      this.searchData.PageIndex = 1;
      this.getList();
    },
    // 重置列表查询
    handleReset() {
      this.datetimerange = null;
      this.handleDatetimeChange();
      this.searchData = searchDataDefault();
      this.getList();
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === "ascending") {
        this.searchData.Asc = true;
      } else {
        this.searchData.Asc = false;
      }
      this.searchData.SortField = column.prop;
      this.searchData.PageIndex = 1;
      this.getList();
    },
  },
};
</script>