<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 受试者编号 -->
        <el-form-item :label="$t('trials:subject:table:subjectId')">
          <el-input
            v-model="searchData.SubjectCode"
            style="width: 140px"
            clearable
          />
        </el-form-item>
        <!-- 患者编号 -->
        <el-form-item :label="$t('trials:uploadDicomList:table:pId')">
          <el-input
            v-model="searchData.PatientIdStr"
            style="width: 140px"
            clearable
          />
        </el-form-item>
        <!-- 性别 -->
        <el-form-item :label="$t('trials:subject:table:gender')">
          <el-select v-model="searchData.SubjectSex" clearable>
            <el-option
              v-for="item of $d.Sex"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 是否绑定访视 -->
        <el-form-item
          :label="$t('trials:study:button:bindVisit')"
          v-if="activeName === 'notSubmit'"
        >
          <el-select v-model="searchData.IsBindedVisit" clearable>
            <el-option
              v-for="item of $d.YesOrNo"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 检查日期 -->
        <el-form-item :label="$t('trials:audit: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']"
          >
          </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-button
            type="primary"
            @click="automaticBind"
            :loading="automaticBindLoading"
            v-if="activeName === 'notSubmit'"
          >
            {{ $t("trials:study:button:automaticBind") }}
          </el-button> -->
        </el-form-item>
      </el-form>
    </template>

    <!-- 检查列表 :default-sort="{ prop: 'StudyTime', order: 'descending' }" -->
    <template slot="main-container">
      <el-table
        v-loading="loading"
        v-adaptive="{ bottomOffset: 80 }"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <el-table-column type="index" width="30" />
        <!-- 受试者编号 -->
        <el-table-column
          prop="SubjectCode"
          :label="$t('trials:subject:table:subjectId')"
          show-overflow-tooltip
          sortable="custom"
          min-width="120"
        />
        <!-- 患者编号 -->
        <el-table-column
          prop="PatientIdStr"
          :label="$t('trials:uploadDicomList:table:pId')"
          show-overflow-tooltip
          min-width="100"
          sortable="custom"
        >
        </el-table-column>
        <!--患者姓名 -->
        <el-table-column
          prop="PatientName"
          :label="$t('trials:uploadDicomList:table:patientName')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 性别 -->
        <el-table-column
          prop="SubjectSex"
          :label="$t('trials:subject:table:gender')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        >
          <template slot-scope="scope">
            <span>{{ $fd("Sex", scope.row.SubjectSex) }}</span>
          </template>
        </el-table-column>
        <!-- 检查设备 -->
        <el-table-column
          prop="Modalities"
          :label="$t('trials:studyList:table:modality')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 检查类型 -->
        <el-table-column
          prop="ModalityForEdit"
          :label="$t('trials:audit:table:modality')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
          v-if="activeName === 'submit'"
        />
        <!-- 检查描述 -->
        <el-table-column
          prop="Description"
          :label="$t('trials:inspection:table:studyDescription')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 序列数量 -->
        <el-table-column
          prop="SeriesCount"
          :label="$t('trials:audit:table:seriesCount')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 图像数量 -->
        <el-table-column
          prop="InstanceCount"
          :label="$t('trials:audit:table:instanceCount')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 检查日期 -->
        <el-table-column
          prop="StudyTime"
          :label="$t('trials:audit:table:studyDate')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 访视 -->
        <el-table-column
          prop="VisitName"
          :label="$t('trials:auditRecord:table:visit')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- 状态 -->
        <el-table-column
          prop="SubmitState"
          :label="$t('trials:trials-list:table:status')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.SubmitState === null">-</span>
            <el-tag
              v-else-if="scope.row.SubmitState * 1 === 0"
              type="warning"
              >{{ $fd("SubmitState", scope.row.SubmitState * 1) }}</el-tag
            >
            <el-tag v-else-if="scope.row.SubmitState * 1 === 1" type="danger">{{
              $fd("SubmitState", scope.row.SubmitState * 1)
            }}</el-tag>
            <el-tag v-else-if="scope.row.SubmitState * 1 === 2">{{
              $fd("SubmitState", scope.row.SubmitState * 1)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('common:action:action')"
          min-width="200"
          fixed="right"
          v-if="
            hasPermi([
              'trials:trials-panel:study:view',
              'trials:trials-panel:study:editVisit',
              'trials:trials-panel:study:delStudy',
            ])
          "
        >
          <template slot-scope="scope">
            <!-- 查看 -->
            <el-button
              circle
              icon="el-icon-info"
              @click="handleViewStudy(scope.row)"
              v-hasPermi="['trials:trials-panel:study:view']"
              :title="$t('trials:studyList:button:view')"
            />
            <!-- 修改访视 -->
            <el-button
              circle
              icon="el-icon-edit-outline"
              @click="editVisitFn(scope.row)"
              v-if="activeName === 'notSubmit'"
              v-hasPermi="['trials:trials-panel:study:editVisit']"
              :title="
                scope.row.SubjectVisitId
                  ? $t('trials:study:button:editVisit')
                  : $t('trials:study:button:bindVisit')
              "
            />
            <!-- 移除 -->
            <el-button
              circle
              icon="el-icon-delete"
              @click.stop="remove(scope.row)"
              class="detail"
              v-hasPermi="['trials:trials-panel:study:delStudy']"
              :disabled="!scope.row.SubjectVisitId"
              v-if="activeName === 'notSubmit'"
              :title="$t('common:button:remove')"
            />
            <!-- 诊断报告 -->
            <el-button
              circle
              icon="el-icon-document"
              @click.stop="report(scope.row)"
              v-hasPermi="['trials:trials-panel:study:view']"
              :title="$t('trials:inspection:button:diagnosticReport')"
              disabled
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        class="page"
        :total="total"
        :page.sync="searchData.PageIndex"
        :limit.sync="searchData.PageSize"
        @pagination="getList"
      />
    </template>
    <editVisit
      v-if="editVisitVisible"
      :visible.sync="editVisitVisible"
      :data="editVisitMessage"
      @getList="getList"
    />
  </BaseContainer>
</template>
<script>
import BaseContainer from "@/components/BaseContainer";
import Pagination from "@/components/Pagination";
import editVisit from "./edit-visit";
import { getToken } from "@/utils/auth";
import {
  getPatientStudyBeforeConfirmList,
  getTrialPatientStudyList,
  autoBindingPatientStudyVisit,
} from "@/api/trials/study.js";
import { updateSubjectVisitStudyBinding } from "@/api/trials/visit.js";

const defaultSearchData = () => {
  return {
    SubjectCode: null,
    PatientIdStr: null,
    PatientSex: null,
    SubjectSex: null,
    BeginStudyTime: null,
    EndStudyTime: null,
    IsBindedVisit: null,
    Asc: true,
    SortField: null,
    PageIndex: 1,
    PageSize: 20,
  };
};
export default {
  name: "studyList",
  components: {
    BaseContainer,
    Pagination,
    editVisit,
  },
  props: {
    activeName: {
      required: true,
      default: "notSubmit",
    },
  },
  data() {
    return {
      // 搜索
      searchData: defaultSearchData(),
      dateValue: [],
      // 列表
      list: [],
      loading: false,
      total: 0,

      // 修改访视相关
      editVisitVisible: false,
      editVisitMessage: {},
      // 自动绑定
      automaticBindLoading: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    report() {},
    // 移除检查与访视绑定关系
    async remove(item) {
      try {
        let confirm = await this.$confirm(
          this.$t("trials:sitesList:message:removeSite"),
          {
            type: "warning",
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t("common:button:confirm"),
            cancelButtonText: this.$t("recompose:button:cancel"),
          }
        );
        if (confirm !== "confirm") return;
        let data = {
          isAdd: false,
          TrialId: this.$route.query.trialId,
          SubjectId: item.SubjectId,
          SubjectVisitId: item.SubjectVisitId,
          ScpStudyId: item.StudyId,
        };
        let res = await updateSubjectVisitStudyBinding(data);
        if (res.IsSuccess) {
          this.getList();
          this.$message.success(this.$t("common:message:removedSuccessfully"));
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 自动绑定
    async automaticBind() {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
        };
        this.automaticBindLoading = true;
        let res = await autoBindingPatientStudyVisit(data);
        this.automaticBindLoading = false;
        if (res.IsSuccess) {
          this.$message.success(
            this.$t("trials:study:message:bindSuccessfully")
          );
          this.getList();
        }
      } catch (err) {
        this.automaticBindLoading = false;
        console.log(err);
      }
    },
    // 修改访视
    editVisitFn(item) {
      this.editVisitVisible = true;
      this.editVisitMessage = item;
      this.editVisitMessage.TrialId = this.$route.query.trialId;
    },
    // 获取检查列表数据
    async getList() {
      let data = {};
      Object.keys(this.searchData).forEach((key) => {
        data[key] = this.searchData[key];
      });
      data.TrialId = this.$route.query.trialId;
      if (this.dateValue && this.dateValue[0] && this.dateValue[1]) {
        data.BeginStudyTime = this.$moment(this.dateValue[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        data.EndStudyTime = this.$moment(this.dateValue[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      } else {
        data.BeginStudyTime = null;
        data.EndStudyTime = null;
      }
      try {
        let res = null;
        this.loading = true;
        if (this.activeName === "notSubmit") {
          res = await getPatientStudyBeforeConfirmList(data);
        } else {
          res = await getTrialPatientStudyList(data);
        }
        this.loading = false;
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
        }
      } catch (err) {
        this.loading = false;
        console.log(err);
      }
    },
    // 查看影像
    handleViewStudy(row) {
      let type = "Study";
      if (this.activeName === "notSubmit") {
        type = "Patient";
      }
      var token = getToken();
      const routeData = this.$router.resolve({
        path: `/showdicom?studyId=${row.StudyId}&TokenKey=${token}&type=${type}`,
      });
      var newWindow = window.open(routeData.href, "_blank");
      this.$emit("setOpenWindow", newWindow);
      this.$setOpenWindow(newWindow);
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1;
      this.getList();
    },
    // 重置
    handleReset() {
      this.reset();
      this.getList();
    },
    // 初始化
    reset() {
      this.searchData = defaultSearchData();
      this.dateValue = [];
    },
    // 排序
    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>
<style lang="scss" scoped>
</style>